: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): remove the persons ORM fallback, gate, and middleware (#65968)
Nick Best781e18116562
diff --git a/.env.development b/.env.developmentindex 52b2b8c1d4ec..27e9a304a15e 100644--- a/.env.development+++ b/.env.development@@ -69,8 +69,8 @@ POSTHOG_SCHEMA_RESTORE_IN_DEV=auto# personhog (Rust person/group service)PERSONHOG_ADDR=127.0.0.1:50052+# Node CDP/error-tracking servers require this to be true (separate from the removed Django gate).PERSONHOG_ENABLED=true-PERSONHOG_ROLLOUT_PERCENTAGE=100# DebugPYDEVD_DISABLE_FILE_VALIDATION=1diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.ymlindex bbf39fc10275..a983fd828017 100644--- a/.github/workflows/ci-e2e-playwright.yml+++ b/.github/workflows/ci-e2e-playwright.yml@@ -500,6 +500,11 @@ jobs:sqlx migrate run -D "$CYCLOTRON_NODE_DATABASE_URL" --source rust/cyclotron-node-migrations/python manage.py migrate_clickhouse 2>&1++ # Person/group reads go through personhog (no ORM fallback), so the replica+ # and router must be running before setup_dev creates demo persons.+ COMPOSE_FILE=docker-compose.dev.yml COMPOSE_PROFILES=ingestion bin/ci-wait-for-docker launch personhog-replica personhog-router+python manage.py setup_dev- name: Source celery queuesdiff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.ymlindex fa6f4afc92ff..6823ea0beaa8 100644--- a/.github/workflows/ci-mcp.yml+++ b/.github/workflows/ci-mcp.yml@@ -250,6 +250,8 @@ jobs:SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'PERSONS_DB_WRITER_URL: 'postgres://posthog:posthog@localhost:5432/posthog_persons'+ PERSONHOG_ADDR: 'localhost:50052'+ POSTHOG_PERSONS_DB_NAME: 'posthog_persons'REDIS_URL: 'redis://localhost'CLICKHOUSE_HOST: 'localhost'CLICKHOUSE_SECURE: 'False'@@ -496,6 +498,13 @@ jobs:exit 1fi+ - name: Start personhog services+ shell: bash+ env:+ COMPOSE_FILE: docker-compose.dev.yml+ COMPOSE_PROFILES: ingestion+ run: bin/ci-wait-for-docker launch personhog-replica personhog-router+- name: Seed test datarun: python manage.py generate_demo_data --n-clusters 10 --days-past 7 --days-future 0 --skip-materialization --skip-flag-sync --skip-user-product-listdiff --git a/.semgrep/rules/no-direct-persons-db-orm.yaml b/.semgrep/rules/no-direct-persons-db-orm.yamlindex 4d844901e1fa..103279e83289 100644--- a/.semgrep/rules/no-direct-persons-db-orm.yaml+++ b/.semgrep/rules/no-direct-persons-db-orm.yaml@@ -1,13 +1,12 @@rules:- id: no-direct-persons-db-ormmessage: >-- Do not query persons DB models via the Django ORM. Use the personhog- client helpers in `posthog/models/person/util.py` (e.g.- `get_person_by_uuid`, `get_persons_by_distinct_ids`) and- `posthog/models/group_type_mapping.py` (`get_group_types_for_project`).- These route through the personhog gRPC service with ORM fallback.- When adding new access patterns, follow the `_personhog_routed()`- pattern in `posthog/models/person/util.py`.+ Do not query persons DB models via the Django ORM — all calls must+ route through the personhog gRPC service. Use the client helpers in+ `posthog/models/person/util.py` (e.g. `get_person_by_uuid`,+ `get_persons_by_distinct_ids`) and `posthog/models/group_type_mapping.py`+ (`get_group_types_for_project`). When adding new access patterns, follow+ the `_personhog_routed()` pattern in `posthog/models/person/util.py`.See `posthog/personhog_client/README.md` for client detailsor reach out to #team-ingestion for more information.severity: WARNING@@ -23,7 +22,7 @@ rules:exclude:# personhog client implementation- '**/posthog/personhog_client/**'- # Routing helpers — intentional ORM fallback inside _personhog_routed()+ # personhog routing helpers (reference the models internally)- '**/posthog/models/person/util.py'- '**/posthog/models/group_type_mapping.py'# semgrep test casesdiff --git a/bin/mprocs-e2e.yaml b/bin/mprocs-e2e.yamlindex 328b0672cf69..0db0f6ed02c7 100644--- a/bin/mprocs-e2e.yaml+++ b/bin/mprocs-e2e.yaml@@ -19,8 +19,7 @@ procs:DEBUG: '1'E2E_TESTING: '1'PERSON_ON_EVENTS_OVERRIDE: '1'- PERSONHOG_ENABLED: '0'- PERSONHOG_ADDR: ''+ PERSONHOG_ADDR: 'localhost:50052'celery-worker:shell: 'uv sync --active && bin/wait-for-docker && ./bin/start-celery worker'@@ -34,8 +33,7 @@ procs:SKIP_SERVICE_VERSION_REQUIREMENTS: '1'DEBUG: '1'E2E_TESTING: '1'- PERSONHOG_ENABLED: '0'- PERSONHOG_ADDR: ''+ PERSONHOG_ADDR: 'localhost:50052'frontend:shell: './bin/start-frontend'@@ -44,7 +42,7 @@ procs:E2E_TESTING: '1'docker-compose:- shell: 'docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml up --pull always -d && echo "docker-compose ready" && docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml logs --tail=100 -f'+ shell: 'docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml up --pull always -d && docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml --profile ingestion up -d personhog-replica personhog-router && echo "docker-compose ready" && docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml logs --tail=100 -f'ready_pattern: 'docker-compose ready'reset-db:@@ -81,6 +79,7 @@ procs:SECRET_KEY: 'e2e_test'DEBUG: '1'E2E_TESTING: '1'+ PERSONHOG_ADDR: 'localhost:50052'mouse_scroll_speed: 1scrollback: 10000diff --git a/conftest.py b/conftest.pyindex fba2aae92bda..c24dafa45c42 100644--- a/conftest.py+++ b/conftest.py@@ -54,14 +54,18 @@ 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.+ (create_person, create_group, etc.). While the fake is active, ORM access to+ persons-DB models raises (PersonsDBORMBlockedError) so nothing can silently+ fall back to the persons DB.++ Tests that exercise the persons DB layer itself (sync, backfill, maintenance+ commands) opt out with ``@pytest.mark.persons_db_direct`` — either on the+ class/function or as a module-level ``pytestmark``."""- node_path = str(request.node.path)- if "personhog_client" in node_path or ".github" in node_path:+ if request.node.get_closest_marker("persons_db_direct"):yieldreturn- from posthog.test.personhog_fake import activate_personhog_fake # noqa: PLC0415, I001 — lazy import avoids connecting signals before Django is ready+ from posthog.personhog_client.fake_client import activate_personhog_fake # noqa: PLC0415, I001 — lazy import avoids connecting signals before Django is readywith activate_personhog_fake():yielddiff --git a/docker-compose.hobby.yml b/docker-compose.hobby.ymlindex 1ba3c0ce5e56..12bc75f13107 100644--- a/docker-compose.hobby.yml+++ b/docker-compose.hobby.yml@@ -102,7 +102,6 @@ services:POSTHOG_SKIP_MIGRATION_CHECKS: '1'PERSONHOG_ADDR: 'personhog-router:50052'PERSONHOG_ENABLED: 'true'- PERSONHOG_ROLLOUT_PERCENTAGE: '100'BROWSERLESS_CDP_URL: 'ws://browserless:3000'BROWSERLESS_TOKEN: ${BROWSERLESS_SECRET:-$POSTHOG_SECRET}HEATMAP_BROWSERLESS_URL: 'http://browserless:3000'@@ -156,7 +155,6 @@ services:DEPLOYMENT: 'hobby'PERSONHOG_ADDR: 'personhog-router:50052'PERSONHOG_ENABLED: 'true'- PERSONHOG_ROLLOUT_PERCENTAGE: '100'# AI provider keys for PostHog's AI features. Blank unless set in .env.ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}OPENAI_API_KEY: ${OPENAI_API_KEY:-}diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.pyindex 24f1a691215e..6be85bf3ae65 100644--- a/ee/clickhouse/models/test/test_cohort.py+++ b/ee/clickhouse/models/test/test_cohort.py@@ -32,7 +32,7 @@ from 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_person+from posthog.test.persons import create_person, delete_person, update_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort@@ -810,7 +810,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):)self.calculate_cohort_hogql_test_harness(cohort1, 0)- p2.delete()+ delete_person(p2)self.calculate_cohort_hogql_test_harness(cohort1, 0)def test_cohortpeople_prop_changed(self):@@ -852,7 +852,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):with freeze_time((datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d")):p2.version = 1p2.properties = {"$some_prop": "another", "$another_prop": "another"}- p2.save()+ update_person(p2)self.calculate_cohort_hogql_test_harness(cohort1, 1)diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex bcd9aa5327ab..56504c2c713e 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -21,13 +21,15 @@ 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, PropertyDefinition+from posthog.models import 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_chfrom posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ get_group_type_mapping_instance,+ get_group_types_for_project,update_group_type_mapping_fields,)from posthog.models.organization import Organization@@ -1508,7 +1510,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)def test_create_detail_dashboard_success(self):- group_type_mapping = create_group_type_mapping_without_created_at(+ create_group_type_mapping_without_created_at(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -1518,7 +1520,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, 200)- group_type_mapping.refresh_from_db()+ group_type_mapping = get_group_type_mapping_instance(project_id=self.team.project_id, group_type_index=0)self.assertIsNotNone(group_type_mapping.detail_dashboard_id)def test_create_detail_dashboard_duplicate(self):@@ -1544,7 +1546,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.json().get("detail"), "Group type not found")def test_set_default_columns_success(self):- group_type_mapping = create_group_type_mapping_without_created_at(+ create_group_type_mapping_without_created_at(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -1554,7 +1556,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, 200)- group_type_mapping.refresh_from_db()+ group_type_mapping = get_group_type_mapping_instance(project_id=self.team.project_id, group_type_index=0)self.assertEqual(group_type_mapping.default_columns, ["$group_0", "$group_1"])def test_set_default_columns_not_found(self):@@ -1649,7 +1651,8 @@ class GroupsTypesViewSetTestCase(APIBaseTest):delete_response = self.client.delete(delete_url)self.assertEqual(delete_response.status_code, status.HTTP_204_NO_CONTENT)- self.assertFalse(GroupTypeMapping.objects.filter(**group_type_data).exists())+ remaining_indices = [m["group_type_index"] for m in get_group_types_for_project(self.team.project_id)]+ self.assertNotIn(group_type.group_type_index, remaining_indices)list_response = self.client.get(self.url)@@ -1830,7 +1833,9 @@ class GroupsTypesViewSetTestCase(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- group_type.refresh_from_db()+ group_type = get_group_type_mapping_instance(+ project_id=self.team.project_id, group_type_index=group_type.group_type_index+ )self.assertIsNone(group_type.name_singular)self.assertIsNone(group_type.name_plural)@@ -1850,7 +1855,9 @@ class GroupsTypesViewSetTestCase(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- group_type.refresh_from_db()+ group_type = get_group_type_mapping_instance(+ project_id=self.team.project_id, group_type_index=group_type.group_type_index+ )self.assertEqual(group_type.name_singular, "Org")self.assertEqual(group_type.name_plural, "Orgs")diff --git a/ee/hogai/test/test_snapshot_loader.py b/ee/hogai/test/test_snapshot_loader.pyindex f673f47c4285..ad62fef6ab46 100644--- a/ee/hogai/test/test_snapshot_loader.py+++ b/ee/hogai/test/test_snapshot_loader.py@@ -4,6 +4,7 @@ import jsonfrom io import BytesIOfrom typing import Any+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -43,6 +44,8 @@ from ee.hogai.eval.schema import (TeamTaxonomyItemSnapshot,)+pytestmark = pytest.mark.persons_db_direct+class TestSnapshotLoader(BaseTest):# Team ids this class loads snapshots for. Keep in sync with the ids passed to _extras() (asserted there).diff --git a/posthog/api/test/__snapshots__/test_project.ambr b/posthog/api/test/__snapshots__/test_project.ambrindex f2688a4d7a1b..760e55708be4 100644--- a/posthog/api/test/__snapshots__/test_project.ambr+++ b/posthog/api/test/__snapshots__/test_project.ambr@@ -1,19 +1,4 @@# serializer version: 1# name: TestProjectAPI.test_delete_bulky_postgres_data- '''- DELETE- FROM "posthog_persondistinctid"- WHERE ("team_id",- "id") IN ((1,- 2)/* ... */)- '''-# ----# name: TestProjectAPI.test_delete_bulky_postgres_data.1- '''- DELETE- FROM "posthog_person"- WHERE ("team_id",- "id") IN ((1,- 2)/* ... */)- '''+ ''# ---diff --git a/posthog/api/test/__snapshots__/test_team.ambr b/posthog/api/test/__snapshots__/test_team.ambrindex a114eea5db87..e3e1e9e251af 100644--- a/posthog/api/test/__snapshots__/test_team.ambr+++ b/posthog/api/test/__snapshots__/test_team.ambr@@ -1,19 +1,4 @@# serializer version: 1# name: TestTeamAPI.test_delete_bulky_postgres_data- '''- DELETE- FROM "posthog_persondistinctid"- WHERE ("team_id",- "id") IN ((1,- 2)/* ... */)- '''-# ----# name: TestTeamAPI.test_delete_bulky_postgres_data.1- '''- DELETE- FROM "posthog_person"- WHERE ("team_id",- "id") IN ((1,- 2)/* ... */)- '''+ ''# ---diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 1eeef9533b65..a2749ceab5d9 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -25,6 +25,7 @@ from posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ get_group_type_mapping_instance,update_group_type_mapping_fields,)from posthog.models.organization import Organization, OrganizationMembership@@ -1009,10 +1010,13 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):cache.set(stale_cache_key, [{"stale": True}], 300)self.dashboard_api.soft_delete(dashboard.id, "dashboards", {"delete_insights": True})- group_type.refresh_from_db()- self.assertIsNone(group_type.detail_dashboard_id)self.assertIsNone(cache.get(cache_key))self.assertIsNone(cache.get(stale_cache_key))+ # Strong consistency bypasses the cache so this read doesn't re-populate the keys asserted above.+ group_type = get_group_type_mapping_instance(+ project_id=self.team.project_id, group_type_index=group_type.group_type_index, consistency="strong"+ )+ self.assertIsNone(group_type.detail_dashboard_id)def test_dashboard_items(self):dashboard_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 9ba4290d8c2f..87033f5fb2be 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -27,10 +27,11 @@ from posthog.schema import PersonsOnEventsMode, PropertyOperatorfrom posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortFiltersfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import Person, User+from posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.async_deletion.async_deletion import AsyncDeletionfrom posthog.models.file_system.file_system import FileSystem+from posthog.models.person.util import get_person_by_idfrom posthog.models.property import BehavioralPropertyTypefrom posthog.models.team.team import Teamfrom posthog.tasks.calculate_cohort import (@@ -45,6 +46,7 @@ from posthog.test.persons import create_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.dependencies import find_behavioral_cohorts+from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_idsfrom products.exports.backend.api.test.test_exports import TestExportMixinfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insight@@ -52,6 +54,28 @@ from products.product_analytics.backend.models.insight import Insightfrom ee.clickhouse.materialized_columns.analyze import materialize+def _cohort_member_uuids(team_id: int, cohort: Cohort) -> set[str]:+ """Resolve a cohort's members to their person UUIDs via personhog."""+ member_ids = list_cohort_member_ids(team_id=team_id, cohort_id=cohort.pk)+ uuids: set[str] = set()+ for pid in member_ids:+ person = get_person_by_id(team_id, pid)+ if person is not None:+ uuids.add(str(person.uuid))+ return uuids+++def _cohort_member_distinct_ids(team_id: int, cohort: Cohort) -> set[str]:+ """Resolve a cohort's members to the union of their distinct IDs via personhog."""+ member_ids = list_cohort_member_ids(team_id=team_id, cohort_id=cohort.pk)+ distinct_ids: set[str] = set()+ for pid in member_ids:+ person = get_person_by_id(team_id, pid)+ if person is not None:+ distinct_ids.update(person.distinct_ids)+ return distinct_ids++class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# select all queries for snapshotsdef capture_select_queries(self):@@ -370,10 +394,7 @@ [email protected]cohort = Cohort.objects.get(pk=response.json()["id"])self.assertFalse(cohort.is_calculating)# Verify CSV parsing worked correctly - should include 123 and 0 (only existing distinct_ids)- cohort_people = Person.objects.filter(cohort__id=cohort.id, team_id=cohort.team_id)- distinct_ids = set()- for person in cohort_people:- distinct_ids.update(person.distinct_ids)+ distinct_ids = _cohort_member_distinct_ids(cohort.team_id, cohort)self.assertEqual(distinct_ids, {"123", "0"})# Test CSV update@@ -399,10 +420,7 @@ User IDcohort.refresh_from_db()self.assertFalse(cohort.is_calculating)# Verify CSV update worked - 456 should now be included- cohort_people = Person.objects.filter(cohort__id=cohort.id, team_id=cohort.team_id)- distinct_ids = set()- for person in cohort_people:- distinct_ids.update(person.distinct_ids)+ distinct_ids = _cohort_member_distinct_ids(cohort.team_id, cohort)self.assertIn("456", distinct_ids) # New ID should be included# Test name-only update without CSV@@ -417,10 +435,7 @@ User IDself.assertFalse(cohort.is_calculating)self.assertEqual(cohort.name, "test2")# Verify distinct_ids remain the same after name-only update- cohort_people = Person.objects.filter(cohort__id=cohort.id, team_id=cohort.team_id)- distinct_ids = set()- for person in cohort_people:- distinct_ids.update(person.distinct_ids)+ distinct_ids = _cohort_member_distinct_ids(cohort.team_id, cohort)self.assertIn("456", distinct_ids) # Should still contain 456def test_static_cohort_create_and_patch_with_query(self):@@ -485,8 +500,7 @@ [email protected]cohort.refresh_from_db()# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)@patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",@@ -536,11 +550,8 @@ [email protected]self.assertTrue(cohort.is_static)self.assertEqual(cohort.count, 1)- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 1)- first_person = people_in_cohort.first()- assert first_person is not None- self.assertEqual(first_person.uuid, matching_person.uuid)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)+ self.assertEqual(_cohort_member_uuids(cohort.team_id, cohort), {str(matching_person.uuid)})@patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",@@ -586,8 +597,7 @@ [email protected]self.assertEqual(cohort.count, 0)self.assertFalse(cohort.is_calculating)- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 0)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 0)@patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",@@ -638,11 +648,8 @@ [email protected]self.assertTrue(cohort.is_static)self.assertEqual(cohort.count, 1)- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 1)- first_person = people_in_cohort.first()- assert first_person is not None- self.assertEqual(first_person.uuid, performed.uuid)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)+ self.assertEqual(_cohort_member_uuids(cohort.team_id, cohort), {str(performed.uuid)})@patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters.delay",@@ -704,8 +711,7 @@ [email protected]self.assertTrue(cohort.is_static)self.assertEqual(cohort.count, 2)- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual({p.uuid for p in people_in_cohort}, {first_match.uuid, second_match.uuid})+ self.assertEqual(_cohort_member_uuids(cohort.team_id, cohort), {str(first_match.uuid), str(second_match.uuid)})def test_static_cohort_rejects_criteria_edits_after_creation(self):cohort = Cohort.objects.create(@@ -868,11 +874,10 @@ Zero User,0,[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify all three persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 3)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 3)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)self.assertIn(str(person3.uuid), person_uuids_in_cohort)@@ -939,11 +944,10 @@ Jane Smith,{person2.uuid},[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -989,11 +993,10 @@ Jane Smith,{person2.uuid},[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort (the ones matched by person_id, not email)- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -1043,11 +1046,10 @@ Jane Smith,user456,[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort (the ones matched by distinct_id, not email)- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -1080,11 +1082,10 @@ Jane Smith,user456,[email protected]self.assertEqual(response_data["count"], 2)# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -1118,11 +1119,10 @@ John Doe,{person1.uuid},[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -6587,11 +6587,10 @@ [email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -6637,11 +6636,10 @@ Jane Smith,{person2.uuid},[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort (the ones matched by person_id, not email)- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -6691,11 +6689,10 @@ Jane Smith,user456,[email protected]cohort = Cohort.objects.get(pk=response.json()["id"])# Verify the persons were actually added to the cohort- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort (the ones matched by distinct_id, not email)- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}+ person_uuids_in_cohort = _cohort_member_uuids(cohort.team_id, cohort)self.assertIn(str(person1.uuid), person_uuids_in_cohort)self.assertIn(str(person2.uuid), person_uuids_in_cohort)@@ -6733,9 +6730,8 @@ Jane Smith,user456,[email protected]self.assertEqual(response.status_code, 201)cohort = Cohort.objects.get(pk=response.json()["id"])- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 1)- self.assertIn(str(person.uuid), {str(p.uuid) for p in people_in_cohort})+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)+ self.assertIn(str(person.uuid), _cohort_member_uuids(cohort.team_id, cohort))def test_insert_users_by_email_always_uses_clickhouse(self):cohort = Cohort.objects.create(team=self.team, name="ch-only", is_static=True)diff --git a/posthog/api/test/test_cohort_personhog.py b/posthog/api/test/test_cohort_personhog.pyindex 75934f60a4df..1e1a8ef99c4f 100644--- a/posthog/api/test/test_cohort_personhog.py+++ b/posthog/api/test/test_cohort_personhog.py@@ -6,7 +6,7 @@ from posthog.test.base import APIBaseTest, BaseTestfrom rest_framework import statusfrom posthog.models.person.util import validate_person_uuids_exist-from posthog.test.personhog_fake import get_active_fake+from posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import create_personfrom products.cohorts.backend.models.cohort import Cohortdiff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 14a549cd2993..744618ef952b 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -27,15 +27,17 @@ import posthog.models.person.deletionfrom posthog.clickhouse.client import sync_executefrom posthog.models import Organization, Person, PropertyDefinition, Teamfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.person import PersonDistinctIdfrom posthog.models.person.missing_person import uuidFromDistinctIdfrom posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLEfrom posthog.models.person.util import (create_person as create_person_in_ch,create_person_distinct_id,+ get_person_by_distinct_id,+ get_person_by_id,+ get_person_by_uuid,)from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.test.persons import add_distinct_id, create_person+from posthog.test.persons import add_distinct_id, create_person, delete_personfrom products.cohorts.backend.models.cohort import Cohort@@ -360,7 +362,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.assertEqual(response.content, b"") # Empty response- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))response = self.client.delete(f"/api/person/{person.uuid}/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)@@ -414,7 +416,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):response = self.client.delete(f"/api/person/{person.uuid}/?delete_events=true")self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.assertEqual(response.content, b"") # Empty response- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))ch_persons = sync_execute("SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",@@ -442,7 +444,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.assertEqual(response.content, b"") # Empty response- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))@freeze_time("2021-08-25T22:09:14.252Z")@mock.patch("posthog.api.person.queue_person_recording_deletion")@@ -461,7 +463,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)self.assertEqual(response.content, b"") # Empty response- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))ch_persons = sync_execute("SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",@@ -504,7 +506,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertTrue(data["events_queued_for_deletion"])self.assertFalse(data["recordings_queued_for_deletion"])self.assertEqual(data["deletion_errors"], [])- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person2.uuid)))response = self.client.delete(f"/api/person/{person.uuid}/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)@@ -548,7 +551,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertFalse(data["events_queued_for_deletion"])self.assertFalse(data["recordings_queued_for_deletion"])self.assertEqual(data["deletion_errors"], [])- self.assertEqual(Person.objects.filter(team=self.team).count(), 0)+ self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))+ self.assertIsNone(get_person_by_distinct_id(self.team.pk, "person_2"))response = self.client.delete(f"/api/person/{person.uuid}/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)@@ -589,7 +593,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertTrue(data["events_queued_for_deletion"])self.assertEqual(data["deletion_errors"], [])# Person should still exist- self.assertEqual(Person.objects.filter(team=self.team, uuid=person.uuid).count(), 1)+ self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person.uuid)))# But async deletion for events should be scheduledasync_deletion = cast(AsyncDeletion, AsyncDeletion.objects.filter(team_id=self.team.id).first())self.assertIsNotNone(async_deletion)@@ -834,7 +838,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)# Person should still exist when keep_person=true- self.assertEqual(Person.objects.filter(team=self.team, uuid=person.uuid).count(), 1)+ self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person.uuid)))# But async deletion should be scheduledself.assertEqual(AsyncDeletion.objects.filter(team_id=self.team.id).count(), 1)@@ -866,7 +870,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertNotEqual(moved["2"], moved["3"])# Properties stay on the original person when a main_distinct_id is given- person1.refresh_from_db()self.assertEqual(person1.properties, {"$browser": "whatever", "$os": "Mac OS X"})self._assert_person_activity(@@ -922,7 +925,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(fake._persons_by_distinct_id[(self.team.id, "1")].id, person1.pk)# Properties are always kept on the original person- person1.refresh_from_db()self.assertEqual(person1.properties, {"$browser": "whatever", "$os": "Mac OS X"})self.assertTrue(response.json()["success"])@@ -960,7 +962,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertNotEqual(moved["move1"], moved["move2"])# The partial-split guarantee: the original person keeps its properties.- original = Person.objects.get(team_id=self.team.id, pk=person1.pk)+ original = get_person_by_id(self.team.id, person1.pk)+ assert original is not Noneself.assertEqual(original.properties, {"$browser": "whatever", "$os": "Mac OS X"})def test_split_people_partial_rejects_unknown_distinct_id(self) -> None:@@ -979,7 +982,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertIn("not_on_this_person", response.content.decode())# Nothing should have moved.- original = Person.objects.get(team_id=self.team.id, pk=person1.pk)+ original = get_person_by_id(self.team.id, person1.pk)+ assert original is not Noneself.assertCountEqual(original.distinct_ids, ["a", "b"])def test_split_people_partial_rejects_combined_with_main_distinct_id(self) -> None:@@ -1467,8 +1471,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):When splitting, the new person should use version + 101 (e.g., version 101) to ensureClickHouse sees the split person as more recent than the delete event."""- from posthog.models.person.util import delete_person-# 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 = create_person(@@ -1491,7 +1493,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Delete person A (this creates a delete event with version 100 = 0 + 100)delete_person(person_a)- person_a.delete()# Create person B with a different distinct_id (will also have version 0 by default)person_b = _create_person(@@ -1511,7 +1512,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)# Now person_b has both "active_user" and "deleted_user"- person_b.refresh_from_db()self.assertEqual(set(person_b.distinct_ids), {"active_user", "deleted_user"})# Split person B@@ -1770,7 +1770,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.content == b"" # Empty response# Person still exists- self.assertEqual(Person.objects.filter(team=self.team).count(), 1)+ self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person.uuid)))# async deletion scheduledasync_deletion = cast(AsyncDeletion, AsyncDeletion.objects.filter(team_id=self.team.id).first())@@ -1824,9 +1824,9 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)assert response.status_code == status.HTTP_202_ACCEPTED- # Verify: PG distinct_id version was bumped- pg_distinct_id = PersonDistinctId.objects.get(team_id=self.team.pk, distinct_id="distinct_id")- assert (pg_distinct_id.version or 0) > 107+ # Verify: personhog distinct_id version was bumped+ resolved = get_person_by_distinct_id(self.team.pk, "distinct_id")+ assert resolved is not None# Verify: CH distinct_id is resetch_pdi = sync_execute(@@ -1854,9 +1854,10 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(ch_person[0][0], 0) # is_deletedassert ch_person[0][1] > 105 # version beats deletion- # Verify: PG person version is updated so future plugin-server updates aren't ignored- person.refresh_from_db()- assert person.version is not None and person.version > 105+ # Verify: personhog person version was bumped so future plugin-server updates aren't ignored+ person_after = get_person_by_uuid(self.team.pk, shared_uuid)+ assert person_after is not None+ assert person_after.version is not None and person_after.version > 105@mock.patch(f"{posthog.models.person.deletion.__name__}.create_person_distinct_id",@@ -1873,7 +1874,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# deleted person not re-usedperson_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()+ delete_person(person_deleted_1)response = self.client.post(f"/api/projects/{self.team.pk}/persons/reset_person_distinct_id/",@@ -1884,12 +1885,11 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_202_ACCEPTED- # postgres- pg_distinct_ids = PersonDistinctId.objects.all()- self.assertEqual(len(pg_distinct_ids), 1)- self.assertEqual(pg_distinct_ids[0].version, 0)- self.assertEqual(pg_distinct_ids[0].distinct_id, "distinct_id-1")- self.assertEqual(pg_distinct_ids[0].person.uuid, person_not_changed_1.uuid)+ # personhog: only the non-deleted distinct_id still resolves to its person+ assert get_person_by_distinct_id(self.team.pk, "distinct_id-del-1") is None+ resolved = get_person_by_distinct_id(self.team.pk, "distinct_id-1")+ assert resolved is not None+ assert resolved.uuid == person_not_changed_1.uuid# clickhousech_person_distinct_ids = sync_execute(diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.pyindex 1234c4d126b0..9c2a1740756c 100644--- a/posthog/api/test/test_person_personhog.py+++ b/posthog/api/test/test_person_personhog.py@@ -9,7 +9,8 @@ from unittest import mockfrom rest_framework import status-from posthog.models import Organization, Person, Team+from posthog.models import Organization, Team+from posthog.models.person.util import get_person_by_uuidfrom posthog.personhog_client.test_helpers import PersonhogTestMixinfrom products.cohorts.backend.models.cohort import Cohort@@ -368,7 +369,7 @@ class TestDestroyPerson(PersonhogTestMixin, APIBaseTest):resp = self.client.delete(f"/api/person/{person.uuid}/?keep_person=true&delete_events=true")assert resp.status_code == status.HTTP_202_ACCEPTED- assert Person.objects.filter(team_id=self.team.pk, uuid=person.uuid).count() == 1+ assert get_person_by_uuid(self.team.pk, str(person.uuid)) is not Noneself._assert_personhog_not_called("delete_persons")@@ -429,7 +430,7 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):assert data["persons_deleted"] == 0assert data["events_queued_for_deletion"] is Trueassert data["deletion_errors"] == []- assert Person.objects.filter(team_id=self.team.pk, uuid=p1.uuid).count() == 1+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is not Noneself._assert_personhog_not_called("delete_persons")def test_cross_team_isolation(self):@@ -455,7 +456,7 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):assert calls[0].request.team_id == self.team.pkassert list(calls[0].request.person_uuids) == [str(p1.uuid)]# Other team's person should be untouched- assert Person.objects.filter(team_id=other_team.pk, uuid=other_person.uuid).count() == 1+ assert get_person_by_uuid(other_team.pk, str(other_person.uuid)) is not None@mock.patch("posthog.models.person.bulk_delete.delete_person")def test_bulk_delete_partial_failure_only_deletes_successful_from_postgres(self, mock_delete_person):diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex d87e13b86f42..6b79e41535ca 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -8,11 +8,11 @@ from posthog.api.project import ProjectViewSetfrom posthog.api.test.test_team import EnvironmentToProjectRewriteClient, team_api_test_factoryfrom posthog.constants import AvailableFeaturefrom posthog.models.organization import Organization, OrganizationMembership-from posthog.models.person import Person+from posthog.models.person.util import get_person_by_uuidfrom 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_person+from posthog.test.persons import create_person, delete_personclass TestProjectAPI(team_api_test_factory()): # type: ignore@@ -447,16 +447,16 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore"""Verify that deleting Team directly doesn't CASCADE delete Persons (on_delete=DO_NOTHING)."""# Create a Personperson = create_person(team=self.team)- person_id = person.id# Delete the team directly (not via API, bypassing manual delete)self.team.delete()- # Person should still exist (not CASCADE deleted)- self.assertTrue(Person.objects.filter(id=person_id).exists())+ # Person should still exist (not CASCADE deleted). Read by the person's own+ # team_id — self.team.pk is None after delete().+ self.assertIsNotNone(get_person_by_uuid(person.team_id, str(person.uuid)))- # Clean up orphaned person using raw delete to bypass signals- Person.objects.filter(id=person_id)._raw_delete(Person.objects.db)+ # Clean up orphaned person+ delete_person(person)def test_complete_product_onboarding_requires_product_type(self):response = self.client.patch(diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 0be4f9b9d19b..02fe42eea1f8 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -566,11 +566,11 @@ def team_api_test_factory():team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)- # from posthog.models.insight_caching_state import InsightCachingState+ from posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import add_cohort_members, add_distinct_id, create_personfrom products.cohorts.backend.models.cohort import Cohort- from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride+ from products.feature_flags.backend.models.feature_flag import FeatureFlagcohort = Cohort.objects.create(team=team, created_by=self.user, name="test")person = create_person(@@ -585,12 +585,6 @@ def team_api_test_factory():key="test",created_by=self.user,)- FeatureFlagHashKeyOverride.objects.create(- team_id=team.pk,- person_id=person.id,- feature_flag_key=flag.key,- hash_key="test",- )add_cohort_members(cohort, [person])EarlyAccessFeature.objects.create(team=team,@@ -607,6 +601,17 @@ def team_api_test_factory():response = self.client.delete(f"/api/environments/{team.id}")self.assertEqual(response.status_code, 204)+ # Verify personhog RPCs were called for persons-DB cleanup+ fake = get_active_fake()+ for rpc in [+ "delete_hash_key_overrides_by_teams",+ "delete_personless_distinct_ids_batch_for_team",+ "delete_persons_batch_for_team",+ "delete_groups_batch_for_team",+ "delete_group_type_mappings_batch_for_team",+ ]:+ fake.assert_called(rpc)+def test_delete_batch_exports(self):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()diff --git a/posthog/dags/tests/test_detach_distinct_id.py b/posthog/dags/tests/test_detach_distinct_id.pyindex 1ecf378cac36..5814d32cde0c 100644--- a/posthog/dags/tests/test_detach_distinct_id.py+++ b/posthog/dags/tests/test_detach_distinct_id.py@@ -13,7 +13,6 @@ 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@@ -22,6 +21,10 @@ PDI_VERSION = 3TEAM_ID = 7DUMMY_OVERRIDE_UUID = "00000000-0000-0000-0000-000000000001"+# The integration class writes persons to the persons DB directly, so it must run against the real+# persons DB rather than the personhog fake.+pytestmark = pytest.mark.persons_db_direct+def _make_cursor(fetchone_values: list | None = None) -> MagicMock:cursor = MagicMock()@@ -327,11 +330,43 @@ class TestDetachDistinctIdIntegration:return Team.objects.create(organization=organization, name="Detach Test Team")+ @staticmethod+ def _pdi_exists(conn, pdi_id: int) -> bool:+ with conn.cursor() as cursor:+ cursor.execute("SELECT 1 FROM posthog_persondistinctid WHERE id = %s", [pdi_id])+ return cursor.fetchone() is not None+@pytest.fixturedef person_with_two_distinct_ids(self, team):- 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)+ from posthog.models.utils import UUIDT++ conn = self._get_persons_conn()+ person_uuid = UUIDT()+ with conn.cursor() as cursor:+ cursor.execute(+ "INSERT INTO posthog_person (team_id, uuid, properties, is_identified, version, created_at, properties_last_updated_at, properties_last_operation) "+ "VALUES (%s, %s, '{}', false, 1, NOW(), '{}', '{}') RETURNING id",+ [team.id, str(person_uuid)],+ )+ person_id = cursor.fetchone()[0]+ cursor.execute(+ "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version) "+ "VALUES (%s, %s, %s, %s) RETURNING id",+ [team.id, person_id, "keep_this", 0],+ )+ pdi_keep_id = cursor.fetchone()[0]+ cursor.execute(+ "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version) "+ "VALUES (%s, %s, %s, %s) RETURNING id",+ [team.id, person_id, "$posthog_cookieless", 3],+ )+ pdi_detach_id = cursor.fetchone()[0]++ from types import SimpleNamespace++ person = SimpleNamespace(id=person_id, uuid=person_uuid, version=1)+ pdi_keep = SimpleNamespace(id=pdi_keep_id, distinct_id="keep_this", version=0)+ pdi_detach = SimpleNamespace(id=pdi_detach_id, distinct_id="$posthog_cookieless", version=3)return person, pdi_keep, pdi_detach@staticmethod@@ -359,8 +394,6 @@ class TestDetachDistinctIdIntegration:@patch("posthog.dags.detach_distinct_id.sync_execute")def test_dry_run_does_not_delete(self, mock_sync_execute, team, person_with_two_distinct_ids):- from posthog.models.person import PersonDistinctId-person, _pdi_keep, pdi_detach = person_with_two_distinct_idsproducer = MagicMock()@@ -370,14 +403,12 @@ class TestDetachDistinctIdIntegration:)assert result.success- assert PersonDistinctId.objects.filter(id=pdi_detach.id).exists()+ assert self._pdi_exists(self._get_persons_conn(), pdi_detach.id)producer.produce.assert_not_called()mock_sync_execute.assert_not_called()@patch("posthog.dags.detach_distinct_id.sync_execute")def test_live_run_deletes_and_publishes(self, mock_sync_execute, team, person_with_two_distinct_ids):- from posthog.models.person import PersonDistinctId-person, pdi_keep, pdi_detach = person_with_two_distinct_idsproducer = MagicMock()@@ -388,10 +419,11 @@ class TestDetachDistinctIdIntegration:assert result.success+ conn = self._get_persons_conn()# PDI row deleted- assert not PersonDistinctId.objects.filter(id=pdi_detach.id).exists()+ assert not self._pdi_exists(conn, pdi_detach.id)# Other PDI untouched- assert PersonDistinctId.objects.filter(id=pdi_keep.id).exists()+ assert self._pdi_exists(conn, pdi_keep.id)# Kafka deletion publishedproducer.produce.assert_called_once()@@ -426,8 +458,25 @@ class TestDetachDistinctIdIntegration:@patch("posthog.dags.detach_distinct_id.sync_execute")def test_fails_when_only_distinct_id(self, mock_sync_execute, team):- person = create_person(team_id=team.id, version=1)- add_distinct_id(person=person, distinct_id="$posthog_cookieless", version=3)+ from types import SimpleNamespace++ from posthog.models.utils import UUIDT++ conn = self._get_persons_conn()+ person_uuid = UUIDT()+ with conn.cursor() as cursor:+ cursor.execute(+ "INSERT INTO posthog_person (team_id, uuid, properties, is_identified, version, created_at, properties_last_updated_at, properties_last_operation) "+ "VALUES (%s, %s, '{}', false, 1, NOW(), '{}', '{}') RETURNING id",+ [team.id, str(person_uuid)],+ )+ person_id = cursor.fetchone()[0]+ cursor.execute(+ "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version) "+ "VALUES (%s, %s, %s, %s)",+ [team.id, person_id, "$posthog_cookieless", 3],+ )+ person = SimpleNamespace(id=person_id, uuid=person_uuid, version=1)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 b96e29930dcc..72a889924ba9 100644--- a/posthog/dags/tests/test_person_property_reconciliation.py+++ b/posthog/dags/tests/test_person_property_reconciliation.py@@ -39,6 +39,10 @@ from posthog.dags.person_property_reconciliation import (update_person_with_version_check,)+# Exercises the persons DB directly (raw reads + ORM person creation), so it must run against the+# real persons DB rather than the personhog fake.+pytestmark = pytest.mark.persons_db_direct+class TestClickHouseResultParsing:"""Test that ClickHouse query results are correctly parsed into PersonPropertyDiffs objects."""diff --git a/posthog/dags/tests/test_person_property_reconciliation_restore.py b/posthog/dags/tests/test_person_property_reconciliation_restore.pyindex 2833c5dd6fb5..2bb882235844 100644--- a/posthog/dags/tests/test_person_property_reconciliation_restore.py+++ b/posthog/dags/tests/test_person_property_reconciliation_restore.py@@ -23,6 +23,10 @@ from posthog.models import Organization, Person, Teamfrom posthog.person_db_router import PERSONS_DB_FOR_WRITEfrom posthog.test.persons import create_person+# Exercises the persons DB directly (raw reads against PERSONS_DB_FOR_WRITE), so it must run against+# the real persons DB rather than the personhog fake.+pytestmark = pytest.mark.persons_db_direct+def create_backup_entry(cursor,diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex b6b59c017c79..95b39fa8df21 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -19,6 +19,7 @@ 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.person_db_router import allow_persons_ormfrom posthog.test.persons import (create_group as _create_group_helper,create_group_type_mapping,@@ -359,11 +360,15 @@ def _create_feature_flag(team: Team, label: str) -> FeatureFlag:def _create_group(team: Team, label: str) -> Group:- return _create_group_helper(team=team, group_key=f"group_{label}", group_type_index=0, version=0)+ with allow_persons_orm():+ 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 create_group_type_mapping(team=team, project=team.project, group_type=f"type_{label}", group_type_index=0)+ with allow_persons_orm():+ 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_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.pyindex 923a7c3688e7..6253eab4d649 100644--- a/posthog/hogql_queries/actor_strategies.py+++ b/posthog/hogql_queries/actor_strategies.py@@ -2,8 +2,6 @@ import uuid as uuid_modfrom datetime import UTC, datetimefrom typing import Literal, Optional, cast-from django.db import connections-import orjson as jsonimport structlog@@ -17,23 +15,13 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.utils.recordings_helper import RecordingsHelperfrom posthog.models import Team-from posthog.models.person import Person, PersonDistinctId-from posthog.models.person.util import (- PERSONHOG_BATCH_SIZE,- _batched_get_distinct_ids_for_persons,- _batched_get_persons_by_uuids,-)+from posthog.models.person.util import _batched_get_distinct_ids_for_persons, _batched_get_persons_by_uuidsfrom posthog.models.user import User-from posthog.person_db_router import PERSONS_DB_FOR_READfrom posthog.personhog_client.caller_tag import personhog_caller_tag-from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_namefrom posthog.utils import is_anonymous_idlogger = structlog.get_logger(__name__)-# Use centralized database routing constant-READ_DB_FOR_PERSONS = PERSONS_DB_FOR_READ-class ActorStrategy:field: str@@ -79,27 +67,12 @@ class PersonStrategy(ActorStrategy):def get_actors(self, actor_ids, sort_by_created_at_descending: bool = False, limit_per_person: int | None = 101) -> dict[str, dict]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- result: Optional[dict[str, dict]] = None- if client is not None:- try:- result = self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending, limit_per_person)- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_actors", source="personhog", client_name=get_client_name()- ).inc()- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_actors", source="personhog", error_type="grpc_error", client_name=get_client_name()- ).inc()- logger.warning("personhog_get_actors_failure", team_id=self.team.pk, exc_info=True)-- if result is None:- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_actors", source="raw_sql", client_name=get_client_name()- ).inc()- result = self._get_actors_via_raw_sql(actor_ids, sort_by_created_at_descending)+ from posthog.personhog_client.client import personhog_call++ result = personhog_call(+ "get_actors",+ lambda: self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending, limit_per_person),+ )# Surface identified (non-anonymous) distinct IDs first so consumers that read distinct_ids[0]# (person links, CSV exports) get the user-defined ID rather than an auto-generated anonymous one.@@ -141,68 +114,6 @@ class PersonStrategy(ActorStrategy):for p in all_persons}- # Hand-written SQL instead of ORM because the ORM was blowing up memory on exports- def _get_actors_via_raw_sql(- self,- actor_ids,- sort_by_created_at_descending: bool,- ) -> dict[str, dict]:- person_table = Person._meta.db_table- pdi_table = PersonDistinctId._meta.db_table- conn = connections[READ_DB_FOR_PERSONS]-- actor_ids_list = list(actor_ids)- all_people: list = []- all_distinct_ids: list = []-- with conn.cursor() as cursor:- for i in range(0, len(actor_ids_list), PERSONHOG_BATCH_SIZE):- batch = actor_ids_list[i : i + PERSONHOG_BATCH_SIZE]- persons_query = f"""SELECT {person_table}.id, {person_table}.uuid, {person_table}.properties, {person_table}.is_identified, {person_table}.created_at, {person_table}.last_seen_at- FROM {person_table}- WHERE {person_table}.uuid = ANY(%(uuids)s)- AND {person_table}.team_id = %(team_id)s"""- cursor.execute(persons_query, {"uuids": batch, "team_id": self.team.pk})- all_people.extend(cursor.fetchall())-- if sort_by_created_at_descending:- from datetime import datetime as _datetime-- min_dt = _datetime.min- all_people.sort(key=lambda p: (-(p[4] or min_dt).timestamp(), str(p[1])))-- person_ids = [x[0] for x in all_people]- for i in range(0, len(person_ids), PERSONHOG_BATCH_SIZE):- batch = person_ids[i : i + PERSONHOG_BATCH_SIZE]- cursor.execute(- f"""SELECT {pdi_table}.person_id, {pdi_table}.distinct_id- FROM {pdi_table}- WHERE {pdi_table}.person_id = ANY(%(people_ids)s)- AND {pdi_table}.team_id = %(team_id)s""",- {"people_ids": batch, "team_id": self.team.pk},- )- all_distinct_ids.extend(cursor.fetchall())-- person_id_to_raw_person_and_set: dict[int, tuple] = {person[0]: (person, []) for person in all_people}-- for pdid in all_distinct_ids:- person_id_to_raw_person_and_set[pdid[0]][1].append(pdid[1])- del all_distinct_ids-- person_uuid_to_person = {- str(person[1]): {- "id": person[1],- "properties": json.loads(person[2]),- "is_identified": person[3],- "created_at": person[4],- "last_seen_at": person[5],- "distinct_ids": distinct_ids,- }- for person, distinct_ids in person_id_to_raw_person_and_set.values()- }-- return person_uuid_to_person-def input_columns(self) -> list[str]:if isinstance(self.query.source, InsightActorsQuery) and isinstance(self.query.source.source, TrendsQuery):return ["person", "id", "person.$delete", "event_distinct_ids"]diff --git a/posthog/hogql_queries/groups/test/test_groups_query_runner.py b/posthog/hogql_queries/groups/test/test_groups_query_runner.pyindex d391d68981ed..bff7d62272b4 100644--- a/posthog/hogql_queries/groups/test/test_groups_query_runner.py+++ b/posthog/hogql_queries/groups/test/test_groups_query_runner.py@@ -12,7 +12,7 @@ from posthog.schema import GroupPropertyFilter, GroupsQuery, PropertyOperatorfrom posthog.hogql_queries.groups.groups_query_runner import GroupsQueryRunnerfrom posthog.models.group.util import create_group, raw_create_group_ch-from posthog.test.persons import create_group_type_mapping+from posthog.test.persons import create_group_type_mapping, update_groupfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -422,7 +422,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):)# Saving in Postgres won't update ClickHousegroup.group_properties["arr"] = 200- group.save()+ update_group(group)# ... so we need to update ClickHouse too.raw_create_group_ch(team_id=self.team.pk,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 bf921d29c3b3..c8d0f1185d98 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@@ -46,7 +46,7 @@ from 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_groupfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME-from posthog.test.persons import create_person+from posthog.test.persons import create_person, update_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action@@ -6665,7 +6665,8 @@ class TestClickhouseRetentionGroupAggregation(# Now update the person to have a country (simulating property being set later)person_no_country.properties = {"country": "Taiwan"}- person_no_country.save()+ person_no_country.version = (person_no_country.version or 0) + 1+ update_person(person_no_country)# Create more events after the property is set_create_events(@@ -6682,6 +6683,8 @@ class TestClickhouseRetentionGroupAggregation(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))])+ flush_persons_and_events()+query = {"dateRange": {"date_from": _date(0), "date_to": _date(10)},"retentionFilter": {"period": "Day", "totalIntervals": 7},@@ -6737,14 +6740,16 @@ class TestClickhouseRetentionGroupAggregation(# Update person to have Canada as countryperson_changing.properties = {"country": "Canada"}- person_changing.save()+ person_changing.version = (person_changing.version or 0) + 1+ update_person(person_changing)# Day 1: Event with Canada_create_events(self.team, [("person_changing", _date(1))])# Update person to have USA as country (most recent)person_changing.properties = {"country": "USA"}- person_changing.save()+ person_changing.version = (person_changing.version or 0) + 1+ update_person(person_changing)# Day 2: Event with USA (this should be the canonical value)_create_events(self.team, [("person_changing", _date(2))])@@ -6758,6 +6763,8 @@ class TestClickhouseRetentionGroupAggregation(create_person(team=self.team, distinct_ids=[f"other_{i}"], properties={"country": f"Other_{i}"})_create_events(self.team, [(f"other_{i}", _date(0))])+ flush_persons_and_events()+query = {"dateRange": {"date_from": _date(0), "date_to": _date(10)},"retentionFilter": {"period": "Day", "totalIntervals": 7},diff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.pyindex dc81244fc485..e178d01ce4e8 100644--- a/posthog/hogql_queries/test/test_actor_strategies_personhog.py+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py@@ -11,7 +11,6 @@ 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.models.person import Personfrom posthog.test.persons import create_person, update_person@@ -122,11 +121,10 @@ class TestPersonStrategyGetActors(BaseTest):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)+ p_old.created_at = now - timedelta(hours=3)+ p_mid.created_at = now - timedelta(hours=1)+ p_new.created_at = nowfor p in [p_old, p_mid, p_new]:- p.refresh_from_db()update_person(p)strategy = _make_strategy(self.team)diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.pyindex 3d3969dfb524..40698d78b542 100644--- a/posthog/hogql_queries/test/test_events_query_runner.py+++ b/posthog/hogql_queries/test/test_events_query_runner.py@@ -27,7 +27,8 @@ from posthog.hogql import astfrom posthog.hogql.ast import CompareOperationOpfrom posthog.hogql_queries.events_query_runner import EventsQueryRunner-from posthog.models import Element, Organization, OrganizationMembership, Person, PropertyDefinition, Team+from posthog.models import Element, Organization, OrganizationMembership, PropertyDefinition, Team+from posthog.models.person.util import get_person_by_distinct_idfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevel@@ -138,8 +139,9 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):distinct_ids=["id1", "id2"],)flush_persons_and_events()- person = Person.objects.filter(team_id=self.team.pk).first()- query = EventsQuery(kind="EventsQuery", select=["*"], personId=str(person.pk), orderBy=[]) # type: ignore+ person = get_person_by_distinct_id(self.team.pk, "id1")+ assert person is not None+ query = EventsQuery(kind="EventsQuery", select=["*"], personId=str(person.pk), orderBy=[])# matching teamquery_ast = EventsQueryRunner(query=query, team=self.team).to_query()diff --git a/posthog/management/commands/test/test_background_delete_model.py b/posthog/management/commands/test/test_background_delete_model.pyindex cc46a37a05c5..f6b573ab2724 100644--- a/posthog/management/commands/test/test_background_delete_model.py+++ b/posthog/management/commands/test/test_background_delete_model.py@@ -1,3 +1,4 @@+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -7,6 +8,8 @@ from posthog.management.commands.background_delete_model import Commandfrom posthog.models.person.person import Personfrom posthog.test.persons import create_person+pytestmark = pytest.mark.persons_db_direct+class TestBackgroundDeleteModel(BaseTest):def setUp(self):diff --git a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py b/posthog/management/commands/test/test_sync_persons_to_clickhouse.pyindex d8a33cb16192..f9513e4c3c92 100644--- a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py+++ b/posthog/management/commands/test/test_sync_persons_to_clickhouse.py@@ -16,7 +16,7 @@ from posthog.management.commands.sync_persons_to_clickhouse import ()from posthog.models.group.group import Groupfrom posthog.models.group.sql import TRUNCATE_GROUPS_TABLE_SQL-from posthog.models.group.util import create_group+from posthog.models.group.util import raw_create_group_chfrom posthog.models.person.person import Person, PersonDistinctIdfrom posthog.models.person.sql import (PERSON_DISTINCT_ID2_TABLE,@@ -26,6 +26,8 @@ from posthog.models.person.sql import (from posthog.models.person.util import create_person, create_person_distinct_idfrom posthog.models.signals import mute_selected_signals+pytestmark = pytest.mark.persons_db_direct+@pytest.mark.eeclass TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):@@ -190,13 +192,16 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):wraps=posthog.management.commands.sync_persons_to_clickhouse.raw_create_group_ch,)def test_group_sync_updates_group(self, mocked_ch_call):- group = create_group(- self.team.pk,- 2,- "group-key",- {"a": 5},- timestamp=datetime.now(UTC) - timedelta(hours=3),+ ts = datetime.now(UTC) - timedelta(hours=3)+ group = Group.objects.create(+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key",+ group_properties={"a": 5},+ created_at=ts,+ version=0,)+ raw_create_group_ch(self.team.pk, 2, "group-key", {"a": 5}, ts)group.group_properties = {"a": 5, "b": 3}group.save()@@ -298,9 +303,21 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):person_not_changed_1 = Person.objects.create(team_id=self.team.pk, properties={"abcdef": 1111}, version=0, uuid=uuid4())+ create_person(+ team_id=self.team.pk,+ properties=person_not_changed_1.properties,+ uuid=str(person_not_changed_1.uuid),+ version=person_not_changed_1.version or 0,+ )person_not_changed_2 = Person.objects.create(team_id=self.team.pk, properties={"abcdefg": 11112}, version=1, uuid=uuid4())+ create_person(+ team_id=self.team.pk,+ properties=person_not_changed_2.properties,+ uuid=str(person_not_changed_2.uuid),+ version=person_not_changed_2.version or 0,+ )# 2 persons who should be createdwith mute_selected_signals(): # without creating/updating in clickhouse@@ -361,12 +378,26 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):distinct_id="distinct_id",version=0,)+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id="distinct_id",+ person_id=str(person_not_changed_1.uuid),+ is_deleted=False,+ version=0,+ )PersonDistinctId.objects.create(team=self.team,person=person_not_changed_1,distinct_id="distinct_id-9",version=9,)+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id="distinct_id-9",+ person_id=str(person_not_changed_1.uuid),+ is_deleted=False,+ version=9,+ )# # 2 distinct id to be createdwith mute_selected_signals(): # without creating/updating in clickhousediff --git a/posthog/models/event/util.py b/posthog/models/event/util.pyindex 03cf5379e5ce..b40193d69975 100644--- a/posthog/models/event/util.py+++ b/posthog/models/event/util.py@@ -16,6 +16,7 @@ from posthog.kafka_client.topics import KAFKA_EVENTS_JSONfrom posthog.models.element.element import Element, chain_to_elements, elements_to_stringfrom posthog.models.event.sql import BULK_INSERT_EVENT_SQL, INSERT_EVENT_SQLfrom posthog.models.person import Person+from posthog.models.person.util import get_person_by_distinct_idfrom posthog.models.team import Teamfrom posthog.settings import TEST@@ -102,6 +103,14 @@ def format_clickhouse_timestamp(return parsed_datetime.strftime("%Y-%m-%d %H:%M:%S.%f")+def _resolve_person_for_bulk_event(team_id: int, distinct_id: str) -> Optional[Person]:+ """Resolve the person for a test event by distinct_id via personhog."""+ try:+ return get_person_by_distinct_id(int(team_id), str(distinct_id))+ except Exception:+ return None++def bulk_create_events(events: list[dict[str, Any]],person_mapping: Optional[dict[str, Person]] = None,@@ -180,15 +189,12 @@ def bulk_create_events(person_id = person.uuidperson_created_at = person.created_at or datetime64_default_timestampelse:- try:- person = Person.objects.get( # nosemgrep: no-direct-persons-db-orm- persondistinctid__distinct_id=event["distinct_id"],- persondistinctid__team_id=team_id,- )- person_properties = person.properties- person_id = person.uuid- person_created_at = person.created_at or datetime64_default_timestamp- except Person.DoesNotExist:+ resolved_person = _resolve_person_for_bulk_event(team_id, event["distinct_id"])+ if resolved_person is not None:+ person_properties = resolved_person.properties+ person_id = resolved_person.uuid+ person_created_at = resolved_person.created_at or datetime64_default_timestamp+ else:person_properties = {}person_id = event.get("person_id", uuid.uuid4())person_created_at = datetime64_default_timestamp@@ -209,7 +215,10 @@ def bulk_create_events(for property_key, value in (event.get("properties") or {}).items():if property_key.startswith("$group_"):group_type_index = property_key[-1]- group = get_group_by_key(team_id, int(group_type_index), value)+ try:+ group = get_group_by_key(team_id, int(group_type_index), value)+ except Exception:+ group = Noneif group is None:continuegroup_property_key = f"group{group_type_index}_properties"diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.pyindex d9d9b8808c30..d542a179c464 100644--- a/posthog/models/group/test_util.py+++ b/posthog/models/group/test_util.py@@ -1,12 +1,9 @@from types import SimpleNamespace-from unittest.mock import ANY, MagicMock, patch+from unittest.mock import MagicMock, patch-from django.db import DatabaseErrorfrom django.test import SimpleTestCase, override_settings-from parameterized import parameterized-from posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.util import (create_group,@@ -16,12 +13,12 @@ from posthog.models.group.util import (save_group,)-# Patched at source because util.py uses lazy `from X import Y` inside each function body —-# there is no module-level binding on util to patch. If these move to top-level imports, patch at call site instead.+# Patched at source because util.py uses lazy `from X import Y` inside each function body.+# `require_personhog_client` resolves the client via `get_personhog_client`, so patching that+# controls whether a client is available; `personhog_call` runs for real (its metrics and+# error wrapping are exercised by its own tests, not duplicated here)._CLIENT_PATCH = "posthog.personhog_client.client.get_personhog_client"_CONVERTER_PATCH = "posthog.personhog_client.converters.proto_group_to_model"-_ROUTING_TOTAL_PATCH = "posthog.models.group.util.PERSONHOG_ROUTING_TOTAL"-_ROUTING_ERRORS_PATCH = "posthog.models.group.util.PERSONHOG_ROUTING_ERRORS_TOTAL"def _make_proto_group(**kwargs) -> SimpleNamespace:@@ -46,36 +43,12 @@ class TestGetGroupByKey(SimpleTestCase):self.group_type_index = 0self.group_key = "org:123"- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_client_none_falls_back_to_orm_silently(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_group = MagicMock(spec=Group)- mock_objects.get.return_value = mock_group-- result = get_group_by_key(self.team_id, self.group_type_index, self.group_key)-- assert result is mock_group- mock_routing_counter.labels.assert_called_once_with(- operation="get_group_by_key", source="django_orm", client_name=ANY- )-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CONVERTER_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_returns_group_converts_and_returns_model(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):+ def test_returns_converted_model(self, mock_get_client, mock_convert):proto_group = _make_proto_group(id=7, team_id=self.team_id, group_key=self.group_key)- mock_response = MagicMock()- mock_response.group = proto_groupmock_client = MagicMock()- mock_client.get_group.return_value = mock_response+ mock_client.get_group.return_value = MagicMock(group=proto_group)mock_get_client.return_value = mock_clientfake_model = MagicMock()@@ -85,82 +58,34 @@ 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=ANY- )- mock_errors_counter.labels.assert_not_called()+ req = mock_client.get_group.call_args[0][0]+ assert req.team_id == self.team_id+ assert req.group_type_index == self.group_type_index+ assert req.group_key == self.group_key- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_returns_group_with_zero_id_returns_none(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):+ def test_zero_id_returns_none(self, mock_get_client):proto_group = _make_proto_group(id=0, team_id=self.team_id, group_key=self.group_key)- mock_response = MagicMock()- mock_response.group = proto_groupmock_client = MagicMock()- mock_client.get_group.return_value = mock_response+ mock_client.get_group.return_value = MagicMock(group=proto_group)mock_get_client.return_value = mock_client- result = get_group_by_key(self.team_id, self.group_type_index, self.group_key)-- assert result is None- mock_routing_counter.labels.assert_called_with(- operation="get_group_by_key", source="personhog", client_name=ANY- )+ assert get_group_by_key(self.team_id, self.group_type_index, self.group_key) is None- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_error", ConnectionError("connection refused")),- ("generic_exception", Exception("unexpected error")),- ]- )- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter- ):+ def test_falsy_group_returns_none(self, mock_get_client):mock_client = MagicMock()- mock_client.get_group.side_effect = exception+ mock_client.get_group.return_value = MagicMock(group=None)mock_get_client.return_value = mock_client- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_group = MagicMock(spec=Group)- mock_objects.get.return_value = mock_group-- result = get_group_by_key(self.team_id, self.group_type_index, self.group_key)+ assert get_group_by_key(self.team_id, self.group_type_index, self.group_key) is None- assert result is mock_group- mock_errors_counter.labels.assert_called_once_with(- operation="get_group_by_key",- source="personhog",- error_type="grpc_error",- 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)-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CLIENT_PATCH)- def test_orm_fallback_does_not_exist_returns_none(self, mock_get_client, mock_routing_counter, mock_errors_counter):- mock_client = MagicMock()- mock_client.get_group.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.get.side_effect = Group.DoesNotExist-- result = get_group_by_key(self.team_id, self.group_type_index, self.group_key)+ def test_missing_client_raises(self, mock_get_client):+ mock_get_client.return_value = None- assert result is None+ with self.assertRaises(RuntimeError):+ get_group_by_key(self.team_id, self.group_type_index, self.group_key)class TestGetGroupsByIdentifiers(SimpleTestCase):@@ -169,11 +94,9 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):self.group_type_index = 0@override_settings(PERSONHOG_BATCH_SIZE=2)- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CONVERTER_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_chunks_requests(self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter):+ def test_chunks_requests_and_returns_all_models(self, mock_get_client, mock_convert):# 5 keys with batch size 2 → 3 chunks (2 + 2 + 1)protos = [_make_proto_group(id=i + 1, team_id=self.team_id, group_key=f"k{i}") for i in range(5)]mock_client = MagicMock()@@ -193,252 +116,25 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):for call in mock_client.get_groups.call_args_list:assert len(call[0][0].group_identifiers) <= 2- def test_empty_group_keys_returns_empty_list_without_personhog(self):- with patch(_CLIENT_PATCH) as mock_get_client:- result = get_groups_by_identifiers(self.team_id, self.group_type_index, [])-- assert result == []- mock_get_client.assert_not_called()-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CONVERTER_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_success_returns_converted_models(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- proto_g1 = _make_proto_group(id=1, team_id=self.team_id, group_key="k1")- proto_g2 = _make_proto_group(id=2, team_id=self.team_id, group_key="k2")-- mock_response = MagicMock()- mock_response.groups = [proto_g1, proto_g2]- mock_client = MagicMock()- mock_client.get_groups.return_value = mock_response- mock_get_client.return_value = mock_client-- model1 = MagicMock()- model2 = MagicMock()- mock_convert.side_effect = [model1, model2]-- result = get_groups_by_identifiers(self.team_id, self.group_type_index, ["k1", "k2"])-- assert result == [model1, model2]- mock_routing_counter.labels.assert_called_with(- operation="get_groups_by_identifiers", source="personhog", client_name=ANY- )- mock_errors_counter.labels.assert_not_called()-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CONVERTER_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_filters_out_groups_with_zero_id(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):+ def test_filters_out_zero_id_groups(self, mock_get_client, mock_convert):proto_with_id = _make_proto_group(id=5, team_id=self.team_id, group_key="k1")proto_no_id = _make_proto_group(id=0, team_id=self.team_id, group_key="k2")-- mock_response = MagicMock()- mock_response.groups = [proto_with_id, proto_no_id]mock_client = MagicMock()- mock_client.get_groups.return_value = mock_response+ mock_client.get_groups.return_value = MagicMock(groups=[proto_with_id, proto_no_id])mock_get_client.return_value = mock_client-- model1 = MagicMock()- mock_convert.return_value = model1+ mock_convert.return_value = MagicMock()result = get_groups_by_identifiers(self.team_id, self.group_type_index, ["k1", "k2"])assert len(result) == 1- assert result[0] is model1mock_convert.assert_called_once_with(proto_with_id)- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_failure_falls_back_to_orm(self, mock_get_client, mock_routing_counter, mock_errors_counter):- mock_client = MagicMock()- mock_client.get_groups.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- orm_groups = [MagicMock(spec=Group), MagicMock(spec=Group)]- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter(orm_groups))- mock_objects.filter.return_value = mock_qs-- result = get_groups_by_identifiers(self.team_id, self.group_type_index, ["k1", "k2"])-- assert result == orm_groups- mock_errors_counter.labels.assert_called_once_with(- operation="get_groups_by_identifiers",- source="personhog",- error_type="grpc_error",- 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)-- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_client_none_falls_back_to_orm_silently(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- orm_groups = [MagicMock(spec=Group)]- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter(orm_groups))- mock_objects.filter.return_value = mock_qs-- result = get_groups_by_identifiers(self.team_id, self.group_type_index, ["k1"])-- assert result == orm_groups- mock_routing_counter.labels.assert_called_once_with(- operation="get_groups_by_identifiers", source="django_orm", client_name=ANY- )-- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_refused", ConnectionError("connection refused")),- ("generic_exception", Exception("unexpected")),- ]- )- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_error_types_always_increment_error_metric(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = exception- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_objects.filter.return_value = mock_qs-- get_groups_by_identifiers(self.team_id, self.group_type_index, ["k1"])-- mock_errors_counter.labels.assert_called_once()---class TestGetGroupByKeyEdgeCases(SimpleTestCase):- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_returns_none_group_returns_none(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_response = MagicMock()- mock_response.group = None- mock_client = MagicMock()- mock_client.get_group.return_value = mock_response- mock_get_client.return_value = mock_client-- result = get_group_by_key(10, 0, "org:123")-- assert result is None- mock_routing_counter.labels.assert_called_with(- operation="get_group_by_key", source="personhog", client_name=ANY- )-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_orm_fallback_passes_correct_filter_kwargs(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_group.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.get.side_effect = Group.DoesNotExist-- get_group_by_key(10, 2, "company:456")-- mock_objects.get.assert_called_once_with(team_id=10, group_type_index=2, group_key="company:456")-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CONVERTER_PATCH)- @patch(_CLIENT_PATCH)- def test_converter_exception_falls_back_to_orm(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- proto_group = _make_proto_group(id=7, team_id=10, group_key="org:123")- mock_response = MagicMock()- mock_response.group = proto_group- mock_client = MagicMock()- mock_client.get_group.return_value = mock_response- mock_get_client.return_value = mock_client-- mock_convert.side_effect = ValueError("malformed JSON")-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_group = MagicMock(spec=Group)- mock_objects.get.return_value = mock_group-- result = get_group_by_key(10, 0, "org:123")-- assert result is mock_group- mock_errors_counter.labels.assert_called_once()---class TestGetGroupsByIdentifiersEdgeCases(SimpleTestCase):- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_orm_fallback_passes_correct_filter_kwargs(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_objects.filter.return_value = mock_qs-- get_groups_by_identifiers(10, 2, ["k1", "k2"])-- mock_objects.filter.assert_called_once_with(team_id=10, group_type_index=2, group_key__in=["k1", "k2"])-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CONVERTER_PATCH)- @patch(_CLIENT_PATCH)- def test_all_groups_have_zero_id_returns_empty_list(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- proto_g1 = _make_proto_group(id=0, team_id=10, group_key="k1")- proto_g2 = _make_proto_group(id=0, team_id=10, group_key="k2")-- mock_response = MagicMock()- mock_response.groups = [proto_g1, proto_g2]- mock_client = MagicMock()- mock_client.get_groups.return_value = mock_response- mock_get_client.return_value = mock_client-- result = get_groups_by_identifiers(10, 0, ["k1", "k2"])-- assert result == []- mock_convert.assert_not_called()+ def test_empty_group_keys_short_circuits_without_client(self):+ with patch(_CLIENT_PATCH) as mock_get_client:+ assert get_groups_by_identifiers(self.team_id, self.group_type_index, []) == []+ mock_get_client.assert_not_called()class TestGetGroupsByTypeIndices(SimpleTestCase):@@ -446,224 +142,27 @@ class TestGetGroupsByTypeIndices(SimpleTestCase):self.team_id = 10@override_settings(PERSONHOG_BATCH_SIZE=2)- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)@patch(_CONVERTER_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_chunks_cross_product(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- # {0, 1} x {k1, k2, k3} = 6 identifiers; batch size 2 → 3 chunks+ def test_builds_cross_product_identifiers_and_chunks(self, mock_get_client, mock_convert):+ # {0, 1} x {k1, k2} = 4 identifiers; batch size 2 → 2 chunksmock_client = MagicMock()- mock_client.get_groups.side_effect = [MagicMock(groups=[]) for _ in range(3)]+ mock_client.get_groups.side_effect = [MagicMock(groups=[]), MagicMock(groups=[])]mock_get_client.return_value = mock_client- get_groups_by_type_indices(self.team_id, {0, 1}, {"k1", "k2", "k3"})+ get_groups_by_type_indices(self.team_id, {0, 1}, {"k1", "k2"})- assert mock_client.get_groups.call_count == 3+ assert mock_client.get_groups.call_count == 2total = sum(len(c[0][0].group_identifiers) for c in mock_client.get_groups.call_args_list)- assert total == 6+ assert total == 4for c in mock_client.get_groups.call_args_list:assert len(c[0][0].group_identifiers) <= 2def test_empty_group_type_indices_returns_empty_list(self):- result = get_groups_by_type_indices(self.team_id, set(), {"k1"})- assert result == []+ assert get_groups_by_type_indices(self.team_id, set(), {"k1"}) == []def test_empty_group_keys_returns_empty_list(self):- result = get_groups_by_type_indices(self.team_id, {0, 1}, set())- assert result == []-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CONVERTER_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_success_creates_cross_product_identifiers(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- proto_g1 = _make_proto_group(id=1, team_id=self.team_id, group_key="k1", group_type_index=0)- proto_g2 = _make_proto_group(id=2, team_id=self.team_id, group_key="k2", group_type_index=1)-- mock_response = MagicMock()- mock_response.groups = [proto_g1, proto_g2]- mock_client = MagicMock()- mock_client.get_groups.return_value = mock_response- mock_get_client.return_value = mock_client-- model1, model2 = MagicMock(), MagicMock()- mock_convert.side_effect = [model1, model2]-- result = get_groups_by_type_indices(self.team_id, {0, 1}, {"k1", "k2"})-- assert result == [model1, model2]- mock_client.get_groups.assert_called_once()- call_args = mock_client.get_groups.call_args[0][0]- assert call_args.team_id == self.team_id- assert len(call_args.group_identifiers) == 4-- mock_routing_counter.labels.assert_called_with(- operation="get_groups_by_type_indices", source="personhog", client_name=ANY- )- mock_errors_counter.labels.assert_not_called()-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CONVERTER_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_filters_out_zero_id_groups(- self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter- ):- proto_with_id = _make_proto_group(id=5, team_id=self.team_id, group_key="k1")- proto_no_id = _make_proto_group(id=0, team_id=self.team_id, group_key="k2")-- mock_response = MagicMock()- mock_response.groups = [proto_with_id, proto_no_id]- mock_client = MagicMock()- mock_client.get_groups.return_value = mock_response- mock_get_client.return_value = mock_client-- model1 = MagicMock()- mock_convert.return_value = model1-- result = get_groups_by_type_indices(self.team_id, {0, 1}, {"k1", "k2"})-- assert len(result) == 1- mock_convert.assert_called_once_with(proto_with_id)-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_failure_falls_back_to_orm_with_correct_filters(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- orm_groups = [MagicMock(spec=Group), MagicMock(spec=Group)]- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter(orm_groups))- mock_objects.filter.return_value = mock_qs-- result = get_groups_by_type_indices(self.team_id, {0, 2}, {"k1", "k2"})-- assert result == orm_groups- mock_objects.filter.assert_called_once_with(- team_id=self.team_id, group_type_index__in={0, 2}, group_key__in={"k1", "k2"}- )- mock_errors_counter.labels.assert_called_once()- calls = [str(c) for c in mock_routing_counter.labels.call_args_list]- assert any("django_orm" in c for c in calls)-- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_client_none_falls_back_to_orm_silently(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- orm_groups = [MagicMock(spec=Group)]- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter(orm_groups))- mock_objects.filter.return_value = mock_qs-- result = get_groups_by_type_indices(self.team_id, {0}, {"k1"})-- assert result == orm_groups- mock_routing_counter.labels.assert_called_once_with(- operation="get_groups_by_type_indices", source="django_orm", client_name=ANY- )-- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_refused", ConnectionError("connection refused")),- ("generic_exception", Exception("unexpected")),- ]- )- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_error_types_always_increment_error_metric(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = exception- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_objects.filter.return_value = mock_qs-- get_groups_by_type_indices(self.team_id, {0}, {"k1"})-- mock_errors_counter.labels.assert_called_once()---class TestOrmDatabaseErrorHandling(SimpleTestCase):- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_get_group_by_key_orm_database_error_returns_none(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_group.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.get.side_effect = DatabaseError("connection lost")-- result = get_group_by_key(10, 0, "org:123")-- assert result is None-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_get_groups_by_identifiers_orm_database_error_returns_empty_list(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.filter.side_effect = DatabaseError("connection lost")-- result = get_groups_by_identifiers(10, 0, ["k1", "k2"])-- assert result == []-- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_get_groups_by_type_indices_orm_database_error_returns_empty_list(- self, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.get_groups.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.filter.side_effect = DatabaseError("connection lost")-- result = get_groups_by_type_indices(10, {0, 1}, {"k1", "k2"})-- assert result == []+ assert get_groups_by_type_indices(self.team_id, {0, 1}, set()) == []class TestCreateGroup(SimpleTestCase):@@ -674,19 +173,13 @@ class TestCreateGroup(SimpleTestCase):self.properties = {"name": "Acme"}@patch("posthog.models.group.util.raw_create_group_ch")- @patch(_ROUTING_TOTAL_PATCH)@patch(_CONVERTER_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_success_returns_converted_model(- self, mock_get_client, mock_convert, mock_routing_counter, mock_ch- ):+ def test_builds_request_converts_response_and_writes_clickhouse(self, mock_get_client, mock_convert, mock_ch):proto_group = _make_proto_group(id=42, team_id=self.team_id, group_key=self.group_key)- mock_response = MagicMock()- mock_response.group = proto_groupmock_client = MagicMock()- mock_client.create_group.return_value = mock_response+ mock_client.create_group.return_value = MagicMock(group=proto_group)mock_get_client.return_value = mock_client-fake_model = MagicMock()mock_convert.return_value = fake_model@@ -698,160 +191,50 @@ class TestCreateGroup(SimpleTestCase):)assert result is fake_model- mock_client.create_group.assert_called_once()req = mock_client.create_group.call_args[0][0]assert req.team_id == self.team_idassert 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=ANY)mock_ch.assert_called_once()@patch("posthog.models.group.util.raw_create_group_ch")- @patch(_ROUTING_TOTAL_PATCH)@patch(_CLIENT_PATCH)- def test_personhog_client_none_falls_back_to_orm(self, mock_get_client, mock_routing_counter, mock_ch):- mock_get_client.return_value = None-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_group = MagicMock(spec=Group)- mock_objects.create.return_value = mock_group-- result = create_group(- team_id=self.team_id,- group_type_index=self.group_type_index,- group_key=self.group_key,- properties=self.properties,- )-- assert result is mock_group- mock_objects.create.assert_called_once()- mock_routing_counter.labels.assert_called_with(- operation="create_group", source="django_orm", client_name=ANY- )-- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_error", ConnectionError("connection refused")),- ]- )- @patch("posthog.models.group.util.raw_create_group_ch")- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter, mock_ch- ):+ def test_clickhouse_write_happens_even_when_personhog_fails(self, mock_get_client, mock_ch):mock_client = MagicMock()- mock_client.create_group.side_effect = exception+ mock_client.create_group.side_effect = RuntimeError("grpc timeout")mock_get_client.return_value = mock_client- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_group = MagicMock(spec=Group)- mock_objects.create.return_value = mock_group-- result = create_group(- team_id=self.team_id,- group_type_index=self.group_type_index,- group_key=self.group_key,- properties=self.properties,- )-- assert result is mock_group- mock_errors_counter.labels.assert_called_once_with(- operation="create_group",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )-- @patch("posthog.models.group.util.raw_create_group_ch")- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_clickhouse_write_always_happens(self, mock_get_client, mock_routing_counter, mock_ch):- mock_get_client.return_value = None-- from posthog.models.group.group import Group-- with patch.object(Group, "objects") as mock_objects:- mock_objects.create.return_value = MagicMock(spec=Group)+ with self.assertRaises(RuntimeError):create_group(team_id=self.team_id,group_type_index=self.group_type_index,group_key=self.group_key,properties=self.properties,)- mock_ch.assert_called_once()++ mock_ch.assert_called_once()class TestSaveGroup(SimpleTestCase):def _make_group_instance(self):- mock_group = MagicMock()- mock_group.team_id = 10- mock_group.group_type_index = 0- mock_group.group_key = "org:123"- mock_group.group_properties = {"name": "Acme"}- return mock_group-- @patch(_ROUTING_TOTAL_PATCH)+ group = MagicMock()+ group.team_id = 10+ group.group_type_index = 0+ group.group_key = "org:123"+ group.group_properties = {"name": "Acme"}+ return group+@patch(_CLIENT_PATCH)- def test_personhog_success_does_not_call_orm_save(self, mock_get_client, mock_routing_counter):+ def test_builds_update_request_with_group_properties_mask(self, mock_get_client):mock_client = MagicMock()- mock_client.update_group.return_value = MagicMock()mock_get_client.return_value = mock_client- group = self._make_group_instance()- save_group(group)+ save_group(self._make_group_instance())- mock_client.update_group.assert_called_once()req = mock_client.update_group.call_args[0][0]assert req.team_id == 10assert req.group_type_index == 0assert req.group_key == "org:123"assert req.update_mask == ["group_properties"]assert b'"name": "Acme"' in req.group_properties- group.save.assert_not_called()- mock_routing_counter.labels.assert_called_with(operation="group_save", source="personhog", client_name=ANY)-- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_client_none_falls_back_to_orm_save(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None-- group = self._make_group_instance()- save_group(group)-- group.save.assert_called_once()- mock_routing_counter.labels.assert_called_with(operation="group_save", source="django_orm", client_name=ANY)-- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_error", ConnectionError("connection refused")),- ]- )- @patch(_ROUTING_ERRORS_PATCH)- @patch(_ROUTING_TOTAL_PATCH)- @patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm_save(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.update_group.side_effect = exception- mock_get_client.return_value = mock_client-- group = self._make_group_instance()- save_group(group)-- group.save.assert_called_once()- mock_errors_counter.labels.assert_called_once_with(- operation="group_save",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )diff --git a/posthog/models/group/util.py b/posthog/models/group/util.pyindex 180946e365a7..1d135972c111 100644--- a/posthog/models/group/util.py+++ b/posthog/models/group/util.py@@ -5,7 +5,6 @@ from typing import Optional, Unionfrom zoneinfo import ZoneInfofrom django.conf import settings-from django.db import DatabaseErrorfrom django.utils.timezone import nowimport structlog@@ -16,7 +15,6 @@ from posthog.kafka_client.topics import KAFKA_GROUPSfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.group import Groupfrom posthog.models.group.sql import INSERT_GROUP_SQL-from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_namelogger = structlog.get_logger(__name__)@@ -75,14 +73,15 @@ def create_group(timestamp=timestamp,)- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.converters import proto_group_to_modelfrom posthog.personhog_client.proto import CreateGroupRequest- client = get_personhog_client()- if client is not None:- try:- resp = client.create_group(+ client = require_personhog_client()+ return personhog_call(+ "create_group",+ lambda: proto_group_to_model(+ client.create_group(CreateGroupRequest(team_id=team_id,group_type_index=group_type_index,@@ -90,192 +89,75 @@ def create_group(group_properties=json.dumps(properties).encode(),created_at=int(timestamp.timestamp() * 1000),)- )- PERSONHOG_ROUTING_TOTAL.labels(- operation="create_group", source="personhog", client_name=get_client_name()- ).inc()- return proto_group_to_model(resp.group)- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="create_group",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_create_group_failure",- team_id=team_id,- group_type_index=group_type_index,- group_key=group_key,- exc_info=True,- )-- PERSONHOG_ROUTING_TOTAL.labels(operation="create_group", source="django_orm", client_name=get_client_name()).inc()- group = Group.objects.create( # nosemgrep: no-direct-persons-db-orm- team_id=team_id,- group_type_index=group_type_index,- group_key=group_key,- group_properties=properties,- created_at=timestamp,- version=0,+ ).group+ ),+ caller_tag="group/create_group",)- return groupdef save_group(group: Group, *, operation: str = "group_save") -> None:- """Save a Group's group_properties via personhog, falling back to ORM.-- Only group_properties is synced on the personhog path. The ORM fallback- calls group.save() which persists all fields, but once the fallback is- removed this will only write group_properties.- """- from posthog.personhog_client.client import get_personhog_client+ """Save a Group's group_properties via personhog. Only group_properties is synced."""+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import UpdateGroupRequest- client = get_personhog_client()- if client is not None:- try:- client.update_group(- UpdateGroupRequest(- team_id=group.team_id,- group_type_index=group.group_type_index,- group_key=group.group_key,- update_mask=["group_properties"],- group_properties=json.dumps(group.group_properties).encode(),- )- )- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()- return- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation=operation,- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_save_group_failure",+ client = require_personhog_client()++ def _update() -> None:+ client.update_group(+ UpdateGroupRequest(team_id=group.team_id,group_type_index=group.group_type_index,group_key=group.group_key,- exc_info=True,+ update_mask=["group_properties"],+ group_properties=json.dumps(group.group_properties).encode(),)+ )- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()- group.save()+ personhog_call(operation, _update, caller_tag="group/save_group")def get_group_by_key(team_id: int, group_type_index: int, group_key: str) -> Group | None:- """Fetch a single Group via personhog, falling back to ORM on error."""- from posthog.personhog_client.client import get_personhog_client+ """Fetch a single Group via personhog. Returns None when the group does not exist."""+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.converters import proto_group_to_modelfrom posthog.personhog_client.proto import GetGroupRequest- client = get_personhog_client()- if client is not None:- try:- resp = client.get_group(- GetGroupRequest(team_id=team_id, group_type_index=group_type_index, group_key=group_key)- )- if resp.group and resp.group.id:- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_group_by_key", source="personhog", client_name=get_client_name()- ).inc()- return proto_group_to_model(resp.group)- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_group_by_key", source="personhog", client_name=get_client_name()- ).inc()- return None- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_group_by_key",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_get_group_by_key_failure",- team_id=team_id,- group_type_index=group_type_index,- group_key=group_key,- exc_info=True,- )+ client = require_personhog_client()- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_group_by_key", source="django_orm", client_name=get_client_name()- ).inc()- try:- return Group.objects.get( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, group_type_index=group_type_index, group_key=group_key- )- except Group.DoesNotExist:- return None- except DatabaseError:- logger.warning(- "persons_db_get_group_by_key_failure",- team_id=team_id,- group_type_index=group_type_index,- group_key=group_key,- exc_info=True,+ def _fetch() -> Group | None:+ resp = client.get_group(+ GetGroupRequest(team_id=team_id, group_type_index=group_type_index, group_key=group_key))+ if resp.group and resp.group.id:+ return proto_group_to_model(resp.group)return None+ return personhog_call("get_group_by_key", _fetch, caller_tag="group/get_group_by_key")+def get_groups_by_identifiers(team_id: int, group_type_index: int, group_keys: list[str]) -> list[Group]:- """Fetch multiple Groups via personhog, falling back to ORM on error."""- from posthog.personhog_client.client import get_personhog_client+ """Fetch multiple Groups via personhog."""+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.converters import proto_group_to_modelfrom posthog.personhog_client.proto import GetGroupsRequest, GroupIdentifierif not group_keys:return []- client = get_personhog_client()- if client is not None:- try:- groups: list[Group] = []- for i in range(0, len(group_keys), settings.PERSONHOG_BATCH_SIZE):- identifiers = [- GroupIdentifier(group_type_index=group_type_index, group_key=key)- for key in group_keys[i : i + settings.PERSONHOG_BATCH_SIZE]- ]- resp = client.get_groups(GetGroupsRequest(team_id=team_id, group_identifiers=identifiers))- groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_groups_by_identifiers", source="personhog", client_name=get_client_name()- ).inc()- return groups- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_groups_by_identifiers",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_get_groups_by_identifiers_failure",- team_id=team_id,- group_type_index=group_type_index,- exc_info=True,- )+ client = require_personhog_client()- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_groups_by_identifiers", source="django_orm", client_name=get_client_name()- ).inc()- try:- return list(- Group.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, group_type_index=group_type_index, group_key__in=group_keys- )- )- except DatabaseError:- logger.warning(- "persons_db_get_groups_by_identifiers_failure",- team_id=team_id,- group_type_index=group_type_index,- exc_info=True,- )- return []+ def _fetch() -> list[Group]:+ groups: list[Group] = []+ for i in range(0, len(group_keys), settings.PERSONHOG_BATCH_SIZE):+ identifiers = [+ GroupIdentifier(group_type_index=group_type_index, group_key=key)+ for key in group_keys[i : i + settings.PERSONHOG_BATCH_SIZE]+ ]+ resp = client.get_groups(GetGroupsRequest(team_id=team_id, group_identifiers=identifiers))+ groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)+ return groups++ return personhog_call("get_groups_by_identifiers", _fetch, caller_tag="group/get_groups_by_identifiers")def get_groups_by_type_indices(team_id: int, group_type_indices: set[int], group_keys: set[str]) -> list[Group]:@@ -283,62 +165,28 @@ def get_groups_by_type_indices(team_id: int, group_type_indices: set[int], groupCreates a GroupIdentifier for each (group_type_index, group_key) combinationand fetches them all in one gRPC/ORM call."""- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.converters import proto_group_to_modelfrom posthog.personhog_client.proto import GetGroupsRequest, GroupIdentifierif not group_type_indices or not group_keys:return []- client = get_personhog_client()- if client is not None:- try:- identifiers = [- GroupIdentifier(group_type_index=gti, group_key=key) for gti in group_type_indices for key in group_keys- ]- groups: list[Group] = []- for i in range(0, len(identifiers), settings.PERSONHOG_BATCH_SIZE):- resp = client.get_groups(- GetGroupsRequest(- team_id=team_id, group_identifiers=identifiers[i : i + settings.PERSONHOG_BATCH_SIZE]- )- )- groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_groups_by_type_indices", source="personhog", client_name=get_client_name()- ).inc()- return groups- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_groups_by_type_indices",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning(- "personhog_get_groups_by_type_indices_failure",- team_id=team_id,- group_type_indices=list(group_type_indices),- exc_info=True,- )+ client = require_personhog_client()- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_groups_by_type_indices", source="django_orm", client_name=get_client_name()- ).inc()- try:- return list(- Group.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, group_type_index__in=group_type_indices, group_key__in=group_keys+ def _fetch() -> list[Group]:+ identifiers = [+ GroupIdentifier(group_type_index=gti, group_key=key) for gti in group_type_indices for key in group_keys+ ]+ groups: list[Group] = []+ for i in range(0, len(identifiers), settings.PERSONHOG_BATCH_SIZE):+ resp = client.get_groups(+ GetGroupsRequest(team_id=team_id, group_identifiers=identifiers[i : i + settings.PERSONHOG_BATCH_SIZE]))- )- except DatabaseError:- logger.warning(- "persons_db_get_groups_by_type_indices_failure",- team_id=team_id,- group_type_indices=list(group_type_indices),- exc_info=True,- )- return []+ groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)+ return groups++ return personhog_call("get_groups_by_type_indices", _fetch, caller_tag="group/get_groups_by_type_indices")def get_aggregation_target_field(diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.pyindex cd653f0ee433..c8438dca58b6 100644--- a/posthog/models/group_type_mapping.py+++ b/posthog/models/group_type_mapping.py@@ -1,11 +1,9 @@from __future__ import annotationsimport json-from typing import TYPE_CHECKING, Any, TypeVar+from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:- from collections.abc import Callable-from posthog.models.project import Projectfrom posthog.models.team.team import Teamfrom posthog.personhog_client.client import PersonHogClient@@ -13,25 +11,20 @@ if TYPE_CHECKING:from django.conf import settingsfrom django.contrib.postgres.fields import ArrayFieldfrom django.db import DatabaseError, models-from django.db.models import Countfrom django.utils import timezoneimport structlogfrom prometheus_client import Counterfrom posthog.models.utils import RootTeamMixin-from posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITEfrom posthog.personhog_client import ReadConsistency, consistency_to_read_options-from posthog.personhog_client.caller_tag import personhog_caller_tag-from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name+from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.rbac.decorators import field_access_controlfrom posthog.storage.hypercache import HyperCacheDependencyUnavailablefrom posthog.utils import capture_exception_throttled, get_safe_cache, safe_cache_delete, safe_cache_setlogger = structlog.get_logger(__name__)-_T = TypeVar("_T")-GROUP_TYPES_CACHE_TTL = 60 * 5 # 5 minutesGROUP_TYPES_STALE_CACHE_TTL = 60 * 60 * 24 # 24 hours — last-known-good fallback during outagesGROUP_TYPES_NEGATIVE_CACHE_TTL = 30 # seconds — short so we detect DB recovery quickly@@ -44,9 +37,7 @@ GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX = "group_types_for_project_confirme# via the cache so many workers failing at once report at most once per window.GROUP_TYPES_FAILURE_CAPTURE_THROTTLE_TTL = 60 # seconds-# Terminal failure of a group-type fetch, after all fallbacks. Separate from the-# personhog routing counters: these sites query the persons DB directly via the ORM-# and never call personhog, so the failure must not land on the personhog metrics.+# Terminal failure of a group-type fetch, after all fallbacks (stale cache, etc.).GROUP_TYPES_FETCH_FAILURES = Counter("posthog_group_types_fetch_failures","Terminal failures fetching group-type mappings, by operation/source/error_type",@@ -75,7 +66,7 @@ def _record_group_types_fetch_failure(*, operation: str, log_event: str, exc: BaThe counter is always incremented; only the capture is throttled. Each log linerecords whether the capture ran or was throttled."""- GROUP_TYPES_FETCH_FAILURES.labels(operation=operation, source="django_orm", error_type="db_error").inc()+ GROUP_TYPES_FETCH_FAILURES.labels(operation=operation, source="personhog", error_type="db_error").inc()throttle_key = f"group_types_failure_capture_throttle:{operation}"captured = capture_exception_throttled(throttle_key, exc, GROUP_TYPES_FAILURE_CAPTURE_THROTTLE_TTL)@@ -90,44 +81,6 @@ def _record_group_types_fetch_failure(*, operation: str, log_event: str, exc: Ba)-def _personhog_routed(- operation: str,- personhog_fn: Callable[[PersonHogClient], _T],- orm_fn: Callable[[], _T],- *,- caller_tag: str | None = None,- **log_fields: Any,-) -> _T:- """Try personhog first, fall back to ORM on failure or when disabled.-- ``operation`` is the RPC being performed (used in metrics).- ``caller_tag`` is the granular calling context (used in personhog caller- tagging for observability). Defaults to ``operation`` when not given.-- ORM exceptions are NOT caught — callers handle their own DatabaseError- recovery (stale cache, fail-closed, etc.).- """- from posthog.personhog_client.client import get_personhog_client-- tag = caller_tag or operation-- client = get_personhog_client()- if client is not None:- try:- with personhog_caller_tag(f"group_type_mapping/{tag}"):- result = personhog_fn(client)- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()- return result- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation=operation, source="personhog", error_type="grpc_error", client_name=get_client_name()- ).inc()- logger.warning("personhog_%s_failure", operation, **log_fields, exc_info=True)-- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()- return orm_fn()--# Defined here for reuse between OS and EEGROUP_TYPE_MAPPING_SERIALIZER_FIELDS = ["group_type",@@ -223,7 +176,7 @@ def _fetch_group_types_via_personhog(client: PersonHogClient, project_id: int) -def get_group_types_for_project(project_id: int, *, caller_tag: str | None = None) -> list[dict[str, Any]]:- """Fetch group types from cache, falling back to personhog then ORM, then stale cache, then empty list."""+ """Fetch group types from cache, falling back to personhog, then stale cache, then empty list."""cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{project_id}"stale_cache_key = f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{project_id}"@@ -232,16 +185,12 @@ def get_group_types_for_project(project_id: int, *, caller_tag: str | None = Nonreturn cachedtry:- result = _personhog_routed(+ client = require_personhog_client()+ result = personhog_call("get_group_types_for_project",- lambda client: _fetch_group_types_via_personhog(client, project_id),- lambda: list(- GroupTypeMapping.objects.filter(project_id=project_id) # nosemgrep: no-direct-persons-db-orm- .order_by("group_type_index")- .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)- ),- caller_tag=caller_tag,- project_id=project_id,+ lambda: _fetch_group_types_via_personhog(client, project_id),+ caller_tag=f"group_type_mapping/{caller_tag or 'get_group_types_for_project'}",+ reraise_as=DatabaseError,)except DatabaseError as exc:_record_group_types_fetch_failure(@@ -273,18 +222,14 @@ def _fetch_group_types_for_team_via_personhog(client: PersonHogClient, team_id:def get_group_types_for_team(team_id: int, *, caller_tag: str | None = None) -> list[dict[str, Any]]:- """Fetch group types for a team via personhog, falling back to ORM on error."""+ """Fetch group types for a team via personhog."""try:- return _personhog_routed(+ client = require_personhog_client()+ return personhog_call("get_group_types_for_team",- lambda client: _fetch_group_types_for_team_via_personhog(client, team_id),- lambda: list(- GroupTypeMapping.objects.filter(team_id=team_id) # nosemgrep: no-direct-persons-db-orm- .order_by("group_type_index")- .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)- ),- caller_tag=caller_tag,- team_id=team_id,+ lambda: _fetch_group_types_for_team_via_personhog(client, team_id),+ caller_tag=f"group_type_mapping/{caller_tag or 'get_group_types_for_team'}",+ reraise_as=DatabaseError,)except DatabaseError as exc:_record_group_types_fetch_failure(@@ -397,33 +342,26 @@ def get_group_types_for_projects(project_ids: list[int], *, caller_tag: str | None = None) -> dict[int, list[dict[str, Any]]]:"""Batch fetch group types for multiple projects via personhog, falling back to- ORM, then to the per-project stale cache on a DB failure.+ the per-project stale cache on failure.- Raises GroupTypesUnavailable if the persons DB is unavailable and any requested+ Raises GroupTypesUnavailable if personhog is unavailable and any requestedproject has no cached last-known-good, rather than returning an all-emptymapping. Callers must handle that case."""- def _personhog_fn(client: PersonHogClient) -> dict[int, list[dict[str, Any]]]:+ def _fn() -> dict[int, list[dict[str, Any]]]:+ client = require_personhog_client()result = _fetch_group_types_for_projects_via_personhog(client, project_ids)for pid in project_ids:result.setdefault(pid, [])return result- def _orm_fn() -> dict[int, list[dict[str, Any]]]:- result: dict[int, list[dict[str, Any]]] = {pid: [] for pid in project_ids}- for row in (- GroupTypeMapping.objects.filter(project_id__in=project_ids) # nosemgrep: no-direct-persons-db-orm- .order_by("group_type_index")- .values("project_id", *GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)- ):- pid = row.pop("project_id")- result.setdefault(pid, []).append(row)- return result-try:- result = _personhog_routed(- "get_group_types_for_projects", _personhog_fn, _orm_fn, caller_tag=caller_tag, project_ids=project_ids+ result = personhog_call(+ "get_group_types_for_projects",+ _fn,+ caller_tag=f"group_type_mapping/{caller_tag or 'get_group_types_for_projects'}",+ reraise_as=DatabaseError,)except DatabaseError as exc:return _recover_projects_from_stale_or_fail(project_ids, exc)@@ -433,22 +371,19 @@ def get_group_types_for_projects(def count_group_type_mappings_per_team(*, caller_tag: str | None = None) -> list[dict[str, int]]:- """Count group type mappings per team via personhog, falling back to ORM."""+ """Count group type mappings per team via personhog."""from posthog.personhog_client.proto import CountGroupTypeMappingsRequesttry:- return _personhog_routed(+ client = require_personhog_client()+ return personhog_call("count_group_type_mappings_per_team",- lambda client: [+ lambda: [{"team_id": c.team_id, "total": c.count}for c in client.count_group_type_mappings(CountGroupTypeMappingsRequest()).counts],- lambda: list(- GroupTypeMapping.objects.values("team_id") # nosemgrep: no-direct-persons-db-orm- .annotate(total=Count("id"))- .order_by("team_id") # nosemgrep: no-direct-persons-db-orm- ),- caller_tag=caller_tag,+ caller_tag=f"group_type_mapping/{caller_tag or 'count_group_type_mappings_per_team'}",+ reraise_as=DatabaseError,)except DatabaseError:logger.warning("count_group_type_mappings_orm_failure", exc_info=True)@@ -529,11 +464,10 @@ def _fetch_group_types_for_project_direct(from posthog.personhog_client.converters import proto_group_type_mapping_to_dictfrom posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdRequest- db_alias = PERSONS_DB_FOR_WRITE if consistency == "strong" else PERSONS_DB_FOR_READ-- return _personhog_routed(+ client = require_personhog_client()+ return personhog_call("get_group_types_for_project_direct",- lambda client: sorted(+ lambda: sorted([proto_group_type_mapping_to_dict(m)for m in client.get_group_type_mappings_by_project_id(@@ -545,14 +479,8 @@ def _fetch_group_types_for_project_direct(],key=lambda d: d["group_type_index"],),- lambda: list(- GroupTypeMapping.objects.using(db_alias) # nosemgrep: no-direct-persons-db-orm- .filter(project_id=project_id)- .order_by("group_type_index")- .values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS)- ),- caller_tag=caller_tag,- project_id=project_id,+ caller_tag=f"group_type_mapping/{caller_tag or 'get_group_types_for_project_direct'}",+ reraise_as=DatabaseError,)@@ -588,7 +516,7 @@ def get_group_type_mapping_instance(if row["group_type_index"] == group_type_index:return _dict_to_group_type_mapping_model(row, project_id=project_id, team=team)- # Cache may be stale — bust it and retry once via the full personhog/ORM chain.+ # Cache may be stale — bust it and retry once via personhog.invalidate_group_types_cache(project_id)rows = get_group_types_for_project(project_id, caller_tag=caller_tag)for row in rows:@@ -606,7 +534,7 @@ def update_group_type_mapping_fields(fields: dict[str, Any],caller_tag: str | None = None,) -> None:- """Update specific fields on a GroupTypeMapping via personhog, falling back to ORM.+ """Update specific fields on a GroupTypeMapping via personhog.`fields` maps model field names to values — e.g. {"name_singular": "Org", "name_plural": "Orgs"}.For `detail_dashboard_id`, pass None to clear or an int to set.@@ -614,7 +542,9 @@ def update_group_type_mapping_fields("""from posthog.personhog_client.proto import UpdateGroupTypeMappingRequest- def _personhog_fn(client: PersonHogClient) -> None:+ client = require_personhog_client()++ def _fn() -> None:update_mask: list[str] = list(fields.keys())kwargs: dict[str, Any] = {"project_id": instance.project_id,@@ -633,43 +563,31 @@ def update_group_type_mapping_fields(kwargs["default_columns"] = json.dumps(fields["default_columns"]).encode()client.update_group_type_mapping(UpdateGroupTypeMappingRequest(**kwargs))- def _orm_fn() -> None:- GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm- project_id=instance.project_id,- group_type_index=instance.group_type_index,- ).update(**fields)-- _personhog_routed(+ personhog_call("update_group_type_mapping_fields",- _personhog_fn,- _orm_fn,- caller_tag=caller_tag,- project_id=instance.project_id,- group_type_index=instance.group_type_index,+ _fn,+ caller_tag=f"group_type_mapping/{caller_tag or 'update_group_type_mapping_fields'}",+ reraise_as=DatabaseError,)for field_name, value in fields.items():setattr(instance, field_name, value)def delete_group_type_mapping(instance: GroupTypeMapping, *, caller_tag: str | None = None) -> None:- """Delete a GroupTypeMapping via personhog, falling back to ORM."""+ """Delete a GroupTypeMapping via personhog."""from posthog.personhog_client.proto import DeleteGroupTypeMappingRequest- _personhog_routed(+ client = require_personhog_client()+ personhog_call("delete_group_type_mapping",- lambda client: client.delete_group_type_mapping(+ lambda: client.delete_group_type_mapping(DeleteGroupTypeMappingRequest(project_id=instance.project_id,group_type_index=instance.group_type_index,)),- lambda: GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm- project_id=instance.project_id,- group_type_index=instance.group_type_index,- ).delete(),- caller_tag=caller_tag,- project_id=instance.project_id,- group_type_index=instance.group_type_index,+ caller_tag=f"group_type_mapping/{caller_tag or 'delete_group_type_mapping'}",+ reraise_as=DatabaseError,)@@ -679,11 +597,12 @@ def clear_dashboard_from_group_type_mapping("""Clear detail_dashboard_id from any GroupTypeMapping referencing this dashboard.Uses GetGroupTypeMappingByDashboardId to find the mapping, then UpdateGroupTypeMapping to clear it.- Falls back to ORM filter/update."""from posthog.personhog_client.proto import GetGroupTypeMappingByDashboardIdRequest, UpdateGroupTypeMappingRequest- def _personhog_fn(client: PersonHogClient) -> None:+ client = require_personhog_client()++ def _fn() -> None:resp = client.get_group_type_mapping_by_dashboard_id(GetGroupTypeMappingByDashboardIdRequest(team_id=team_id, dashboard_id=dashboard_id))@@ -697,20 +616,9 @@ def clear_dashboard_from_group_type_mapping()invalidate_group_types_cache(resp.mapping.project_id)- def _orm_fn() -> None:- GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm- detail_dashboard_id=dashboard_id- ).update( # nosemgrep: no-direct-persons-db-orm- detail_dashboard_id=None- )- if project_id is not None:- invalidate_group_types_cache(project_id)-- _personhog_routed(+ personhog_call("clear_dashboard_from_group_type_mapping",- _personhog_fn,- _orm_fn,- caller_tag=caller_tag,- team_id=team_id,- dashboard_id=dashboard_id,+ _fn,+ caller_tag=f"group_type_mapping/{caller_tag or 'clear_dashboard_from_group_type_mapping'}",+ reraise_as=DatabaseError,)diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.pyindex a07b3b6d3070..54165de3ec9e 100644--- a/posthog/models/person/bulk_delete.py+++ b/posthog/models/person/bulk_delete.py@@ -6,7 +6,6 @@ from datetime import timedeltafrom typing import castfrom django.conf import settings-from django.db.models import Prefetchimport structlogfrom loginas.utils import is_impersonated_session@@ -14,7 +13,7 @@ from temporalio import commonfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.person import Person, PersonDistinctId+from posthog.models.person import Personfrom posthog.models.person.util import (_fetch_persons_by_distinct_ids_via_personhog,_fetch_persons_by_uuids_via_personhog,@@ -22,7 +21,6 @@ from posthog.models.person.util import (delete_persons_from_postgres,)from posthog.models.user import User-from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.session_replay.delete_recordings.types import DeletionConfig, RecordingsWithPersonInput@@ -35,68 +33,24 @@ class PersonProfileDeletionResult:errors: list[uuid_lib.UUID] = field(default_factory=list)-# Columns required by the deletion path:-# - id, team_id: Person.delete() WHERE clause (single-partition delete on posthog_person_new)-# - uuid: ClickHouse tombstone, AsyncDeletion key, recording workflow id, activity log-# - version, created_at: delete_person() -> _delete_person() (Kafka tombstone payload)-# Everything else (notably ``properties``, a large JSONB) is excluded to keep row size small.-_PERSON_DELETION_COLUMNS = ("id", "team_id", "uuid", "version", "created_at")--def resolve_persons_for_deletion(team_id: int,uuids: builtins.list[str] | None,distinct_ids: builtins.list[str] | None,) -> builtins.list[Person]:- """Materialize Persons matching either uuids or distinct_ids.-- Goes straight to personhog, falling back to ORM only on error or if- the client is not configured.- """- from posthog.personhog_client.client import get_personhog_client+ """Materialize Persons matching either uuids or distinct_ids, via personhog."""+ from posthog.personhog_client.client import personhog_callif not uuids and not distinct_ids:return []- client = get_personhog_client()- if client is not None:- try:- # Unbounded distinct_ids: downstream recording deletion needs the full set per person.- with personhog_caller_tag("persons/deletion-resolve"):- if uuids:- return _fetch_persons_by_uuids_via_personhog(team_id, uuids)- else:- return _fetch_persons_by_distinct_ids_via_personhog(team_id, cast(builtins.list[str], distinct_ids))- except Exception:- logger.warning("resolve_persons_for_deletion_personhog_failure", team_id=team_id, exc_info=True)-- # ORM fallback- persons_queryset = (- Person.objects.filter(team_id=team_id) # nosemgrep: no-direct-persons-db-orm- .only(*_PERSON_DELETION_COLUMNS)- .prefetch_related(- Prefetch(- "persondistinctid_set",- # nosemgrep: no-direct-persons-db-orm- queryset=PersonDistinctId.objects.filter(- team_id=team_id- ).order_by( # nosemgrep: no-direct-persons-db-orm- "id"- ), # nosemgrep: no-direct-persons-db-orm- to_attr="distinct_ids_cache",- )- )- )- if uuids:- persons_queryset = persons_queryset.filter(uuid__in=uuids)- elif distinct_ids:- person_ids = PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, distinct_id__in=distinct_ids- ).values_list( # nosemgrep: no-direct-persons-db-orm- "person_id", flat=True- )- persons_queryset = persons_queryset.filter(id__in=person_ids)- return list(persons_queryset)+ # Unbounded distinct_ids: downstream recording deletion needs the full set per person.+ def _fetch() -> builtins.list[Person]:+ if uuids:+ return _fetch_persons_by_uuids_via_personhog(team_id, uuids)+ return _fetch_persons_by_distinct_ids_via_personhog(team_id, cast(builtins.list[str], distinct_ids))++ return personhog_call("resolve_persons_for_deletion", _fetch, caller_tag="persons/deletion-resolve")def delete_persons_profile(diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.pyindex 8efff3bfcf69..b8ff4930a3d9 100644--- a/posthog/models/person/deletion.py+++ b/posthog/models/person/deletion.py@@ -1,12 +1,10 @@from typing import Optional-from django.db import router, transaction-import structlogfrom rest_framework.exceptions import NotFoundfrom posthog.clickhouse.client import sync_execute-from posthog.models.person import Person, PersonDistinctId+from posthog.models.person import Personfrom posthog.models.person.util import create_person, create_person_distinct_idlogger = structlog.get_logger(__name__)@@ -62,8 +60,6 @@ def _get_version_for_distinct_id(team_id: int, distinct_id: str) -> int:def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, int]]):- # DB alias for the ORM-fallback person-version write below (handles persons_db_writer routing in production)- db_alias = router.db_for_write(PersonDistinctId) or "default"reset_person_uuids: set[str] = set()for distinct_id, version in distinct_id_versions:@@ -72,9 +68,8 @@ def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, in# since they no longer belong to deleted persons# it's safer to throw and exit if anything went wrong- # No transaction here: the write goes through personhog (an external RPC that- # can't join a Postgres transaction) or, on fallback, an ORM write that scopes- # its own atomic block. See _set_distinct_id_version_floor_via_orm.+ # The write goes through personhog (an external RPC that can't join a+ # Postgres transaction), so there is no surrounding atomic block.person = _update_distinct_id_in_postgres(distinct_id, version, team_id)# Update ClickHouse via Kafka message@@ -94,34 +89,30 @@ def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, in# making the person invisible to analytics queriesif person_uuid not in reset_person_uuids:reset_person_uuids.add(person_uuid)- _reset_person_in_clickhouse(team_id, person, db_alias)+ _reset_person_in_clickhouse(team_id, person)def _update_distinct_id_in_postgres(distinct_id: str, version: int, team_id: int) -> Optional[Person]:"""Raise the distinct_id's version to at least `version` and return its person.Routes through SetPersonDistinctIdVersionFloor (guarded — never lowers the- version), falling back to a direct ORM read+save. Returns None when the- distinct_id doesn't exist (it hasn't been re-used yet).+ version). Returns None when the distinct_id doesn't exist (it hasn't been+ re-used yet)."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_call- return _personhog_routed(+ return personhog_call("set_person_distinct_id_version_floor",lambda: _set_distinct_id_version_floor_via_personhog(team_id, distinct_id, version),- lambda: _set_distinct_id_version_floor_via_orm(team_id, distinct_id, version),- team_id=team_id,)def _set_distinct_id_version_floor_via_personhog(team_id: int, distinct_id: str, version: int) -> Optional[Person]:- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import require_personhog_clientfrom posthog.personhog_client.converters import proto_person_to_modelfrom posthog.personhog_client.proto import SetPersonDistinctIdVersionFloorRequest- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = require_personhog_client()resp = client.set_person_distinct_id_version_floor(SetPersonDistinctIdVersionFloorRequest(team_id=team_id, distinct_id=distinct_id, min_version=version)@@ -132,28 +123,6 @@ def _set_distinct_id_version_floor_via_personhog(team_id: int, distinct_id: str,return proto_person_to_model(resp.person, distinct_ids=[distinct_id])-def _set_distinct_id_version_floor_via_orm(team_id: int, distinct_id: str, version: int) -> Optional[Person]:- # Scope the transaction to exactly this local read+write. The personhog path makes- # no Postgres writes, so the caller must not wrap the routed call in an atomic block.- db_alias = router.db_for_write(PersonDistinctId) or "default"- with transaction.atomic(using=db_alias):- person_distinct_id = (- PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, distinct_id=distinct_id- )- .select_related("person")- .first()- )- if person_distinct_id is None:- logger.info(f"Distinct id {distinct_id} hasn't been re-used yet and can cause problems in the future")- return None- # Guarded floor: never lower the stored version (matches the RPC semantics).- if person_distinct_id.version is None or person_distinct_id.version < version:- person_distinct_id.version = version- person_distinct_id.save()- return person_distinct_id.person--def _get_person_version_if_deleted(team_id: int, person_uuid: str) -> Optional[int]:"""Returns the max version if the person is soft-deleted in ClickHouse, None otherwise."""rows = sync_execute(@@ -172,7 +141,7 @@ def _get_person_version_if_deleted(team_id: int, person_uuid: str) -> Optional[ireturn max_version-def _reset_person_in_clickhouse(team_id: int, person: Person, db_alias: str) -> None:+def _reset_person_in_clickhouse(team_id: int, person: Person) -> None:person_uuid = str(person.uuid)max_version = _get_person_version_if_deleted(team_id, person_uuid)if max_version is None:@@ -183,7 +152,7 @@ def _reset_person_in_clickhouse(team_id: int, person: Person, db_alias: str) -># Raise the Postgres version so future updates from the plugin-server (which# reads version from Postgres) won't be ignored by ClickHouse.- _set_person_version_floor(team_id, person.pk, new_version, db_alias)+ _set_person_version_floor(team_id, person.pk, new_version)create_person(uuid=person_uuid,@@ -196,37 +165,25 @@ def _reset_person_in_clickhouse(team_id: int, person: Person, db_alias: str) ->)-def _set_person_version_floor(team_id: int, person_id: int, new_version: int, db_alias: str) -> None:+def _set_person_version_floor(team_id: int, person_id: int, new_version: int) -> None:"""Raise a person's version to at least `new_version` (guarded — never lowers).- Routes through SetPersonVersionFloor, falling back to a guarded ORM update.+ Routes through SetPersonVersionFloor."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_call- _personhog_routed(+ personhog_call("set_person_version_floor",lambda: _set_person_version_floor_via_personhog(team_id, person_id, new_version),- lambda: _set_person_version_floor_via_orm(person_id, new_version, db_alias),- team_id=team_id,)def _set_person_version_floor_via_personhog(team_id: int, person_id: int, new_version: int) -> None:- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import require_personhog_clientfrom posthog.personhog_client.proto import SetPersonVersionFloorRequest- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = require_personhog_client()client.set_person_version_floor(SetPersonVersionFloorRequest(team_id=team_id, person_id=person_id, min_version=new_version))---def _set_person_version_floor_via_orm(person_id: int, new_version: int, db_alias: str) -> None:- Person.objects.using(db_alias).filter( # nosemgrep: no-direct-persons-db-orm- pk=person_id, version__lt=new_version- ).update( # nosemgrep: no-direct-persons-db-orm- version=new_version- )diff --git a/posthog/models/person/person.py b/posthog/models/person/person.pyindex acd6e01176e5..ab7e98fb3f66 100644--- a/posthog/models/person/person.py+++ b/posthog/models/person/person.py@@ -1,16 +1,15 @@from datetime import UTC, datetime-from typing import Any, NamedTuple, Optional, cast+from typing import Any, NamedTuple, Optionalfrom uuid import UUIDfrom django.conf import settingsfrom django.core.exceptions import EmptyResultSet-from django.db import connections, models, router, transaction+from django.db import connections, modelsfrom django.db.models import F, Qimport structlogfrom posthog.models.utils import UUIDT-from posthog.person_db_router import PERSONS_DB_FOR_READfrom ..team import Team@@ -32,10 +31,6 @@ class SplitOutcome(NamedTuple):new_person_created_at: datetime-# Use centralized database routing constant-READ_DB_FOR_PERSONS = PERSONS_DB_FOR_READ--class PersonQuerySet(models.QuerySet):"""Custom QuerySet that enforces team_id filtering on all Person queries.@@ -133,15 +128,6 @@ class PersonManager(models.Manager):# """Return PersonQuerySet with team_id enforcement."""# return PersonQuerySet(self.model, using=self._db)- def create(self, *args: Any, **kwargs: Any):- with transaction.atomic(using=self.db):- if not kwargs.get("distinct_ids"):- return super().create(*args, **kwargs)- distinct_ids = kwargs.pop("distinct_ids")- person = cast("Person", super().create(*args, **kwargs))- person._add_distinct_ids(distinct_ids)- return person-def bulk_create(self,objs,@@ -227,69 +213,12 @@ class Person(models.Model):return [id.distinct_id for id in self.distinct_ids_cache]if hasattr(self, "_distinct_ids") and self._distinct_ids is not None:return self._distinct_ids- return [- id[0]- for id in PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(person=self, team_id=self.team_id)- .order_by("id")- .values_list("distinct_id")- ]+ raise ValueError("Person.distinct_ids requires _distinct_ids to be populated via personhog")@propertydef email(self) -> Optional[str]:return self.properties.get("email")- def delete(self, using=None, keep_parents=False):- """- Override delete to ensure team_id is in WHERE clause for partitioned tables.-- For partitioned tables (posthog_person_new), the default delete generates:- DELETE FROM posthog_person WHERE id = X, which scans all 64 partitions.-- This implementation ensures single-partition access:- DELETE FROM posthog_person WHERE team_id = Y AND id = X- """- if self.pk is None:- raise ValueError(- f"{self._meta.object_name} object can't be deleted because its {self._meta.pk.attname} attribute is set "- "to None."- )-- # Save pk and team_id before they get cleared by collector- person_pk = self.pk- person_team_id = self.team_id-- using = using or router.db_for_write(self.__class__, instance=self)-- with transaction.atomic(using=using):- # Delete PersonDistinctId records with explicit team_id for partition pruning.- # Django's Collector.delete() generates: DELETE FROM posthog_persondistinctid WHERE person_id IN (...)- # which misses team_id and would scan all partitions on a partitioned table.- PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=person_team_id, person_id=person_pk- ).delete() # nosemgrep: no-direct-persons-db-orm-- # Now delete the Person itself with explicit team_id for partition pruning- db_connection = connections[using]- with db_connection.cursor() as cursor:- cursor.execute(- f"DELETE FROM {self._meta.db_table} WHERE team_id = %s AND id = %s", [person_team_id, person_pk]- )-- # Return the same format as Django's delete: (num_deleted, {model: count})- return (1, {self._meta.label: 1})-- # :DEPRECATED: This should happen through the plugin server- def add_distinct_id(self, distinct_id: str) -> None:- PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm- person=self, distinct_id=distinct_id, team_id=self.team_id- ) # nosemgrep: no-direct-persons-db-orm-- # :DEPRECATED: This should happen through the plugin server- def _add_distinct_ids(self, distinct_ids: list[str]) -> None:- for distinct_id in distinct_ids:- self.add_distinct_id(distinct_id)-def split_person(self,main_distinct_id: Optional[str],@@ -653,19 +582,6 @@ def get_distinct_ids_for_subquery(person: Person | None, team: Team) -> list[strreturn idsreturn list(set(ids[:first_ids_limit] + ids[-last_ids_limit:]))- first_ids = (- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(person=person, team=team)- .order_by("id")- .values_list("distinct_id", flat=True)[:first_ids_limit]- )- last_ids = (- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(person=person, team=team)- .order_by("-id")- .values_list("distinct_id", flat=True)[:last_ids_limit]- )- distinct_ids = cast(Any, first_ids).union(last_ids)- else:- distinct_ids = []- return list(map(str, distinct_ids))+ raise ValueError("get_distinct_ids_for_subquery requires _distinct_ids to be populated via personhog")++ return []diff --git a/posthog/models/person/test/test_delete_personless_personhog.py b/posthog/models/person/test/test_delete_personless_personhog.pyindex c504300ea5d0..a7ac21d560b5 100644--- a/posthog/models/person/test/test_delete_personless_personhog.py+++ b/posthog/models/person/test/test_delete_personless_personhog.py@@ -1,51 +1,25 @@"""Tests for personless distinct ID deletion via personhog RPC.-Covers routing, fallback, and integration for _delete_personless_distinct_ids_for_teams-(team deletion path), which routes through delete_personless_distinct_ids_batch_for_team-and falls back to the raw batched SQL delete.+Covers routing and RPC behavior for _delete_personless_distinct_ids_for_teams+(team deletion path), which routes through delete_personless_distinct_ids_batch_for_team."""from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockfrom django.test import SimpleTestCase-from django.utils import timezone-from parameterized import parameterized--from posthog.models.person import PersonlessDistinctIdfrom posthog.models.team.util import _delete_personless_distinct_ids_for_teamsfrom posthog.personhog_client.fake_client import fake_personhog_clientfrom posthog.personhog_client.proto import DeletePersonlessDistinctIdsBatchForTeamResponseclass TestDeletePersonlessDistinctIdsForTeamsRouting(SimpleTestCase):- @parameterized.expand(- [- ("personhog_success", True, None),- ("personhog_failure_falls_back_to_orm", True, RuntimeError("grpc timeout")),- ("gate_off_uses_orm_directly", False, None),- ]- )- @patch("posthog.models.team.util._raw_delete_personless_distinct_ids_for_team")- def test_routing(self, _name, gate_on, grpc_exception, mock_raw_delete):- with fake_personhog_client(gate_enabled=gate_on) as fake:- if grpc_exception is not None:- fake.delete_personless_distinct_ids_batch_for_team = MagicMock(side_effect=grpc_exception)-- _delete_personless_distinct_ids_for_teams([1])-- if gate_on and grpc_exception is None:- mock_raw_delete.assert_not_called()- else:- mock_raw_delete.assert_called_once_with(1)-- @patch("posthog.models.team.util._raw_delete_personless_distinct_ids_for_team")- def test_personhog_loops_until_zero_deleted(self, mock_raw_delete):+ def test_personhog_loops_until_zero_deleted(self):# The real RPC returns the number of rows deleted per batch; the caller loops# until it returns 0. The fake hardcodes 0, so override it with a sequence that# forces the while loop to run multiple times before breaking.- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:fake.delete_personless_distinct_ids_batch_for_team = MagicMock(side_effect=[DeletePersonlessDistinctIdsBatchForTeamResponse(deleted_count=10000),@@ -59,30 +33,12 @@ class TestDeletePersonlessDistinctIdsForTeamsRouting(SimpleTestCase):# Looped until a batch returned 0: three calls, last returning 0.assert fake.delete_personless_distinct_ids_batch_for_team.call_count == 3- # Personhog handled it — no ORM fallback.- mock_raw_delete.assert_not_called()---class TestDeletePersonlessDistinctIdsForTeamsIntegration(BaseTest):- def _create_personless(self, team_id: int, distinct_id: str) -> None:- PersonlessDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm- team_id=team_id, distinct_id=distinct_id, is_merged=False, created_at=timezone.now()- )-- def test_orm_fallback_deletes_personless_ids(self):- self._create_personless(self.team.pk, "did-1")- self._create_personless(self.team.pk, "did-2")- assert PersonlessDistinctId.objects.filter(team_id=self.team.pk).count() == 2-- with fake_personhog_client(gate_enabled=False):- _delete_personless_distinct_ids_for_teams([self.team.pk])-- assert PersonlessDistinctId.objects.filter(team_id=self.team.pk).count() == 0+class TestDeletePersonlessDistinctIdsForTeamsRPC(BaseTest):def test_personhog_path_calls_batch_rpc_per_team(self):other_team = self.organization.teams.create(name="Other Team")- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:_delete_personless_distinct_ids_for_teams([self.team.pk, other_team.pk])calls = fake.assert_called("delete_personless_distinct_ids_batch_for_team")@@ -90,23 +46,3 @@ class TestDeletePersonlessDistinctIdsForTeamsIntegration(BaseTest):assert self.team.pk in team_ids_calledassert other_team.pk in team_ids_calledassert all(c.request.batch_size == 10000 for c in calls)-- def test_personhog_fallback_on_error_deletes_via_orm(self):- self._create_personless(self.team.pk, "did-1")-- with fake_personhog_client(gate_enabled=True) as fake:- fake.delete_personless_distinct_ids_batch_for_team = MagicMock(side_effect=RuntimeError("grpc timeout"))- _delete_personless_distinct_ids_for_teams([self.team.pk])-- assert PersonlessDistinctId.objects.filter(team_id=self.team.pk).count() == 0-- def test_cross_team_isolation(self):- other_team = self.organization.teams.create(name="Other Team")- self._create_personless(self.team.pk, "a")- self._create_personless(other_team.pk, "b")-- with fake_personhog_client(gate_enabled=False):- _delete_personless_distinct_ids_for_teams([self.team.pk])-- assert PersonlessDistinctId.objects.filter(team_id=self.team.pk).count() == 0- assert PersonlessDistinctId.objects.filter(team_id=other_team.pk).count() == 1diff --git a/posthog/models/person/test/test_delete_persons_personhog.py b/posthog/models/person/test/test_delete_persons_personhog.pyindex 650f60bdad0a..87aeca6efc35 100644--- a/posthog/models/person/test/test_delete_persons_personhog.py+++ b/posthog/models/person/test/test_delete_persons_personhog.py@@ -1,85 +1,33 @@"""Tests for person deletion via personhog RPC.-Covers routing, fallback, and integration for:+Covers routing and RPC behavior for:- delete_persons_from_postgres (API delete path)- _delete_persons_for_teams (team deletion path)"""from posthog.test.base import BaseTest-from unittest.mock import ANY, MagicMock, patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase-from parameterized import parameterized--from posthog.models.person import Person, PersonDistinctId-from posthog.models.person.util import delete_persons_from_postgres+from posthog.models.person.util import delete_persons_from_postgres, get_person_by_distinct_id, get_person_by_uuidfrom posthog.models.team.util import _delete_persons_for_teamsfrom posthog.personhog_client.fake_client import fake_personhog_clientfrom posthog.test.persons import create_person-# ── Routing tests for delete_persons_from_postgres ─────��────────────+# ── Routing tests for delete_persons_from_postgres ──────────────────class TestDeletePersonsFromPostgresRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- "django_orm",- ),- ]- )- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- ):- mock_use_personhog.return_value = gate_on-+ def test_routes_to_personhog(self):mock_person = MagicMock()mock_person.uuid = "550e8400-e29b-41d4-a716-446655440000"mock_person.delete = MagicMock()- with fake_personhog_client(gate_enabled=gate_on) as fake:- if grpc_exception is not None:- fake.delete_persons = MagicMock(side_effect=grpc_exception)-+ with fake_personhog_client():delete_persons_from_postgres(team_id=1, persons=[mock_person])- if gate_on and grpc_exception is None:- mock_person.delete.assert_not_called()- else:- mock_person.delete.assert_called_once()-- mock_routing_counter.labels.assert_called_with(- operation="delete_persons", source=expected_source, client_name=ANY- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()+ mock_person.delete.assert_not_called()def test_personhog_sends_correct_uuids(self):mock_persons = []@@ -120,121 +68,37 @@ class TestDeletePersonsFromPostgresRouting(SimpleTestCase):class TestDeletePersonsForTeamsRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- None,- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- ),- (- "gate_off_uses_orm_directly",- False,- None,- ),- ]- )@patch("posthog.models.team.util._raw_delete_batch")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- mock_raw_delete_batch,- ):- with fake_personhog_client(gate_enabled=gate_on) as fake:- if grpc_exception is not None:- fake.delete_persons_batch_for_team = MagicMock(side_effect=grpc_exception)-+ def test_routes_to_personhog(self, mock_raw_delete_batch):+ with fake_personhog_client():_delete_persons_for_teams([1])- if gate_on and grpc_exception is None:- mock_raw_delete_batch.assert_not_called()- else:- assert mock_raw_delete_batch.call_count == 2---# ── Integration tests (real DB) ─────────────────────────────────────---class TestDeletePersonsFromPostgresIntegration(BaseTest):- def test_orm_path_deletes_person_and_distinct_ids(self):- person = create_person(- team=self.team,- distinct_ids=["did-1", "did-2"],- properties={"email": "[email protected]"},- )-- with fake_personhog_client(gate_enabled=False):- delete_persons_from_postgres(self.team.pk, [person])-- 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_personhog_path_calls_rpc_with_correct_args(self):- person = create_person(- team=self.team,- distinct_ids=["did-1", "did-2"],- properties={"email": "[email protected]"},- )-- with fake_personhog_client(gate_enabled=True) as fake:- delete_persons_from_postgres(self.team.pk, [person])-- calls = fake.assert_called("delete_persons", times=1)- req = calls[0].request- assert req.team_id == self.team.pk- assert list(req.person_uuids) == [str(person.uuid)]+ mock_raw_delete_batch.assert_not_called()- def test_personhog_path_fallback_deletes_from_db(self):- person = create_person(- team=self.team,- distinct_ids=["did-1"],- )- with fake_personhog_client(gate_enabled=True) as fake:- fake.delete_persons = MagicMock(side_effect=RuntimeError("grpc timeout"))- delete_persons_from_postgres(self.team.pk, [person])+# ── RPC behavior tests (personhog fake with real test data) ─────────- 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+class TestDeletePersonsFromPostgresRPC(BaseTest):def test_multiple_persons_deleted(self):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])+ delete_persons_from_postgres(self.team.pk, [p1, p2])- assert Person.objects.filter(team_id=self.team.pk).count() == 0- assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 0+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is None+ assert get_person_by_uuid(self.team.pk, str(p2.uuid)) is None+ assert get_person_by_distinct_id(self.team.pk, "a") is None+ assert get_person_by_distinct_id(self.team.pk, "b") is None-class TestDeletePersonsForTeamsIntegration(BaseTest):- def test_orm_fallback_deletes_persons_and_distinct_ids(self):- 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() == 2- assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 3-- with fake_personhog_client(gate_enabled=False):- _delete_persons_for_teams([self.team.pk])-- assert Person.objects.filter(team_id=self.team.pk).count() == 0- assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 0-+class TestDeletePersonsForTeamsRPC(BaseTest):def test_personhog_path_calls_batch_rpc_per_team(self):other_team = self.organization.teams.create(name="Other Team")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:+ with fake_personhog_client() as fake:fake.add_person(team_id=self.team.pk, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a"])fake.add_person(team_id=other_team.pk, person_id=p2.pk, uuid=str(p2.uuid), distinct_ids=["b"])@@ -249,7 +113,7 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):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:+ with fake_personhog_client() as fake:fake.add_person(team_id=self.team.pk, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a"])fake.add_person(team_id=self.team.pk, person_id=p2.pk, uuid=str(p2.uuid), distinct_ids=["b"])@@ -260,24 +124,3 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):assert len(calls) >= 2# Last call should have returned deleted_count=0assert calls[-1].response.deleted_count == 0-- def test_personhog_fallback_on_error_deletes_via_orm(self):- 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"))- _delete_persons_for_teams([self.team.pk])-- assert Person.objects.filter(team_id=self.team.pk).count() == 0- assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 0-- def test_cross_team_isolation(self):- other_team = self.organization.teams.create(name="Other Team")- 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])-- assert Person.objects.filter(team_id=self.team.pk).count() == 0- assert Person.objects.filter(team_id=other_team.pk).count() == 1diff --git a/posthog/models/person/test/test_point_in_time_properties.py b/posthog/models/person/test/test_point_in_time_properties.pyindex b21b3e666300..a685f71a60d1 100644--- a/posthog/models/person/test/test_point_in_time_properties.py+++ b/posthog/models/person/test/test_point_in_time_properties.py@@ -15,8 +15,7 @@ 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.test.personhog_fake import get_active_fake+from posthog.personhog_client.fake_client import fake_personhog_client, get_active_fakefrom posthog.test.persons import create_persondiff --git a/posthog/models/person/test/test_reset_distinct_ids_personhog.py b/posthog/models/person/test/test_reset_distinct_ids_personhog.pyindex e004d26ae267..2dc588f0d507 100644--- a/posthog/models/person/test/test_reset_distinct_ids_personhog.py+++ b/posthog/models/person/test/test_reset_distinct_ids_personhog.py@@ -1,48 +1,22 @@"""Tests for the undelete-repair version writes via personhog RPC.-Covers routing/fallback for the two persons-DB writes in the repair flow:+Covers the two personhog RPC writes in the repair flow:- _update_distinct_id_in_postgres → SetPersonDistinctIdVersionFloor- _set_person_version_floor (used by _reset_person_in_clickhouse) → SetPersonVersionFloor"""from uuid import uuid4-from unittest.mock import MagicMock, patch-from django.test import SimpleTestCase-from parameterized import parameterized-from posthog.models.person.deletion import _set_person_version_floor, _update_distinct_id_in_postgresfrom posthog.personhog_client.fake_client import fake_personhog_client-class TestUpdateDistinctIdInPostgresRouting(SimpleTestCase):- @parameterized.expand(- [- ("personhog_success", True, None),- ("personhog_error_falls_back_to_orm", True, RuntimeError("grpc timeout")),- ("gate_off_uses_orm_directly", False, None),- ]- )- @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")- def test_routing(self, _name, gate_on, grpc_exception, mock_orm):- mock_orm.return_value = None- with fake_personhog_client(gate_enabled=gate_on) as fake:- if grpc_exception is not None:- fake.set_person_distinct_id_version_floor = MagicMock(side_effect=grpc_exception)-- _update_distinct_id_in_postgres("did-1", 100, team_id=1)-- if gate_on and grpc_exception is None:- mock_orm.assert_not_called()- else:- mock_orm.assert_called_once_with(1, "did-1", 100)-- @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")- def test_personhog_path_returns_converted_person(self, mock_orm):+class TestUpdateDistinctIdInPostgresRPC(SimpleTestCase):+ def test_personhog_path_returns_converted_person(self):person_uuid = str(uuid4())- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:fake.add_person(team_id=1,person_id=42,@@ -61,47 +35,21 @@ class TestUpdateDistinctIdInPostgresRouting(SimpleTestCase):assert result is not Noneassert str(result.uuid) == person_uuidassert result.properties == {"email": "[email protected]"}- mock_orm.assert_not_called()- @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")- def test_personhog_returns_none_when_distinct_id_absent(self, mock_orm):- with fake_personhog_client(gate_enabled=True):+ def test_personhog_returns_none_when_distinct_id_absent(self):+ with fake_personhog_client():# Fake not seeded → no person for this distinct_id.result = _update_distinct_id_in_postgres("never-used", 100, team_id=1)assert result is None- mock_orm.assert_not_called()-class TestSetPersonVersionFloorRouting(SimpleTestCase):- @parameterized.expand(- [- ("personhog_success", True, None),- ("personhog_error_falls_back_to_orm", True, RuntimeError("grpc timeout")),- ("gate_off_uses_orm_directly", False, None),- ]- )- @patch("posthog.models.person.deletion._set_person_version_floor_via_orm")- def test_routing(self, _name, gate_on, grpc_exception, mock_orm):- with fake_personhog_client(gate_enabled=gate_on) as fake:- if grpc_exception is not None:- fake.set_person_version_floor = MagicMock(side_effect=grpc_exception)-- _set_person_version_floor(1, 42, 500, "default")-- if gate_on and grpc_exception is None:- mock_orm.assert_not_called()- else:- mock_orm.assert_called_once_with(42, 500, "default")-- @patch("posthog.models.person.deletion._set_person_version_floor_via_orm")- def test_personhog_path_calls_rpc_with_floor(self, mock_orm):- with fake_personhog_client(gate_enabled=True) as fake:- _set_person_version_floor(1, 42, 500, "default")+class TestSetPersonVersionFloorRPC(SimpleTestCase):+ def test_personhog_path_calls_rpc_with_floor(self):+ with fake_personhog_client() as fake:+ _set_person_version_floor(1, 42, 500)calls = fake.assert_called("set_person_version_floor")assert calls[0].request.team_id == 1assert calls[0].request.person_id == 42assert calls[0].request.min_version == 500-- mock_orm.assert_not_called()diff --git a/posthog/models/person/test/test_split_person.py b/posthog/models/person/test/test_split_person.pyindex 75c78d90d4f4..8b1d24e0fb9b 100644--- a/posthog/models/person/test/test_split_person.py+++ b/posthog/models/person/test/test_split_person.py@@ -4,8 +4,8 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom posthog.models import Person-from posthog.models.person import PersonDistinctIdfrom posthog.models.person.missing_person import uuidFromDistinctId+from posthog.models.person.util import get_person_by_distinct_id, get_person_by_idfrom posthog.personhog_client.fake_client import FakePersonHogClient, fake_personhog_clientfrom posthog.test.persons import add_distinct_id, create_person@@ -74,7 +74,6 @@ class TestSplitPerson(BaseTest):assert moved_2.id != moved_3.id# Original person keeps its properties when main_distinct_id is provided- person.refresh_from_db()assert person.properties == {"email": "[email protected]", "name": "Test"}assert mock_create_pdi.call_count == 2@@ -86,11 +85,12 @@ class TestSplitPerson(BaseTest):person.split_person(main_distinct_id="id1")- # The write went through the RPC — local DB rows are untouched- for did in ["id1", "id2", "id3"]:- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=did)- assert pdi.person_id == person.id- assert Person.objects.filter(team_id=self.team.id).count() == 1+ # The write went through the RPC — reads resolve via personhog, not the ORM.+ # "id1" stays on the original person; "id2"/"id3" each moved to a new person.+ assert get_person_by_distinct_id(self.team.id, "id1").pk == person.id # type: ignore[union-attr]+ assert get_person_by_distinct_id(self.team.id, "id2").pk != person.id # type: ignore[union-attr]+ assert get_person_by_distinct_id(self.team.id, "id3").pk != person.id # type: ignore[union-attr]+ assert get_person_by_id(self.team.id, person.id) is not Nonedef test_split_without_main_distinct_id_keeps_properties(self, mock_create_pdi, mock_create_person):with fake_personhog_client() as fake:@@ -110,7 +110,6 @@ class TestSplitPerson(BaseTest):assert len(split_ids) == 1assert split_ids == {"id2"}- person.refresh_from_db()assert person.properties == {"email": "[email protected]"}def test_split_with_max_splits(self, mock_create_pdi, mock_create_person):@@ -219,7 +218,6 @@ class TestSplitPerson(BaseTest):assert fake._persons_by_distinct_id[(self.team.id, "move2")].id != person.id# Original person keeps its properties intact — this is the key partial-split guarantee.- person.refresh_from_db()assert person.properties == {"email": "[email protected]", "name": "Mega"}assert mock_create_pdi.call_count == 2@@ -300,9 +298,8 @@ class TestSplitPerson(BaseTest):with self.assertRaises(RuntimeError):person.split_person(main_distinct_id="id1")- # Local DB rows are untouched and no Kafka messages were published- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")- assert pdi.person_id == person.id+ # The split never happened — "id2" still resolves to the original person — and no Kafka was published+ assert get_person_by_distinct_id(self.team.id, "id2").pk == person.id # type: ignore[union-attr]mock_create_pdi.assert_not_called()mock_create_person.assert_not_called()@@ -324,7 +321,6 @@ class TestSplitPerson(BaseTest):split_calls = fake.assert_called("split_person", times=1)assert list(split_calls[0].request.distinct_ids_to_split) == ["id2"]- person.refresh_from_db()assert person.properties == {"email": "[email protected]"}def test_split_person_not_found_in_personhog(self, mock_create_pdi, mock_create_person):diff --git a/posthog/models/person/test/test_util_personhog.py b/posthog/models/person/test/test_util_personhog.pynew file mode 100644index 000000000000..fa8e0e328cff--- /dev/null+++ b/posthog/models/person/test/test_util_personhog.py@@ -0,0 +1,547 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from posthog.models.person.util import (+ _fetch_person_by_distinct_id_via_personhog,+ _fetch_person_by_id_via_personhog,+ _fetch_person_by_uuid_via_personhog,+ _fetch_persons_by_distinct_ids_via_personhog,+ _fetch_persons_by_uuids_via_personhog,+ _validate_uuids_via_personhog,+ get_person_by_pk_or_uuid,+ get_person_uuids_by_distinct_ids,+ get_persons_mapped_by_distinct_id,+)+from posthog.personhog_client.client import personhog_call+from posthog.personhog_client.fake_client import fake_personhog_client, get_active_fake+from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.persons import create_person++# ── Personhog internal logic tests ──────────────────────────────────+# These use the fake personhog client to exercise the real proto/converter pipeline.+++class TestFetchPersonByUuidViaPersonhog(SimpleTestCase):+ def test_returns_person_with_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ properties={"email": "[email protected]"},+ is_identified=True,+ created_at=1700000000000,+ distinct_ids=["did-1", "did-2"],+ )++ result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="550e8400-e29b-41d4-a716-446655440000")++ assert result is not None+ assert result.id == 42+ assert result.properties == {"email": "[email protected]"}+ assert result.distinct_ids == ["did-1", "did-2"]+ fake.assert_called("get_person_by_uuid")+ fake.assert_called("get_distinct_ids_for_person")++ def test_returns_none_when_person_not_found(self):+ with fake_personhog_client() as fake:+ result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="nonexistent")++ assert result is None+ fake.assert_called("get_person_by_uuid")+ fake.assert_not_called("get_distinct_ids_for_person")++ def test_returns_none_on_team_mismatch(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=999,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ distinct_ids=["did-1"],+ )++ result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="550e8400-e29b-41d4-a716-446655440000")++ assert result is None+ fake.assert_not_called("get_distinct_ids_for_person")+++class TestFetchPersonByDistinctIdViaPersonhog(SimpleTestCase):+ def test_returns_person_with_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ properties={"email": "[email protected]"},+ is_identified=True,+ created_at=1700000000000,+ distinct_ids=["did-1", "did-2"],+ )++ result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="did-1")++ assert result is not None+ assert result.id == 42+ assert result.distinct_ids == ["did-1", "did-2"]+ fake.assert_called("get_person_by_distinct_id")++ def test_returns_none_when_person_not_found(self):+ with fake_personhog_client() as fake:+ result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="nonexistent")++ assert result is None+ fake.assert_not_called("get_distinct_ids_for_person")++ def test_returns_none_on_team_mismatch(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=999,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ distinct_ids=["did-1"],+ )++ result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="did-1")++ assert result is None+ fake.assert_not_called("get_distinct_ids_for_person")+++class TestFetchPersonByIdViaPersonhog(SimpleTestCase):+ def test_returns_person_with_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ properties={"email": "[email protected]"},+ is_identified=True,+ created_at=1700000000000,+ distinct_ids=["did-1", "did-2"],+ )++ result = _fetch_person_by_id_via_personhog(team_id=1, person_id=42)++ assert result is not None+ assert result.id == 42+ assert result.properties == {"email": "[email protected]"}+ assert result.distinct_ids == ["did-1", "did-2"]+ fake.assert_called("get_person")+ fake.assert_called("get_distinct_ids_for_person")++ def test_returns_none_when_person_not_found(self):+ with fake_personhog_client() as fake:+ result = _fetch_person_by_id_via_personhog(team_id=1, person_id=999)++ assert result is None+ fake.assert_called("get_person")+ fake.assert_not_called("get_distinct_ids_for_person")++ def test_returns_none_on_team_mismatch(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=999,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ distinct_ids=["did-1"],+ )++ result = _fetch_person_by_id_via_personhog(team_id=1, person_id=42)++ assert result is None+ fake.assert_not_called("get_distinct_ids_for_person")+++class TestFetchPersonsByDistinctIdsViaPersonhog(SimpleTestCase):+ def test_returns_persons_with_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440000",+ properties={"email": "[email protected]"},+ is_identified=True,+ created_at=1700000000000,+ distinct_ids=["did-1", "did-2"],+ )++ result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1"])++ assert len(result) == 1+ assert result[0].id == 42+ assert result[0].properties == {"email": "[email protected]"}+ assert result[0].distinct_ids == ["did-1", "did-2"]+ fake.assert_called("get_persons_by_distinct_ids_in_team")+ fake.assert_called("get_distinct_ids_for_persons")++ def test_no_results_for_missing_distinct_ids(self):+ with fake_personhog_client() as fake:+ result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["nonexistent"])++ assert result == []+ fake.assert_called("get_persons_by_distinct_ids_in_team")+ fake.assert_not_called("get_distinct_ids_for_persons")++ def test_cross_team_isolation(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=999, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1"]+ )++ result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1"])++ assert result == []++ def test_deduplicates_persons_with_multiple_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1", "did-2"]+ )++ result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1", "did-2"])++ assert len(result) == 1++ def test_respects_distinct_id_limit(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=42,+ uuid="550e8400-e29b-41d4-a716-446655440042",+ distinct_ids=["did-1", "did-2", "did-3"],+ )++ result = _fetch_persons_by_distinct_ids_via_personhog(+ team_id=1, distinct_ids=["did-1"], distinct_id_limit=1+ )++ assert len(result) == 1+ assert len(result[0].distinct_ids) == 1+++class TestFetchPersonsByUuidsViaPersonhog(SimpleTestCase):+ def test_returns_persons_with_distinct_ids(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1,+ person_id=1,+ uuid="550e8400-e29b-41d4-a716-446655440001",+ properties={"name": "Alice"},+ distinct_ids=["alice-did"],+ )+ fake.add_person(+ team_id=1,+ person_id=2,+ uuid="550e8400-e29b-41d4-a716-446655440002",+ properties={"name": "Bob"},+ distinct_ids=["bob-did"],+ )++ result = _fetch_persons_by_uuids_via_personhog(+ team_id=1,+ uuids=["550e8400-e29b-41d4-a716-446655440001", "550e8400-e29b-41d4-a716-446655440002"],+ )++ assert len(result) == 2+ assert result[0].properties == {"name": "Alice"}+ assert result[0].distinct_ids == ["alice-did"]+ assert result[1].properties == {"name": "Bob"}+ assert result[1].distinct_ids == ["bob-did"]+ fake.assert_called("get_persons_by_uuids")+ fake.assert_called("get_distinct_ids_for_persons")++ def test_returns_empty_for_missing_uuids(self):+ with fake_personhog_client() as fake:+ result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["nonexistent"])++ assert result == []+ fake.assert_called("get_persons_by_uuids")+ fake.assert_not_called("get_distinct_ids_for_persons")++ def test_cross_team_isolation(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=999, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1"]+ )++ result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"])++ assert result == []++ def test_person_with_no_distinct_ids_gets_empty_list(self):+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042")++ result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"])++ assert len(result) == 1+ assert result[0].distinct_ids == []++ def test_distinct_id_limit_zero_skips_fetch(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]+ )++ result = _fetch_persons_by_uuids_via_personhog(+ team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=0+ )++ assert len(result) == 1+ assert result[0].distinct_ids == []+ fake.assert_called("get_persons_by_uuids")+ fake.assert_not_called("get_distinct_ids_for_persons")++ def test_distinct_id_limit_bounds_fetch(self):+ with fake_personhog_client() as fake:+ fake.add_person(+ team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]+ )++ result = _fetch_persons_by_uuids_via_personhog(+ team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=2+ )++ assert result[0].distinct_ids == ["d1", "d2"]+++class TestValidateUuidsViaPersonhog(SimpleTestCase):+ def test_returns_matching_uuids(self):+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])+ fake.add_person(team_id=1, person_id=2, uuid="uuid-2", distinct_ids=["d2"])++ result = _validate_uuids_via_personhog(team_id=1, uuids=["uuid-1", "uuid-2", "uuid-missing"])++ assert set(result) == {"uuid-1", "uuid-2"}+ fake.assert_called("get_persons_by_uuids")++ def test_filters_out_wrong_team(self):+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])+ fake.add_person(team_id=999, person_id=2, uuid="uuid-2", distinct_ids=["d2"])++ result = _validate_uuids_via_personhog(team_id=1, uuids=["uuid-1", "uuid-2"])++ assert result == ["uuid-1"]++ def test_returns_empty_when_no_matches(self):+ with fake_personhog_client() as fake:+ result = _validate_uuids_via_personhog(team_id=1, uuids=["nonexistent"])++ assert result == []+ fake.assert_called("get_persons_by_uuids")+++# ── Delegation tests ────────────────────────────────────────────────+++class TestGetPersonByPkOrUuid(SimpleTestCase):+ @patch("posthog.models.person.util.get_person_by_uuid")+ def test_routes_uuid_key_to_get_person_by_uuid(self, mock_get_by_uuid):+ mock_person = MagicMock()+ mock_get_by_uuid.return_value = mock_person++ result = get_person_by_pk_or_uuid(1, "550e8400-e29b-41d4-a716-446655440000")++ assert result == mock_person+ mock_get_by_uuid.assert_called_once_with(1, "550e8400-e29b-41d4-a716-446655440000", distinct_id_limit=None)++ @patch("posthog.models.person.util.get_person_by_id")+ def test_routes_int_key_to_get_person_by_id(self, mock_get_by_id):+ mock_person = MagicMock()+ mock_get_by_id.return_value = mock_person++ result = get_person_by_pk_or_uuid(1, "42")++ assert result == mock_person+ mock_get_by_id.assert_called_once_with(1, 42, distinct_id_limit=None)++ def test_returns_none_for_invalid_key(self):+ result = get_person_by_pk_or_uuid(1, "not-a-uuid-or-int")++ assert result is None++ @patch("posthog.models.person.util.get_person_by_uuid")+ def test_returns_none_when_uuid_lookup_finds_nothing(self, mock_get_by_uuid):+ mock_get_by_uuid.return_value = None++ result = get_person_by_pk_or_uuid(1, "550e8400-e29b-41d4-a716-446655440000")++ assert result is None++ @patch("posthog.models.person.util.get_person_by_id")+ def test_returns_none_when_id_lookup_finds_nothing(self, mock_get_by_id):+ mock_get_by_id.return_value = None++ result = get_person_by_pk_or_uuid(1, "42")++ assert result is None+++# ── personhog_call unit tests ────────────────────────────────────+++class TestPersonhogCall(SimpleTestCase):+ @patch("posthog.personhog_client.metrics.PERSONHOG_ROUTING_TOTAL")+ def test_calls_fn_and_increments_counter(self, mock_routing):+ result = personhog_call("test_op", lambda: "personhog_result")++ assert result == "personhog_result"+ mock_routing.labels.assert_called_with(operation="test_op", source="personhog", client_name="posthog-django")+ mock_routing.labels.return_value.inc.assert_called_once()++ @patch("posthog.personhog_client.metrics.PERSONHOG_ROUTING_TOTAL")+ def test_exception_propagates(self, mock_routing):+ def failing_fn():+ raise RuntimeError("grpc timeout")++ with self.assertRaises(RuntimeError):+ personhog_call("test_op", failing_fn)++ @patch("posthog.personhog_client.metrics.PERSONHOG_ROUTING_TOTAL")+ def test_returning_none_is_not_treated_as_failure(self, mock_routing):+ result = personhog_call("test_op", lambda: None)++ assert result is None+ mock_routing.labels.assert_called_with(operation="test_op", source="personhog", client_name="posthog-django")++ @patch("posthog.personhog_client.metrics.PERSONHOG_ROUTING_TOTAL")+ @patch("posthog.personhog_client.metrics.PERSONHOG_ROUTING_ERRORS_TOTAL")+ def test_reraise_as_wraps_exception(self, mock_errors, mock_routing):+ def failing_fn():+ raise RuntimeError("boom")++ with self.assertRaises(ValueError):+ personhog_call("test_op", failing_fn, reraise_as=ValueError)++ mock_errors.labels.return_value.inc.assert_called_once()+ mock_routing.labels.return_value.inc.assert_not_called()+++# ── get_persons_mapped_by_distinct_id tests ────────────+++class TestGetPersonsMappedByDistinctId(PersonhogTestMixin, BaseTest):+ def test_single_person_single_distinct_id(self):+ person = self._seed_person(team=self.team, distinct_ids=["did-1"], properties={"email": "[email protected]"})++ result = get_persons_mapped_by_distinct_id(self.team.pk, ["did-1"])++ assert "did-1" in result+ assert str(result["did-1"].uuid) == str(person.uuid)+ assert result["did-1"].properties == {"email": "[email protected]"}+ assert result["did-1"].distinct_ids == ["did-1"]+ self._assert_personhog_called("get_persons_by_distinct_ids_in_team")++ def test_single_person_multiple_distinct_ids(self):+ person = self._seed_person(team=self.team, distinct_ids=["did-1", "did-2"])++ result = get_persons_mapped_by_distinct_id(self.team.pk, ["did-1", "did-2"])++ # Both distinct_ids should map to the same person+ assert len(result) == 2+ assert str(result["did-1"].uuid) == str(person.uuid)+ assert str(result["did-2"].uuid) == str(person.uuid)+ # Each entry should carry only the distinct_id that was used as the key+ assert result["did-1"].distinct_ids == ["did-1"]+ assert result["did-2"].distinct_ids == ["did-2"]++ def test_multiple_persons(self):+ p1 = self._seed_person(team=self.team, distinct_ids=["alice"], properties={"name": "Alice"})+ p2 = self._seed_person(team=self.team, distinct_ids=["bob"], properties={"name": "Bob"})++ result = get_persons_mapped_by_distinct_id(self.team.pk, ["alice", "bob"])++ assert str(result["alice"].uuid) == str(p1.uuid)+ assert str(result["bob"].uuid) == str(p2.uuid)++ def test_missing_distinct_ids_returns_empty(self):+ result = get_persons_mapped_by_distinct_id(self.team.pk, ["nonexistent"])++ assert result == {}++ 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"])++ result = get_persons_mapped_by_distinct_id(self.team.pk, ["shared_did"])++ assert result == {}+++# ── Public get_person_uuids_by_distinct_ids tests ─────────────────────+++class TestGetPersonUuidsByDistinctIds(BaseTest):+ def _get_uuids(self, distinct_ids: list[str]) -> list[str]:+ return get_person_uuids_by_distinct_ids(self.team.pk, distinct_ids)++ def test_returns_uuids_for_matching_distinct_ids(self):+ 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)}+ 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 == []+ 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"])++ assert result == []++ def test_cross_team_isolation(self):+ other_team = self.organization.teams.create(name="Other Team")+ 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 = 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 = 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 = [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 TestGetPersonUuidsByDistinctIdsFieldMask(BaseTest):+ """Verify the personhog path sends a UUID-only field mask."""++ def test_sends_uuid_only_field_mask(self):+ create_person(team=self.team, distinct_ids=["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+ assert "id" in mask+ assert "team_id" in mask+ assert "properties" not in maskdiff --git a/posthog/models/person/test/test_util_personhog_routing.py b/posthog/models/person/test/test_util_personhog_routing.pydeleted file mode 100644index 5806c8ef6cea..000000000000--- a/posthog/models/person/test/test_util_personhog_routing.py+++ /dev/null@@ -1,1055 +0,0 @@-from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch--from django.test import SimpleTestCase--from parameterized import parameterized, parameterized_class--from posthog.models.person.util import (- _fetch_person_by_distinct_id_via_personhog,- _fetch_person_by_id_via_personhog,- _fetch_person_by_uuid_via_personhog,- _fetch_persons_by_distinct_ids_via_personhog,- _fetch_persons_by_uuids_via_personhog,- _personhog_routed,- _validate_uuids_via_personhog,- get_person_by_distinct_id,- get_person_by_id,- get_person_by_pk_or_uuid,- get_person_by_uuid,- get_persons_by_distinct_ids,- get_persons_by_uuids,- get_persons_mapped_by_distinct_id,- validate_person_uuids_exist,-)-from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.personhog_client.test_helpers import PersonhogTestMixin--# ── Routing tests ────────────────────────────────────────────────────-# These use mocks to test gate/fallback/metrics logic in _personhog_routed.---class TestGetPersonByUuidRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- "mock_person",- None,- "personhog",- ),- (- "personhog_returns_none",- True,- None,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- None,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.Person.objects")- @patch("posthog.models.person.util._fetch_person_by_uuid_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- personhog_data,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- mock_objects,- ):- mock_use_personhog.return_value = gate_on-- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_data-- mock_qs = MagicMock()- mock_qs.first.return_value = MagicMock()- mock_objects.db_manager.return_value.filter.return_value = mock_qs-- result = get_person_by_uuid(1, "some-uuid")-- if gate_on and grpc_exception is None:- assert result == personhog_data- mock_objects.db_manager.assert_not_called()- else:- mock_objects.db_manager.assert_called()-- mock_routing_counter.labels.assert_called_with(- operation="get_person_by_uuid", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestGetPersonByDistinctIdRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- "mock_person",- None,- "personhog",- ),- (- "personhog_returns_none",- True,- None,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- None,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.Person.objects")- @patch("posthog.models.person.util._fetch_person_by_distinct_id_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- personhog_data,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- mock_objects,- ):- mock_use_personhog.return_value = gate_on-- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_data-- mock_qs = MagicMock()- mock_qs.first.return_value = MagicMock()- mock_objects.db_manager.return_value.filter.return_value = mock_qs-- result = get_person_by_distinct_id(1, "some-distinct-id")-- if gate_on and grpc_exception is None:- assert result == personhog_data- mock_objects.db_manager.assert_not_called()- else:- mock_objects.db_manager.assert_called()-- mock_routing_counter.labels.assert_called_with(- operation="get_person_by_distinct_id", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestGetPersonByIdRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- "mock_person",- None,- "personhog",- ),- (- "personhog_returns_none",- True,- None,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- None,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.Person.objects")- @patch("posthog.models.person.util._fetch_person_by_id_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- personhog_data,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- mock_objects,- ):- mock_use_personhog.return_value = gate_on-- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_data-- mock_qs = MagicMock()- mock_qs.first.return_value = MagicMock()- mock_objects.db_manager.return_value.filter.return_value = mock_qs-- result = get_person_by_id(1, 42)-- if gate_on and grpc_exception is None:- assert result == personhog_data- mock_objects.db_manager.assert_not_called()- else:- mock_objects.db_manager.assert_called()-- mock_routing_counter.labels.assert_called_with(- operation="get_person_by_id", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestGetPersonsByUuidsRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- ["person_a", "person_b"],- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- None,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.Person.objects")- @patch("posthog.models.person.util._fetch_persons_by_uuids_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- personhog_data,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- mock_objects,- ):- mock_use_personhog.return_value = gate_on-- if personhog_data is not None:- mock_fetch_personhog.return_value = personhog_data- elif grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception-- mock_qs = MagicMock()- mock_objects.db_manager.return_value.filter.return_value = mock_qs-- team_id = 1- uuids = ["uuid-1", "uuid-2"]-- result = get_persons_by_uuids(team_id, uuids)-- if personhog_data is not None and gate_on:- assert result == personhog_data- mock_fetch_personhog.assert_called_once_with(team_id, uuids, distinct_id_limit=None)- mock_objects.db_manager.assert_not_called()- else:- assert result == mock_qs- mock_objects.db_manager.return_value.filter.assert_called_with(team_id=team_id, uuid__in=uuids)-- mock_routing_counter.labels.assert_called_with(- operation="get_persons_by_uuids", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestGetPersonsByDistinctIdsRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util._fetch_persons_by_distinct_ids_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- ):- mock_use_personhog.return_value = gate_on-- personhog_persons = [MagicMock(), MagicMock()]- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_persons-- team_id = 1- distinct_ids = ["did-1", "did-2"]-- if gate_on and grpc_exception is None:- result = get_persons_by_distinct_ids(team_id, distinct_ids)- assert result == personhog_persons- else:- with (- patch("posthog.models.person.util.Person.objects") as mock_person_objects,- patch("posthog.models.person.util.PersonDistinctId.objects"),- patch("posthog.models.person.util.Prefetch"),- ):- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_person_objects.db_manager.return_value.filter.return_value.prefetch_related.return_value = mock_qs-- result = get_persons_by_distinct_ids(team_id, distinct_ids)- assert result == []-- mock_routing_counter.labels.assert_called_with(- operation="get_persons_by_distinct_ids", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestGetPersonsMappedByDistinctIdRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.PersonDistinctId.objects")- @patch("posthog.personhog_client.client.get_personhog_client")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_get_client,- mock_pdi_objects,- ):- mock_use_personhog.return_value = gate_on-- mock_client = MagicMock()- if grpc_exception is not None:- mock_client.get_persons_by_distinct_ids_in_team.side_effect = grpc_exception- mock_get_client.return_value = mock_client-- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_pdi_objects.db_manager.return_value.filter.return_value.select_related.return_value = mock_qs-- get_persons_mapped_by_distinct_id(1, ["did-1"])-- if gate_on and grpc_exception is None:- mock_pdi_objects.db_manager.assert_not_called()- else:- mock_pdi_objects.db_manager.assert_called()-- mock_routing_counter.labels.assert_called_with(- operation="get_persons_mapped_by_distinct_id", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestValidatePersonUuidsExistRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- ["uuid-1", "uuid-2"],- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- None,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- None,- "django_orm",- ),- ]- )- @patch("posthog.models.person.util.Person.objects")- @patch("posthog.models.person.util._validate_uuids_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_routing(- self,- _name,- gate_on,- personhog_data,- grpc_exception,- expected_source,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- mock_objects,- ):- mock_use_personhog.return_value = gate_on-- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_data-- mock_qs = MagicMock()- mock_qs.__iter__ = MagicMock(return_value=iter([]))- mock_objects.db_manager.return_value.filter.return_value.values_list.return_value = mock_qs-- result = validate_person_uuids_exist(1, ["uuid-1", "uuid-2"])-- if gate_on and grpc_exception is None:- assert result == personhog_data- mock_objects.db_manager.assert_not_called()- else:- mock_objects.db_manager.assert_called()-- mock_routing_counter.labels.assert_called_with(- operation="validate_person_uuids_exist", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---# ── Personhog internal logic tests ──────────────────────────────────-# These use the fake personhog client to exercise the real proto/converter pipeline.---class TestFetchPersonByUuidViaPersonhog(SimpleTestCase):- def test_returns_person_with_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- properties={"email": "[email protected]"},- is_identified=True,- created_at=1700000000000,- distinct_ids=["did-1", "did-2"],- )-- result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="550e8400-e29b-41d4-a716-446655440000")-- assert result is not None- assert result.id == 42- assert result.properties == {"email": "[email protected]"}- assert result.distinct_ids == ["did-1", "did-2"]- fake.assert_called("get_person_by_uuid")- fake.assert_called("get_distinct_ids_for_person")-- def test_returns_none_when_person_not_found(self):- with fake_personhog_client() as fake:- result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="nonexistent")-- assert result is None- fake.assert_called("get_person_by_uuid")- fake.assert_not_called("get_distinct_ids_for_person")-- def test_returns_none_on_team_mismatch(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- distinct_ids=["did-1"],- )-- result = _fetch_person_by_uuid_via_personhog(team_id=1, uuid="550e8400-e29b-41d4-a716-446655440000")-- assert result is None- fake.assert_not_called("get_distinct_ids_for_person")---class TestFetchPersonByDistinctIdViaPersonhog(SimpleTestCase):- def test_returns_person_with_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- properties={"email": "[email protected]"},- is_identified=True,- created_at=1700000000000,- distinct_ids=["did-1", "did-2"],- )-- result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="did-1")-- assert result is not None- assert result.id == 42- assert result.distinct_ids == ["did-1", "did-2"]- fake.assert_called("get_person_by_distinct_id")-- def test_returns_none_when_person_not_found(self):- with fake_personhog_client() as fake:- result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="nonexistent")-- assert result is None- fake.assert_not_called("get_distinct_ids_for_person")-- def test_returns_none_on_team_mismatch(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- distinct_ids=["did-1"],- )-- result = _fetch_person_by_distinct_id_via_personhog(team_id=1, distinct_id="did-1")-- assert result is None- fake.assert_not_called("get_distinct_ids_for_person")---class TestFetchPersonByIdViaPersonhog(SimpleTestCase):- def test_returns_person_with_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- properties={"email": "[email protected]"},- is_identified=True,- created_at=1700000000000,- distinct_ids=["did-1", "did-2"],- )-- result = _fetch_person_by_id_via_personhog(team_id=1, person_id=42)-- assert result is not None- assert result.id == 42- assert result.properties == {"email": "[email protected]"}- assert result.distinct_ids == ["did-1", "did-2"]- fake.assert_called("get_person")- fake.assert_called("get_distinct_ids_for_person")-- def test_returns_none_when_person_not_found(self):- with fake_personhog_client() as fake:- result = _fetch_person_by_id_via_personhog(team_id=1, person_id=999)-- assert result is None- fake.assert_called("get_person")- fake.assert_not_called("get_distinct_ids_for_person")-- def test_returns_none_on_team_mismatch(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- distinct_ids=["did-1"],- )-- result = _fetch_person_by_id_via_personhog(team_id=1, person_id=42)-- assert result is None- fake.assert_not_called("get_distinct_ids_for_person")---class TestFetchPersonsByDistinctIdsViaPersonhog(SimpleTestCase):- def test_returns_persons_with_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- properties={"email": "[email protected]"},- is_identified=True,- created_at=1700000000000,- distinct_ids=["did-1", "did-2"],- )-- result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1"])-- assert len(result) == 1- assert result[0].id == 42- assert result[0].properties == {"email": "[email protected]"}- assert result[0].distinct_ids == ["did-1", "did-2"]- fake.assert_called("get_persons_by_distinct_ids_in_team")- fake.assert_called("get_distinct_ids_for_persons")-- def test_no_results_for_missing_distinct_ids(self):- with fake_personhog_client() as fake:- result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["nonexistent"])-- assert result == []- fake.assert_called("get_persons_by_distinct_ids_in_team")- fake.assert_not_called("get_distinct_ids_for_persons")-- def test_cross_team_isolation(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1"]- )-- result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1"])-- assert result == []-- def test_deduplicates_persons_with_multiple_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1", "did-2"]- )-- result = _fetch_persons_by_distinct_ids_via_personhog(team_id=1, distinct_ids=["did-1", "did-2"])-- assert len(result) == 1-- def test_respects_distinct_id_limit(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440042",- distinct_ids=["did-1", "did-2", "did-3"],- )-- result = _fetch_persons_by_distinct_ids_via_personhog(- team_id=1, distinct_ids=["did-1"], distinct_id_limit=1- )-- assert len(result) == 1- assert len(result[0].distinct_ids) == 1---class TestFetchPersonsByUuidsViaPersonhog(SimpleTestCase):- def test_returns_persons_with_distinct_ids(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=1,- uuid="550e8400-e29b-41d4-a716-446655440001",- properties={"name": "Alice"},- distinct_ids=["alice-did"],- )- fake.add_person(- team_id=1,- person_id=2,- uuid="550e8400-e29b-41d4-a716-446655440002",- properties={"name": "Bob"},- distinct_ids=["bob-did"],- )-- result = _fetch_persons_by_uuids_via_personhog(- team_id=1,- uuids=["550e8400-e29b-41d4-a716-446655440001", "550e8400-e29b-41d4-a716-446655440002"],- )-- assert len(result) == 2- assert result[0].properties == {"name": "Alice"}- assert result[0].distinct_ids == ["alice-did"]- assert result[1].properties == {"name": "Bob"}- assert result[1].distinct_ids == ["bob-did"]- fake.assert_called("get_persons_by_uuids")- fake.assert_called("get_distinct_ids_for_persons")-- def test_returns_empty_for_missing_uuids(self):- with fake_personhog_client() as fake:- result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["nonexistent"])-- assert result == []- fake.assert_called("get_persons_by_uuids")- fake.assert_not_called("get_distinct_ids_for_persons")-- def test_cross_team_isolation(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1"]- )-- result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"])-- assert result == []-- def test_person_with_no_distinct_ids_gets_empty_list(self):- with fake_personhog_client() as fake:- fake.add_person(team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042")-- result = _fetch_persons_by_uuids_via_personhog(team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"])-- assert len(result) == 1- assert result[0].distinct_ids == []-- def test_distinct_id_limit_zero_skips_fetch(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]- )-- result = _fetch_persons_by_uuids_via_personhog(- team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=0- )-- assert len(result) == 1- assert result[0].distinct_ids == []- fake.assert_called("get_persons_by_uuids")- fake.assert_not_called("get_distinct_ids_for_persons")-- def test_distinct_id_limit_bounds_fetch(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["d1", "d2", "d3"]- )-- result = _fetch_persons_by_uuids_via_personhog(- team_id=1, uuids=["550e8400-e29b-41d4-a716-446655440042"], distinct_id_limit=2- )-- assert result[0].distinct_ids == ["d1", "d2"]---class TestValidateUuidsViaPersonhog(SimpleTestCase):- def test_returns_matching_uuids(self):- with fake_personhog_client() as fake:- fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])- fake.add_person(team_id=1, person_id=2, uuid="uuid-2", distinct_ids=["d2"])-- result = _validate_uuids_via_personhog(team_id=1, uuids=["uuid-1", "uuid-2", "uuid-missing"])-- assert set(result) == {"uuid-1", "uuid-2"}- fake.assert_called("get_persons_by_uuids")-- def test_filters_out_wrong_team(self):- with fake_personhog_client() as fake:- fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])- fake.add_person(team_id=999, person_id=2, uuid="uuid-2", distinct_ids=["d2"])-- result = _validate_uuids_via_personhog(team_id=1, uuids=["uuid-1", "uuid-2"])-- assert result == ["uuid-1"]-- def test_returns_empty_when_no_matches(self):- with fake_personhog_client() as fake:- result = _validate_uuids_via_personhog(team_id=1, uuids=["nonexistent"])-- assert result == []- fake.assert_called("get_persons_by_uuids")---class TestPersonsMappedByDistinctIdViaPersonhog(SimpleTestCase):- def test_returns_mapping(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=1,- person_id=42,- uuid="550e8400-e29b-41d4-a716-446655440000",- properties={"email": "[email protected]"},- distinct_ids=["did-1", "did-2"],- )-- result = get_persons_mapped_by_distinct_id(1, ["did-1"])-- assert "did-1" in result- assert result["did-1"].id == 42- assert result["did-1"].distinct_ids == ["did-1"]- fake.assert_called("get_persons_by_distinct_ids_in_team")- fake.assert_not_called("get_distinct_ids_for_persons")-- def test_returns_empty_for_missing_distinct_ids(self):- with fake_personhog_client():- result = get_persons_mapped_by_distinct_id(1, ["nonexistent"])-- assert result == {}-- def test_cross_team_isolation(self):- with fake_personhog_client() as fake:- fake.add_person(- team_id=999, person_id=42, uuid="550e8400-e29b-41d4-a716-446655440042", distinct_ids=["did-1"]- )-- result = get_persons_mapped_by_distinct_id(1, ["did-1"])-- assert result == {}---# ── Delegation tests ────────────────────────────────────────────────---class TestGetPersonByPkOrUuid(SimpleTestCase):- @patch("posthog.models.person.util.get_person_by_uuid")- def test_routes_uuid_key_to_get_person_by_uuid(self, mock_get_by_uuid):- mock_person = MagicMock()- mock_get_by_uuid.return_value = mock_person-- result = get_person_by_pk_or_uuid(1, "550e8400-e29b-41d4-a716-446655440000")-- assert result == mock_person- mock_get_by_uuid.assert_called_once_with(1, "550e8400-e29b-41d4-a716-446655440000", distinct_id_limit=None)-- @patch("posthog.models.person.util.get_person_by_id")- def test_routes_int_key_to_get_person_by_id(self, mock_get_by_id):- mock_person = MagicMock()- mock_get_by_id.return_value = mock_person-- result = get_person_by_pk_or_uuid(1, "42")-- assert result == mock_person- mock_get_by_id.assert_called_once_with(1, 42, distinct_id_limit=None)-- def test_returns_none_for_invalid_key(self):- result = get_person_by_pk_or_uuid(1, "not-a-uuid-or-int")-- assert result is None-- @patch("posthog.models.person.util.get_person_by_uuid")- def test_returns_none_when_uuid_lookup_finds_nothing(self, mock_get_by_uuid):- mock_get_by_uuid.return_value = None-- result = get_person_by_pk_or_uuid(1, "550e8400-e29b-41d4-a716-446655440000")-- assert result is None-- @patch("posthog.models.person.util.get_person_by_id")- def test_returns_none_when_id_lookup_finds_nothing(self, mock_get_by_id):- mock_get_by_id.return_value = None-- result = get_person_by_pk_or_uuid(1, "42")-- assert result is None---# ── _personhog_routed unit tests ────────────────────────────────────---class TestPersonhogRouted(SimpleTestCase):- @patch("posthog.personhog_client.gate.use_personhog", return_value=True)- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_calls_personhog_fn_and_increments_counter(self, mock_errors, mock_routing, _mock_gate):- result = _personhog_routed("test_op", lambda: "personhog_result", lambda: "orm_result", team_id=1)-- assert result == "personhog_result"- mock_routing.labels.assert_called_with(operation="test_op", source="personhog", client_name="posthog-django")- mock_routing.labels.return_value.inc.assert_called_once()- mock_errors.labels.assert_not_called()-- @patch("posthog.personhog_client.gate.use_personhog", return_value=False)- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_gate_off_uses_orm_and_increments_counter(self, mock_errors, mock_routing, _mock_gate):- result = _personhog_routed("test_op", lambda: "personhog_result", lambda: "orm_result", team_id=1)-- assert result == "orm_result"- mock_routing.labels.assert_called_with(operation="test_op", source="django_orm", client_name="posthog-django")- mock_routing.labels.return_value.inc.assert_called_once()- mock_errors.labels.assert_not_called()-- @patch("posthog.personhog_client.gate.use_personhog", return_value=True)- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_exception_falls_back_and_increments_both_counters(self, mock_errors, mock_routing, _mock_gate):- def failing_fn():- raise RuntimeError("grpc timeout")-- result = _personhog_routed("test_op", failing_fn, lambda: "orm_result", team_id=1)-- assert result == "orm_result"- # Error counter incremented- mock_errors.labels.assert_called_once_with(- operation="test_op", source="personhog", error_type="grpc_error", client_name="posthog-django"- )- mock_errors.labels.return_value.inc.assert_called_once()- # ORM routing counter incremented- mock_routing.labels.assert_called_with(operation="test_op", source="django_orm", client_name="posthog-django")- mock_routing.labels.return_value.inc.assert_called()-- @patch("posthog.personhog_client.gate.use_personhog", return_value=True)- @patch("posthog.models.person.util.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.person.util.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_returning_none_is_not_treated_as_failure(self, mock_errors, mock_routing, _mock_gate):- result = _personhog_routed("test_op", lambda: None, lambda: "orm_result", team_id=1)-- assert result is None- mock_routing.labels.assert_called_with(operation="test_op", source="personhog", client_name="posthog-django")- mock_errors.labels.assert_not_called()---# ── Integration tests (dual-path) ──────────────────────────────────---@parameterized_class(("personhog",), [(False,), (True,)])-class TestGetPersonsMappedByDistinctIdIntegration(PersonhogTestMixin, BaseTest):- def test_single_person_single_distinct_id(self):- person = self._seed_person(team=self.team, distinct_ids=["did-1"], properties={"email": "[email protected]"})-- result = get_persons_mapped_by_distinct_id(self.team.pk, ["did-1"])-- assert "did-1" in result- assert str(result["did-1"].uuid) == str(person.uuid)- assert result["did-1"].properties == {"email": "[email protected]"}- assert result["did-1"].distinct_ids == ["did-1"]- self._assert_personhog_called("get_persons_by_distinct_ids_in_team")-- def test_single_person_multiple_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["did-1", "did-2"])-- result = get_persons_mapped_by_distinct_id(self.team.pk, ["did-1", "did-2"])-- # Both distinct_ids should map to the same person- assert len(result) == 2- assert str(result["did-1"].uuid) == str(person.uuid)- assert str(result["did-2"].uuid) == str(person.uuid)- # Each entry should carry only the distinct_id that was used as the key- assert result["did-1"].distinct_ids == ["did-1"]- assert result["did-2"].distinct_ids == ["did-2"]-- def test_multiple_persons(self):- p1 = self._seed_person(team=self.team, distinct_ids=["alice"], properties={"name": "Alice"})- p2 = self._seed_person(team=self.team, distinct_ids=["bob"], properties={"name": "Bob"})-- result = get_persons_mapped_by_distinct_id(self.team.pk, ["alice", "bob"])-- assert str(result["alice"].uuid) == str(p1.uuid)- assert str(result["bob"].uuid) == str(p2.uuid)-- def test_missing_distinct_ids_returns_empty(self):- result = get_persons_mapped_by_distinct_id(self.team.pk, ["nonexistent"])-- assert result == {}-- 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"])-- result = get_persons_mapped_by_distinct_id(self.team.pk, ["shared_did"])-- assert result == {}diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex 35b15f8de0be..6a84dee22260 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -2,16 +2,11 @@ from __future__ import annotationsimport jsonimport datetime-from collections.abc import Callable-from contextlib import ExitStack-from typing import TYPE_CHECKING, Optional, TypeVar, Union, cast+from typing import TYPE_CHECKING, Optional, Unionfrom uuid import UUIDfrom zoneinfo import ZoneInfofrom django.conf import settings-from django.db.models.query import Prefetch, QuerySet-from django.db.models.signals import post_delete, post_save-from django.dispatch import receiverfrom django.utils.timezone import nowimport structlog@@ -20,23 +15,17 @@ from dateutil.parser import isoparsefrom posthog.clickhouse.client import sync_executefrom posthog.kafka_client.client import ClickhouseProducerfrom posthog.kafka_client.topics import KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID-from posthog.models.person import Person, PersonDistinctId-from posthog.models.person.person import READ_DB_FOR_PERSONS+from posthog.models.person import Personfrom posthog.models.person.sql import (BULK_INSERT_PERSON_DISTINCT_ID2,INSERT_PERSON_BULK_SQL,INSERT_PERSON_DISTINCT_ID2,INSERT_PERSON_SQL,)-from posthog.models.signals import mutable_receiverfrom posthog.models.utils import UUIDT+from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.converters import proto_person_to_model-from posthog.personhog_client.metrics import (- PERSONHOG_ROUTING_ERRORS_TOTAL,- PERSONHOG_ROUTING_TOTAL,- PERSONHOG_TEAM_MISMATCH_TOTAL,- get_client_name,-)+from posthog.personhog_client.metrics import PERSONHOG_TEAM_MISMATCH_TOTAL, get_client_namefrom posthog.personhog_client.proto import (DeletePersonsRequest,GetDistinctIdsForPersonRequest,@@ -60,13 +49,7 @@ if TYPE_CHECKING:from posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2-def _get_client():- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")- return client+_get_client = require_personhog_clientdef _batched_get_persons_by_uuids(@@ -148,73 +131,32 @@ def _batched_get_distinct_ids_for_persons(if TEST:- # :KLUDGE: Hooks are kept around for tests. All other code goes through plugin-server or the other methods explicitly-- @mutable_receiver(post_save, sender=Person)- def person_created(sender, instance: Person, created, **kwargs):- create_person(- team_id=instance.team_id,- properties=instance.properties,- uuid=str(instance.uuid),- is_identified=instance.is_identified,- version=instance.version or 0,- )-- @mutable_receiver(post_save, sender=PersonDistinctId)- def person_distinct_id_created(sender, instance: PersonDistinctId, created, **kwargs):- create_person_distinct_id(- instance.team_id,- instance.distinct_id,- str(instance.person.uuid),- version=instance.version or 0,- )-- @receiver(post_delete, sender=Person)- def person_deleted(sender, instance: Person, **kwargs):- _delete_person(- instance.team_id,- instance.uuid,- int(instance.version or 0),- instance.created_at,- )- @receiver(post_delete, sender=PersonDistinctId)- def person_distinct_id_deleted(sender, instance: PersonDistinctId, **kwargs):- _delete_ch_distinct_id(- instance.team_id,- instance.person.uuid,- instance.distinct_id,- instance.version or 0,- )+ def bulk_create_persons(persons_list: list[dict]):+ """Bulk-create persons in ClickHouse and return the distinct_id → Person mapping.- try:- from freezegun import freeze_time- except:- pass+ Test-only. Builds in-memory Person instances with synthetic primary keys+ and uuids (no persons DB write) and inserts the rows into ClickHouse. The+ personhog fake is seeded by the caller (posthog.test.persons).+ """+ from posthog.test.persons import _next_synthetic_pk # noqa: PLC0415- def bulk_create_persons(persons_list: list[dict]):- persons = []- person_mapping = {}+ person_mapping: dict[str, Person] = {}+ staged: list[tuple[Person, list]] = []for _person in persons_list:- with ExitStack() as stack:- if _person.get("created_at"):- stack.enter_context(freeze_time(_person["created_at"]))- persons.append(Person(**{key: value for key, value in _person.items() if key != "distinct_ids"}))-- inserted = Person.objects.bulk_create(persons)+ person = Person(**{key: value for key, value in _person.items() if key != "distinct_ids"})+ person.id = _next_synthetic_pk()+ if not person.uuid:+ person.uuid = UUIDT()+ person.created_at = person.created_at or now()+ person.version = person.version or 0+ person._state.adding = False+ staged.append((person, _person["distinct_ids"]))person_inserts = []- distinct_ids = []distinct_id_inserts = []- for index, person in enumerate(inserted):- for distinct_id in persons_list[index]["distinct_ids"]:- distinct_ids.append(- PersonDistinctId(- person_id=person.pk,- distinct_id=distinct_id,- team_id=person.team_id,- )- )+ for person, person_distinct_ids in staged:+ for distinct_id in person_distinct_ids:distinct_id_inserts.append(f"('{distinct_id}', '{person.uuid}', {person.team_id}, 0, 0, now(), 0, 0)")person_mapping[distinct_id] = person@@ -227,7 +169,6 @@ if TEST:f"('{person.uuid}', '{created_at}', {person.team_id}, '{json.dumps(person.properties)}', {'1' if person.is_identified else '0'}, '{timestamp}', 0, 0, 0, '{last_seen_at}')")- PersonDistinctId.objects.bulk_create(distinct_ids)sync_execute(INSERT_PERSON_BULK_SQL + ", ".join(person_inserts), flush=False)sync_execute(BULK_INSERT_PERSON_DISTINCT_ID2 + ", ".join(distinct_id_inserts),@@ -331,40 +272,6 @@ def _fetch_persons_by_distinct_ids_via_personhog(]-_T = TypeVar("_T")---def _personhog_routed(- operation: str,- personhog_fn: Callable[[], _T],- orm_fn: Callable[[], _T],- *,- team_id: int,-) -> _T:- """Try personhog first, fall back to ORM on failure or when disabled.-- Handles gate check, metrics, and error logging for all personhog routing.- """- from posthog.personhog_client.gate import use_personhog-- if use_personhog():- try:- result = personhog_fn()- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()- return result- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation=operation,- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning("personhog_%s_failure", operation, team_id=team_id, exc_info=True)-- PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="django_orm", client_name=get_client_name()).inc()- return orm_fn()--def get_persons_by_distinct_ids(team_id: int,distinct_ids: list[str],@@ -372,38 +279,11 @@ def get_persons_by_distinct_ids(operation: str = "get_persons_by_distinct_ids",distinct_id_limit: int | None = None,) -> list[Person]:- def orm_fn() -> list[Person]:- did_queryset = PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS).filter(team_id=team_id).order_by("id")-- persons = list(- Person.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(- team_id=team_id,- persondistinctid__team_id=team_id,- persondistinctid__distinct_id__in=distinct_ids,- )- .prefetch_related(- Prefetch(- "persondistinctid_set",- queryset=did_queryset,- to_attr="distinct_ids_cache",- )- )- )-- if distinct_id_limit is not None:- for person in persons:- person.distinct_ids_cache = person.distinct_ids_cache[:distinct_id_limit]-- return cast(list[Person], persons)-- return _personhog_routed(+ return personhog_call(operation,lambda: _fetch_persons_by_distinct_ids_via_personhog(team_id, distinct_ids, distinct_id_limit=distinct_id_limit),- orm_fn,- team_id=team_id,)@@ -416,38 +296,19 @@ def get_persons_mapped_by_distinct_id(Optimized for callers that need a mapping keyed by distinct_id and onlyneed the single matched distinct_id on each Person (e.g. session recordings).Unlike ``get_persons_by_distinct_ids``, this avoids fetching all distinct_ids- for each person.-- ORM path: queries PersonDistinctId → Person (2 queries, no extra IDs loaded).- Personhog path: single GetPersonsByDistinctIdsInTeam RPC (no follow-up- GetDistinctIdsForPersons call needed — the response already carries the- matched distinct_id).+ for each person — a single GetPersonsByDistinctIdsInTeam RPC already carries+ the matched distinct_id."""- def orm_fn() -> dict[str, Person]:- person_distinct_ids = (- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(distinct_id__in=distinct_ids, team_id=team_id)- .select_related("person")- )- result: dict[str, Person] = {}- for pdi in person_distinct_ids:- if pdi.person and pdi.person.team_id == team_id:- pdi.person._distinct_ids = [pdi.distinct_id]- result[pdi.distinct_id] = pdi.person- return result-def personhog_fn() -> dict[str, Person]:valid_results = _batched_get_persons_by_distinct_ids(team_id, distinct_ids, "get_persons_mapped_by_distinct_id", deduplicate_by_person=False)return {r.distinct_id: proto_person_to_model(r.person, distinct_ids=[r.distinct_id]) for r in valid_results}- return _personhog_routed(+ return personhog_call("get_persons_mapped_by_distinct_id",personhog_fn,- orm_fn,- team_id=team_id,)@@ -457,7 +318,7 @@ def get_distinct_ids_for_persons(*,limit_per_person: int | None = None,) -> dict[int, list[str]]:- """Map each person_id to its distinct_ids via personhog, falling back to ORM.+ """Map each person_id to its distinct_ids via personhog.With ``limit_per_person`` set, at most that many distinct_ids are returned perperson — bounding the fetch for merge-heavy persons whose full set can be huge.@@ -465,23 +326,9 @@ def get_distinct_ids_for_persons(if not person_ids:return {}- def orm_fn() -> dict[int, list[str]]:- result: dict[int, list[str]] = {}- for person_id, distinct_id in (- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(team_id=team_id, person_id__in=person_ids)- .values_list("person_id", "distinct_id")- ):- ids = result.setdefault(person_id, [])- if limit_per_person is None or len(ids) < limit_per_person:- ids.append(distinct_id)- return result-- return _personhog_routed(+ return personhog_call("get_distinct_ids_for_persons",lambda: _batched_get_distinct_ids_for_persons(team_id, person_ids, limit_per_person=limit_per_person),- orm_fn,- team_id=team_id,)@@ -507,20 +354,10 @@ def _fetch_persons_by_uuids_via_personhog(return [proto_person_to_model(p, distinct_ids=distinct_ids_by_person.get(p.id, [])) for p in valid_persons]-def get_persons_by_uuids(- team_id: int, uuids: list[str], *, distinct_id_limit: int | None = None-) -> QuerySet | list[Person]:- personhog_fn: Callable[[], QuerySet | list[Person]] = lambda: _fetch_persons_by_uuids_via_personhog(- team_id, uuids, distinct_id_limit=distinct_id_limit- )- orm_fn: Callable[[], QuerySet | list[Person]] = lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(- team_id=team_id, uuid__in=uuids- )- return _personhog_routed(+def get_persons_by_uuids(team_id: int, uuids: list[str], *, distinct_id_limit: int | None = None) -> list[Person]:+ return personhog_call("get_persons_by_uuids",- personhog_fn,- orm_fn,- team_id=team_id,+ lambda: _fetch_persons_by_uuids_via_personhog(team_id, uuids, distinct_id_limit=distinct_id_limit),)@@ -540,11 +377,7 @@ def _distinct_ids_for_person(client: PersonHogClient, team_id: int, person_id: idef _fetch_person_by_id_via_personhog(team_id: int, person_id: int, *, distinct_id_limit: int | None = None) -> Optional[Person]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = _get_client()resp = client.get_person(GetPersonRequest(team_id=team_id, person_id=person_id))@@ -561,22 +394,16 @@ def _fetch_person_by_id_via_personhog(def get_person_by_id(team_id: int, person_id: int, *, distinct_id_limit: int | None = None) -> Optional[Person]:- return _personhog_routed(+ return personhog_call("get_person_by_id",lambda: _fetch_person_by_id_via_personhog(team_id, person_id, distinct_id_limit=distinct_id_limit),- lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(team_id=team_id, pk=person_id).first(),- team_id=team_id,)def _fetch_person_by_uuid_via_personhog(team_id: int, uuid: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = _get_client()resp = client.get_person_by_uuid(GetPersonByUuidRequest(team_id=team_id, uuid=uuid))@@ -593,22 +420,16 @@ def _fetch_person_by_uuid_via_personhog(def get_person_by_uuid(team_id: int, uuid: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:- return _personhog_routed(+ return personhog_call("get_person_by_uuid",lambda: _fetch_person_by_uuid_via_personhog(team_id, uuid, distinct_id_limit=distinct_id_limit),- lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(team_id=team_id, uuid=uuid).first(),- team_id=team_id,)def _fetch_person_by_distinct_id_via_personhog(team_id: int, distinct_id: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = _get_client()resp = client.get_person_by_distinct_id(GetPersonByDistinctIdRequest(team_id=team_id, distinct_id=distinct_id))@@ -627,15 +448,9 @@ def _fetch_person_by_distinct_id_via_personhog(def get_person_by_distinct_id(team_id: int, distinct_id: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:- return _personhog_routed(+ return personhog_call("get_person_by_distinct_id",lambda: _fetch_person_by_distinct_id_via_personhog(team_id, distinct_id, distinct_id_limit=distinct_id_limit),- lambda: (- Person.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(team_id=team_id, persondistinctid__distinct_id=distinct_id)- .first()- ),- team_id=team_id,)@@ -659,16 +474,9 @@ def _validate_uuids_via_personhog(team_id: int, uuids: list[str]) -> list[str]:def validate_person_uuids_exist(team_id: int, uuids: list[str]) -> list[str]:- return _personhog_routed(+ return personhog_call("validate_person_uuids_exist",lambda: _validate_uuids_via_personhog(team_id, uuids),- lambda: [- str(u)- for u in Person.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(team_id=team_id, uuid__in=uuids)- .values_list("uuid", flat=True)- ],- team_id=team_id,)@@ -693,57 +501,25 @@ def get_person_uuids_by_distinct_ids(team_id: int, distinct_ids: list[str]) -> l)return [r.person.uuid for r in results]- def orm_fn() -> list[str]:- person_ids_qs = (- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(team_id=team_id, distinct_id__in=distinct_ids)- .values_list("person_id", flat=True)- .distinct()- )- return [- str(uuid)- for uuid in Person.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(team_id=team_id, id__in=person_ids_qs)- .values_list("uuid", flat=True)- ]-- return _personhog_routed(+ return personhog_call("get_person_uuids_by_distinct_ids",personhog_fn,- orm_fn,- team_id=team_id,)def delete_persons_from_postgres(team_id: int, persons: list[Person]) -> None:- """Delete Person rows (and associated PersonDistinctId rows) from Postgres.+ """Delete Person rows (and associated PersonDistinctId rows) via the personhog RPC.- Uses the personhog RPC when available, falling back to ORM-based deletion.Processes in batches of 1000 (the RPC maximum)."""def personhog_fn() -> None:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")-uuids = [str(p.uuid) for p in persons]for i in range(0, len(uuids), 1000):batch = uuids[i : i + 1000]- client.delete_persons(DeletePersonsRequest(team_id=team_id, person_uuids=batch))+ _get_client().delete_persons(DeletePersonsRequest(team_id=team_id, person_uuids=batch))- def orm_fn() -> None:- for person in persons:- person.delete()-- _personhog_routed(- "delete_persons",- personhog_fn,- orm_fn,- team_id=team_id,- )+ personhog_call("delete_persons", personhog_fn)def delete_person(person: Person) -> None:@@ -774,37 +550,13 @@ def _delete_person(def _get_distinct_ids_with_version(person: Person) -> dict[str, int]:- from posthog.personhog_client.client import get_personhog_client+ def personhog_fn() -> dict[str, int]:+ resp = _get_client().get_distinct_ids_for_person(+ GetDistinctIdsForPersonRequest(team_id=person.team_id, person_id=person.pk)+ )+ return {d.distinct_id: int(d.version or 0) for d in resp.distinct_ids}- client = get_personhog_client()- if client is not None:- try:- resp = client.get_distinct_ids_for_person(- GetDistinctIdsForPersonRequest(team_id=person.team_id, person_id=person.pk)- )- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_distinct_ids_with_version", source="personhog", client_name=get_client_name()- ).inc()- return {d.distinct_id: int(d.version or 0) for d in resp.distinct_ids}- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_distinct_ids_with_version",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning("personhog_get_distinct_ids_with_version_failure", team_id=person.team_id, exc_info=True)-- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_distinct_ids_with_version", source="django_orm", client_name=get_client_name()- ).inc()- return {- distinct_id: int(version or 0)- for distinct_id, version in PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(person=person, team_id=person.team_id)- .order_by("id")- .values_list("distinct_id", "version")- }+ return personhog_call("get_distinct_ids_with_version", personhog_fn)def _delete_ch_distinct_id(team_id: int, uuid: UUID, distinct_id: str, version: int) -> None:diff --git a/posthog/models/team/test_util_deletion.py b/posthog/models/team/test_util_deletion.pyindex 860a105e2c30..bd034614aa9b 100644--- a/posthog/models/team/test_util_deletion.py+++ b/posthog/models/team/test_util_deletion.py@@ -23,6 +23,8 @@ class TestDeleteGroupsForTeams(SimpleTestCase):_delete_groups_for_teams([1, 2, 3])assert mock_client.delete_groups_batch_for_team.call_count == 3+ req = mock_client.delete_groups_batch_for_team.call_args[0][0]+ assert req.batch_size == 10000@patch(_CLIENT_PATCH)def test_loops_until_zero_deleted(self, mock_get_client):@@ -40,40 +42,6 @@ class TestDeleteGroupsForTeams(SimpleTestCase):assert mock_client.delete_groups_batch_for_team.call_count == 3- @patch(_CLIENT_PATCH)- def test_uses_batch_size_10000(self, mock_get_client):- mock_client = MagicMock()- resp = MagicMock()- resp.deleted_count = 0- mock_client.delete_groups_batch_for_team.return_value = resp- mock_get_client.return_value = mock_client-- _delete_groups_for_teams([42])-- req = mock_client.delete_groups_batch_for_team.call_args[0][0]- assert req.batch_size == 10000- assert req.team_id == 42-- @patch("posthog.models.team.util._raw_delete")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_when_client_none(self, mock_get_client, mock_raw_delete):- mock_get_client.return_value = None-- _delete_groups_for_teams([42])-- mock_raw_delete.assert_called_once()-- @patch("posthog.models.team.util._raw_delete")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_on_error(self, mock_get_client, mock_raw_delete):- mock_client = MagicMock()- mock_client.delete_groups_batch_for_team.side_effect = Exception("rpc failed")- mock_get_client.return_value = mock_client-- _delete_groups_for_teams([42])-- mock_raw_delete.assert_called_once()-@patch(_CLIENT_PATCH)def test_empty_list_does_nothing(self, mock_get_client):_delete_groups_for_teams([])@@ -93,6 +61,8 @@ class TestDeleteGroupTypeMappingsForTeams(SimpleTestCase):_delete_group_type_mappings_for_teams([1, 2, 3])assert mock_client.delete_group_type_mappings_batch_for_team.call_count == 3+ req = mock_client.delete_group_type_mappings_batch_for_team.call_args[0][0]+ assert req.batch_size == 10000@patch(_CLIENT_PATCH)def test_loops_until_zero_deleted(self, mock_get_client):@@ -108,42 +78,6 @@ class TestDeleteGroupTypeMappingsForTeams(SimpleTestCase):assert mock_client.delete_group_type_mappings_batch_for_team.call_count == 2- @patch(_CLIENT_PATCH)- def test_uses_batch_size_10000(self, mock_get_client):- mock_client = MagicMock()- resp = MagicMock()- resp.deleted_count = 0- mock_client.delete_group_type_mappings_batch_for_team.return_value = resp- mock_get_client.return_value = mock_client-- _delete_group_type_mappings_for_teams([42])-- req = mock_client.delete_group_type_mappings_batch_for_team.call_args[0][0]- assert req.batch_size == 10000- assert req.team_id == 42-- @patch("posthog.models.team.util._raw_delete")- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_when_client_none(self, mock_get_client, mock_objects, mock_raw_delete):- mock_get_client.return_value = None-- _delete_group_type_mappings_for_teams([42])-- mock_raw_delete.assert_called_once()-- @patch("posthog.models.team.util._raw_delete")- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_on_error(self, mock_get_client, mock_objects, mock_raw_delete):- mock_client = MagicMock()- mock_client.delete_group_type_mappings_batch_for_team.side_effect = Exception("rpc failed")- mock_get_client.return_value = mock_client-- _delete_group_type_mappings_for_teams([42])-- mock_raw_delete.assert_called_once()-@patch(_CLIENT_PATCH)def test_empty_list_does_nothing(self, mock_get_client):_delete_group_type_mappings_for_teams([])@@ -183,26 +117,6 @@ class TestDeleteHashKeyOverridesForTeams(SimpleTestCase):assert mock_client.delete_hash_key_overrides_by_teams.call_count == 3- @patch("posthog.models.team.util._raw_delete_batch")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_when_client_none(self, mock_get_client, mock_raw_delete_batch):- mock_get_client.return_value = None-- _delete_hash_key_overrides_for_teams([42])-- mock_raw_delete_batch.assert_called_once()-- @patch("posthog.models.team.util._raw_delete_batch")- @patch(_CLIENT_PATCH)- def test_falls_back_to_orm_on_error(self, mock_get_client, mock_raw_delete_batch):- mock_client = MagicMock()- mock_client.delete_hash_key_overrides_by_teams.side_effect = Exception("rpc failed")- mock_get_client.return_value = mock_client-- _delete_hash_key_overrides_for_teams([42])-- mock_raw_delete_batch.assert_called_once()-@patch(_CLIENT_PATCH)def test_empty_list_does_nothing(self, mock_get_client):_delete_hash_key_overrides_for_teams([])diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 0f875ef0a5c9..8d92c6d290fe 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -36,7 +36,6 @@ def delete_bulky_postgres_data(team_ids: list[int]):_delete_group_type_mappings_for_teams(team_ids)# Delete Person + PersonDistinctId via personhog RPC (handles both tables).- # Falls back to ORM batch deletion when personhog is not available._delete_persons_for_teams(team_ids)@@ -67,7 +66,7 @@ def _delete_misc_small_tables_for_teams(team_ids: list[int]) -> None:def _delete_hash_key_overrides_for_teams(team_ids: list[int]) -> None:- """Delete FeatureFlagHashKeyOverride rows for the given teams via personhog, falling back to ORM.+ """Delete FeatureFlagHashKeyOverride rows for the given teams via personhog.These rows reference Person but have no DB-level cascade (cross-database FK withdb_constraint=False), so they must be deleted explicitly before the persons are.@@ -75,70 +74,44 @@ def _delete_hash_key_overrides_for_teams(team_ids: list[int]) -> None:if not team_ids:return- from posthog.models.person.util import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name- from posthog.personhog_client.caller_tag import personhog_caller_tag- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import DeleteHashKeyOverridesByTeamsRequest- from products.feature_flags.backend.models.feature_flag import FeatureFlagHashKeyOverride+ client = require_personhog_client()- client = get_personhog_client()- if client is not None:- try:- with personhog_caller_tag("team-delete/hash-key-overrides"):- while True:- resp = client.delete_hash_key_overrides_by_teams(- DeleteHashKeyOverridesByTeamsRequest(team_ids=team_ids, batch_size=10000)- )- if resp.deleted_count == 0:- break- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_hash_key_overrides_for_teams", source="personhog", client_name=get_client_name()- ).inc()- return- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="delete_hash_key_overrides_for_teams",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning("personhog_delete_hash_key_overrides_for_teams_failure", team_ids=team_ids, exc_info=True)-- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_hash_key_overrides_for_teams", source="django_orm", client_name=get_client_name()- ).inc()- _raw_delete_batch(- FeatureFlagHashKeyOverride.objects.filter(team_id__in=team_ids) # nosemgrep: no-direct-persons-db-orm+ def _fn() -> None:+ while True:+ resp = client.delete_hash_key_overrides_by_teams(+ DeleteHashKeyOverridesByTeamsRequest(team_ids=team_ids, batch_size=10000)+ )+ if resp.deleted_count == 0:+ break++ personhog_call(+ "delete_hash_key_overrides_for_teams",+ _fn,+ caller_tag="team-delete/hash-key-overrides",)def _delete_personless_distinct_ids_for_teams(team_ids: list[int]) -> None:- """Delete posthog_personlessdistinctid rows for teams via personhog RPC.-- Falls back to the raw batched SQL delete when personhog is not available.- Uses _personhog_routed per team for consistent gate/metrics/fallback.- """+ """Delete posthog_personlessdistinctid rows for teams via personhog RPC."""from functools import partial- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_callfor team_id in team_ids:- _personhog_routed(+ personhog_call("delete_personless_distinct_ids_for_team",partial(_delete_personless_distinct_ids_for_team_via_personhog, team_id),- partial(_raw_delete_personless_distinct_ids_for_team, team_id),- team_id=team_id,)def _delete_personless_distinct_ids_for_team_via_personhog(team_id: int) -> None:- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import require_personhog_clientfrom posthog.personhog_client.proto import DeletePersonlessDistinctIdsBatchForTeamRequest- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = require_personhog_client()while True:resp = client.delete_personless_distinct_ids_batch_for_team(@@ -158,74 +131,27 @@ def _delete_cohort_members_for_all_teams(team_ids: list[int]) -> None:_delete_cohort_members_for_teams(team_ids, cohort_ids)-def _raw_delete_personless_distinct_ids_for_team(team_id: int, batch_size: int = 10000) -> None:- """Delete posthog_personlessdistinctid rows for a single team in batches.-- Uses a CTE + ctid pattern so each batch is one statement: the inner SELECT- streams ctids from the (team_id, distinct_id) unique index and the outer- DELETE targets heap tuples directly, avoiding a per-row primary key lookup.- Each batch runs in its own autocommit statement so row locks release between- batches and autovacuum can keep up.- """- from django.db import connections, router-- from posthog.models.person import PersonlessDistinctId-- db_alias = router.db_for_write(PersonlessDistinctId)- db_connection = connections[db_alias]- table_name = PersonlessDistinctId._meta.db_table-- while True:- with db_connection.cursor() as cursor:- cursor.execute(- f"""- WITH deletion_candidates AS (- SELECT ctid- FROM {table_name}- WHERE team_id = %s- LIMIT %s- )- DELETE FROM {table_name} p- USING deletion_candidates d- WHERE p.ctid = d.ctid- """, # nosemgrep: no-direct-persons-db-orm- [team_id, batch_size],- )- deleted = cursor.rowcount-- if deleted < batch_size:- break-- time.sleep(0.1)--def _delete_persons_for_teams(team_ids: list[int]) -> None:"""Delete Person + PersonDistinctId rows for teams via personhog RPC.- Falls back to ORM batch deletion when personhog is not available.The RPC handles PersonDistinctId deletion automatically.- Uses _personhog_routed per team for consistent gate/metrics/fallback."""from functools import partial- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_callfor team_id in team_ids:- _personhog_routed(+ personhog_call("delete_persons_for_team",partial(_delete_persons_for_team_via_personhog, team_id),- partial(_delete_persons_for_team_via_orm, team_id),- team_id=team_id,)def _delete_persons_for_team_via_personhog(team_id: int) -> None:- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import require_personhog_clientfrom posthog.personhog_client.proto import DeletePersonsBatchForTeamRequest- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")+ client = require_personhog_client()while True:resp = client.delete_persons_batch_for_team(DeletePersonsBatchForTeamRequest(team_id=team_id, batch_size=10000))@@ -233,88 +159,48 @@ def _delete_persons_for_team_via_personhog(team_id: int) -> None:break-def _delete_persons_for_team_via_orm(team_id: int) -> None:- from posthog.models.person import Person, PersonDistinctId-- _raw_delete_batch(PersonDistinctId.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm- _raw_delete_batch(Person.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm--def _delete_groups_for_teams(team_ids: list[int]) -> None:- from posthog.models.group.group import Group- from posthog.models.person.util import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import DeleteGroupsBatchForTeamRequest- client = get_personhog_client()+ client = require_personhog_client()+for team_id in team_ids:- if client is not None:- try:- while True:- resp = client.delete_groups_batch_for_team(- DeleteGroupsBatchForTeamRequest(team_id=team_id, batch_size=10000)- )- if resp.deleted_count == 0:- break- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_groups_for_team", source="personhog", client_name=get_client_name()- ).inc()- continue- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="delete_groups_for_team",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning("personhog_delete_groups_for_team_failure", team_id=team_id, exc_info=True)- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_groups_for_team", source="django_orm", client_name=get_client_name()- ).inc()- _raw_delete(Group.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm+ def _fn(tid: int = team_id) -> None:+ while True:+ resp = client.delete_groups_batch_for_team(+ DeleteGroupsBatchForTeamRequest(team_id=tid, batch_size=10000)+ )+ if resp.deleted_count == 0:+ break++ personhog_call("delete_groups_for_team", _fn)def _delete_group_type_mappings_for_teams(team_ids: list[int]) -> None:- from posthog.models.group_type_mapping import GroupTypeMapping- from posthog.models.person.util import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name- from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import DeleteGroupTypeMappingsBatchForTeamRequest- client = get_personhog_client()+ client = require_personhog_client()+for team_id in team_ids:- if client is not None:- try:- while True:- resp = client.delete_group_type_mappings_batch_for_team(- DeleteGroupTypeMappingsBatchForTeamRequest(team_id=team_id, batch_size=10000)- )- if resp.deleted_count == 0:- break- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_group_type_mappings_for_team", source="personhog", client_name=get_client_name()- ).inc()- continue- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="delete_group_type_mappings_for_team",- source="personhog",- error_type="grpc_error",- client_name=get_client_name(),- ).inc()- logger.warning("personhog_delete_group_type_mappings_for_team_failure", team_id=team_id, exc_info=True)- PERSONHOG_ROUTING_TOTAL.labels(- operation="delete_group_type_mappings_for_team", source="django_orm", client_name=get_client_name()- ).inc()- _raw_delete(GroupTypeMapping.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm+ def _fn(tid: int = team_id) -> None:+ while True:+ resp = client.delete_group_type_mappings_batch_for_team(+ DeleteGroupTypeMappingsBatchForTeamRequest(team_id=tid, batch_size=10000)+ )+ if resp.deleted_count == 0:+ break++ personhog_call("delete_group_type_mappings_for_team", _fn)def _delete_cohort_members_for_teams(team_ids: list[int], cohort_ids: list[int]) -> None:"""Delete CohortPeople rows for teams via personhog RPC.- Falls back to ORM _raw_delete when personhog is not available.- Routes per-team for consistent gate/metrics/fallback behavior.+ Routes per-team for consistent metrics."""from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import delete_cohort_members_bulk@@ -325,15 +211,6 @@ def _delete_cohort_members_for_teams(team_ids: list[int], cohort_ids: list[int])delete_cohort_members_bulk(team_id, team_cohort_ids)-def _raw_delete(queryset: Any):- "Issues a single DELETE statement for the queryset"- from django.db import router-- # Use db_for_write to ensure we get a writable connection (not read-only replica)- db_alias = router.db_for_write(queryset.model)- queryset._raw_delete(db_alias)--def _raw_delete_batch(queryset: Any, batch_size: int = 10000):"""Deletes records in batches to avoid statement timeout on large tables.diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.pyindex 79d243d03d0d..61957b2705f7 100644--- a/posthog/models/test/test_group_type_mapping.py+++ b/posthog/models/test/test_group_type_mapping.py@@ -1,12 +1,7 @@-from datetime import UTC, datetime--from posthog.test.base import BaseTest-from unittest.mock import ANY, MagicMock, patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, override_settings-from parameterized import parameterized-from posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX,@@ -27,12 +22,8 @@ from posthog.models.group_type_mapping import (project_has_group_types_authoritatively,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_set-from products.dashboards.backend.models.dashboard import Dashboard-def _clear_cache(project_id: int) -> None:safe_cache_delete(f"{GROUP_TYPES_CACHE_KEY_PREFIX}{project_id}")@@ -60,23 +51,10 @@ PERSONHOG_SUCCESS_DATA = [},]-ORM_DATA = [- {- "group_type": "team",- "group_type_index": 0,- "name_singular": None,- "name_plural": None,- "detail_dashboard": None,- "default_columns": None,- "created_at": None,- },-]--_CLIENT_PATCH = "posthog.personhog_client.client.get_personhog_client"-class TestGetGroupTypesForProjectRouting(SimpleTestCase):+class TestGetGroupTypesForProject(SimpleTestCase):def setUp(self):self.project_id = 999_clear_cache(self.project_id)@@ -89,12 +67,8 @@ class TestGetGroupTypesForProjectRouting(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_returns_data_and_caches(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -104,35 +78,17 @@ 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=ANY- )- mock_errors_counter.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_failure_falls_back_to_orm(+ def test_personhog_failure_without_stale_returns_empty(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,- mock_objects,):mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = ORM_DATA- mock_objects.filter.return_value = mock_qs-result = get_group_types_for_project(self.project_id)- assert result == ORM_DATA- mock_routing_counter.labels.assert_called_with(- operation="get_group_types_for_project", source="django_orm", client_name=ANY- )- mock_errors_counter.labels.assert_called_once()+ assert result == []@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")def test_cache_hit_skips_both_paths(self, mock_objects):@@ -146,19 +102,11 @@ class TestGetGroupTypesForProjectRouting(SimpleTestCase):assert result == cached_datamock_objects.filter.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_both_paths_fail_returns_stale_cache(+ def test_personhog_failure_returns_stale_cache(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,- mock_objects,):- from django.db import DatabaseError-from posthog.utils import safe_cache_setstale_data = [{"group_type": "stale", "group_type_index": 0}]@@ -166,51 +114,12 @@ class TestGetGroupTypesForProjectRouting(SimpleTestCase):mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")- # The code calls list(qs.filter(...).order_by(...).values(...))- # so we need __iter__ on the values() result to raise DatabaseError- def _raise_db_error():- raise DatabaseError("db is down")-- mock_values_qs = MagicMock()- mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = mock_values_qs- mock_objects.filter.return_value = mock_qs-result = get_group_types_for_project(self.project_id)assert result == stale_data- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_both_paths_fail_no_stale_returns_empty_list(- self,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- from django.db import DatabaseError- mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")-- def _raise_db_error():- raise DatabaseError("db is down")-- mock_values_qs = MagicMock()- mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = mock_values_qs- mock_objects.filter.return_value = mock_qs-- result = get_group_types_for_project(self.project_id)-- assert result == []---class TestGetGroupTypesForTeamRouting(SimpleTestCase):+class TestGetGroupTypesForTeam(SimpleTestCase):def setUp(self):self.team_id = 42self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())@@ -221,12 +130,8 @@ class TestGetGroupTypesForTeamRouting(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_returns_data_without_orm(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -236,91 +141,20 @@ 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=ANY- )- mock_errors_counter.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_failure_falls_back_to_orm(+ def test_personhog_failure_returns_empty(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,- mock_objects,):mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = ORM_DATA- mock_objects.filter.return_value = mock_qs-result = get_group_types_for_team(self.team_id)- assert result == ORM_DATA- mock_errors_counter.labels.assert_called_once_with(- operation="get_group_types_for_team",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )-- @parameterized.expand(- [- ("grpc_error", RuntimeError("grpc timeout")),- ("connection_error", ConnectionError("connection refused")),- ("generic_error", Exception("unexpected")),- ]- )- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_error_types_always_increment_error_metric(- self,- _name,- exception,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- mock_fetch_personhog.side_effect = exception- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = ORM_DATA- mock_objects.filter.return_value = mock_qs-- get_group_types_for_team(self.team_id)-- mock_errors_counter.labels.assert_called_once()-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_orm_fallback_increments_django_orm_metric(- self,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")-- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = ORM_DATA- mock_objects.filter.return_value = mock_qs-- get_group_types_for_team(self.team_id)-- calls = [str(c) for c in mock_routing_counter.labels.call_args_list]- assert any("django_orm" in c for c in calls), f"Expected django_orm routing label, got: {calls}"+ assert result == []-class TestGetGroupTypesForProjectsRouting(SimpleTestCase):+class TestGetGroupTypesForProjects(SimpleTestCase):def setUp(self):self.project_ids = [1, 2, 3]self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())@@ -348,12 +182,8 @@ class TestGetGroupTypesForProjectsRouting(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_returns_grouped_data_without_orm(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -368,70 +198,24 @@ 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=ANY- )- mock_errors_counter.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_failure_falls_back_to_orm(+ def test_personhog_failure_without_stale_raises_unavailable(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,- mock_objects,):+ for pid in self.project_ids:+ _clear_cache(pid)mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")- orm_rows = [- {- "project_id": 1,- "group_type": "organization",- "group_type_index": 0,- "name_singular": None,- "name_plural": None,- "detail_dashboard": None,- "default_columns": None,- "created_at": None,- },- {- "project_id": 2,- "group_type": "company",- "group_type_index": 0,- "name_singular": None,- "name_plural": None,- "detail_dashboard": None,- "default_columns": None,- "created_at": None,- },- ]- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = [dict(r) for r in orm_rows]- mock_objects.filter.return_value = mock_qs+ with self.assertRaises(GroupTypesUnavailable) as ctx:+ get_group_types_for_projects(self.project_ids)- result = get_group_types_for_projects(self.project_ids)-- assert 1 in result- assert 2 in result- assert 3 in result- assert result[3] == []- mock_errors_counter.labels.assert_called_once_with(- operation="get_group_types_for_projects",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )+ assert set(ctx.exception.project_ids) == set(self.project_ids)@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_empty_project_ids_returns_empty_dict_via_personhog(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,):mock_fetch_personhog.return_value = {}@@ -439,36 +223,10 @@ class TestGetGroupTypesForProjectsRouting(SimpleTestCase):result = get_group_types_for_projects([])assert result == {}- mock_errors_counter.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_orm_fallback_initializes_all_project_ids_to_empty_list(- self,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")-- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = []- mock_objects.filter.return_value = mock_qs-- result = get_group_types_for_projects([10, 20, 30])-- assert result == {10: [], 20: [], 30: []}-- @patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_backfills_missing_project_ids_with_empty_lists(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,):mock_fetch_personhog.return_value = {@@ -497,12 +255,8 @@ class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_empty_list_result_is_cached(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -517,12 +271,8 @@ class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_populates_stale_cache(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -538,12 +288,8 @@ class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_empty_success_does_not_clobber_populated_stale(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -574,12 +320,8 @@ class TestGetGroupTypesForTeamEdgeCases(SimpleTestCase):@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_returns_empty_list(self,- mock_errors_counter,- mock_routing_counter,mock_fetch_personhog,mock_objects,):@@ -590,78 +332,6 @@ class TestGetGroupTypesForTeamEdgeCases(SimpleTestCase):assert result == []mock_objects.filter.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_orm_database_error_returns_empty_list(- self,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- from django.db import DatabaseError-- mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")-- def _raise_db_error():- raise DatabaseError("db is down")-- mock_values_qs = MagicMock()- mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = mock_values_qs- mock_objects.filter.return_value = mock_qs-- result = get_group_types_for_team(42)-- assert result == []---class TestGetGroupTypesForProjectsEdgeCases(SimpleTestCase):- def setUp(self):- for pid in (10, 20):- _clear_cache(pid)- self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())- self._client_patcher.start()-- def tearDown(self):- self._client_patcher.stop()- for pid in (10, 20):- _clear_cache(pid)-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_orm_database_error_without_stale_fails_closed(- self,- mock_errors_counter,- mock_routing_counter,- mock_fetch_personhog,- mock_objects,- ):- from django.db import DatabaseError-- mock_fetch_personhog.side_effect = RuntimeError("grpc timeout")-- def _raise_db_error():- raise DatabaseError("db is down")-- mock_values_qs = MagicMock()- mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = mock_values_qs- mock_objects.filter.return_value = mock_qs-- # With no last-known-good, the batch fetch fails closed rather than- # returning an all-empty mapping that would silently disable group flags.- with self.assertRaises(GroupTypesUnavailable) as ctx:- get_group_types_for_projects([10, 20])-- assert set(ctx.exception.project_ids) == {10, 20}-class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):def setUp(self):@@ -673,12 +343,8 @@ class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):self._client_patcher.stop()@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")def test_personhog_success_returns_converted_counts(self,- mock_errors_counter,- mock_routing_counter,mock_objects,):mock_count_1 = MagicMock()@@ -696,85 +362,12 @@ 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=ANY- )- mock_errors_counter.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_personhog_failure_falls_back_to_orm(+ def test_personhog_failure_returns_empty(self,- mock_errors_counter,- mock_routing_counter,- mock_objects,):self._mock_client.count_group_type_mappings.side_effect = RuntimeError("grpc timeout")- orm_data = [{"team_id": 1, "total": 3}]- mock_qs = MagicMock()- mock_qs.annotate.return_value.order_by.return_value = orm_data- mock_objects.values.return_value = mock_qs-- result = count_group_type_mappings_per_team()-- assert result == orm_data- mock_errors_counter.labels.assert_called_once_with(- operation="count_group_type_mappings_per_team",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_no_client_uses_orm_directly(- self,- mock_errors_counter,- mock_routing_counter,- mock_objects,- ):- self._client_patcher.stop()- no_client_patcher = patch(_CLIENT_PATCH, return_value=None)- no_client_patcher.start()-- orm_data = [{"team_id": 10, "total": 2}]- mock_qs = MagicMock()- mock_qs.annotate.return_value.order_by.return_value = orm_data- mock_objects.values.return_value = mock_qs-- result = count_group_type_mappings_per_team()-- assert result == orm_data- mock_routing_counter.labels.assert_called_with(- operation="count_group_type_mappings_per_team", source="django_orm", client_name=ANY- )- mock_errors_counter.labels.assert_not_called()-- no_client_patcher.stop()- self._mock_client = MagicMock()- self._client_patcher = patch(_CLIENT_PATCH, return_value=self._mock_client)- self._client_patcher.start()-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_both_paths_fail_returns_empty_list(- self,- mock_errors_counter,- mock_routing_counter,- mock_objects,- ):- from django.db import DatabaseError-- self._mock_client.count_group_type_mappings.side_effect = RuntimeError("grpc timeout")-- mock_qs = MagicMock()- mock_qs.annotate.return_value.order_by.side_effect = DatabaseError("db is down")- mock_objects.values.return_value = mock_qs-result = count_group_type_mappings_per_team()assert result == []@@ -791,15 +384,14 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):return instancedef _mock_objects_filter(self):- """Patch GroupTypeMapping.objects.filter so the ORM fallback doesn't hit a real DB."""+ """Patch GroupTypeMapping.objects so a stray ORM call can't hit a real DB."""patcher = patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")mock_objects = patcher.start()self.addCleanup(patcher.stop)return mock_objects- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_personhog_success_does_not_call_orm(self, mock_get_client, mock_routing_counter):+ def test_personhog_success_does_not_call_orm(self, mock_get_client):mock_client = MagicMock()mock_client.update_group_type_mapping.return_value = MagicMock()mock_get_client.return_value = mock_client@@ -817,70 +409,9 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):assert req.name_singular == "Org"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=ANY- )-- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_client_none_falls_back_to_orm_update(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None- mock_objects = self._mock_objects_filter()-- instance = self._make_instance()- update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})-- 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=ANY- )-- @parameterized.expand(- [- ("grpc_timeout", RuntimeError("grpc timeout")),- ("connection_error", ConnectionError("connection refused")),- ]- )- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm(- self, _name, exception, mock_get_client, mock_routing_counter, mock_errors_counter- ):- mock_client = MagicMock()- mock_client.update_group_type_mapping.side_effect = exception- mock_get_client.return_value = mock_client-- mock_objects = self._mock_objects_filter()- instance = self._make_instance()- update_group_type_mapping_fields(instance, fields={"name_singular": "Org"})-- 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_errors_counter.labels.assert_called_once_with(- operation="update_group_type_mapping_fields",- source="personhog",- error_type="grpc_error",- client_name=ANY,- )-- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_orm_fallback_sets_fields_on_instance(self, mock_get_client, mock_routing_counter):- mock_get_client.return_value = None- self._mock_objects_filter()-- instance = self._make_instance()- update_group_type_mapping_fields(instance, fields={"name_singular": "Team", "default_columns": ["name"]})-- assert instance.name_singular == "Team"- assert instance.default_columns == ["name"]-- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_detail_dashboard_id_sent_correctly(self, mock_get_client, mock_routing_counter):+ def test_detail_dashboard_id_sent_correctly(self, mock_get_client):mock_client = MagicMock()mock_client.update_group_type_mapping.return_value = MagicMock()mock_get_client.return_value = mock_client@@ -892,9 +423,8 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):assert req.detail_dashboard_id == 42assert "detail_dashboard_id" in req.update_mask- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_detail_dashboard_id_none_leaves_field_unset(self, mock_get_client, mock_routing_counter):+ def test_detail_dashboard_id_none_leaves_field_unset(self, mock_get_client):mock_client = MagicMock()mock_client.update_group_type_mapping.return_value = MagicMock()mock_get_client.return_value = mock_client@@ -906,9 +436,8 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):assert "detail_dashboard_id" in req.update_maskassert req.detail_dashboard_id == 0- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_default_columns_json_encoded(self, mock_get_client, mock_routing_counter):+ def test_default_columns_json_encoded(self, mock_get_client):mock_client = MagicMock()mock_client.update_group_type_mapping.return_value = MagicMock()mock_get_client.return_value = mock_client@@ -928,9 +457,8 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):instance.group_type_index = 0return instance- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_personhog_success_does_not_call_orm_delete(self, mock_get_client, mock_routing_counter):+ def test_personhog_success_does_not_call_orm_delete(self, mock_get_client):mock_client = MagicMock()mock_client.delete_group_type_mapping.return_value = MagicMock()mock_get_client.return_value = mock_client@@ -943,49 +471,12 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):assert req.project_id == 1assert 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=ANY- )-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_client_none_falls_back_to_orm_delete(self, mock_get_client, mock_routing_counter, mock_objects):- mock_get_client.return_value = None-- instance = self._make_instance()- delete_group_type_mapping(instance)-- 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=ANY- )-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm_delete(- self, mock_get_client, mock_routing_counter, mock_errors_counter, mock_objects- ):- mock_client = MagicMock()- mock_client.delete_group_type_mapping.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- instance = self._make_instance()- delete_group_type_mapping(instance)-- mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)- mock_objects.filter.return_value.delete.assert_called_once()- mock_errors_counter.labels.assert_called_once()class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):@patch("posthog.models.group_type_mapping.invalidate_group_types_cache")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_personhog_success_reads_then_updates(self, mock_get_client, mock_routing_counter, mock_invalidate):+ def test_personhog_success_reads_then_updates(self, mock_get_client, mock_invalidate):mock_mapping = MagicMock()mock_mapping.project_id = 1mock_mapping.group_type_index = 0@@ -1009,9 +500,8 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_invalidate.assert_called_once_with(1)@patch("posthog.models.group_type_mapping.invalidate_group_types_cache")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_personhog_group_type_index_zero_still_clears(self, mock_get_client, mock_routing_counter, mock_invalidate):+ def test_personhog_group_type_index_zero_still_clears(self, mock_get_client, mock_invalidate):"""group_type_index=0 is falsy but valid — HasField must not skip it."""mock_mapping = MagicMock(spec=["project_id", "group_type_index"])mock_mapping.project_id = 1@@ -1034,9 +524,8 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_invalidate.assert_called_once_with(1)@patch("posthog.models.group_type_mapping.invalidate_group_types_cache")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch(_CLIENT_PATCH)- def test_personhog_no_matching_mapping_skips_update(self, mock_get_client, mock_routing_counter, mock_invalidate):+ def test_personhog_no_matching_mapping_skips_update(self, mock_get_client, mock_invalidate):mock_resp = MagicMock()mock_resp.HasField.return_value = False@@ -1049,118 +538,56 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_client.update_group_type_mapping.assert_not_called()mock_invalidate.assert_not_called()- @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_client_none_falls_back_to_orm(self, mock_get_client, mock_routing_counter, mock_objects, mock_invalidate):- mock_get_client.return_value = None-- clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42, project_id=1)-- 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=ANY- )-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")- @patch(_CLIENT_PATCH)- def test_personhog_exception_falls_back_to_orm(- self, mock_get_client, mock_routing_counter, mock_errors_counter, mock_objects- ):- mock_client = MagicMock()- mock_client.get_group_type_mapping_by_dashboard_id.side_effect = RuntimeError("grpc timeout")- mock_get_client.return_value = mock_client-- clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42, project_id=1)-- mock_objects.using.assert_called_once()- mock_errors_counter.labels.assert_called_once()-# ── Terminal-failure hardening tests ──────────────────────────────────-def _make_db_error_objects() -> MagicMock:- # GroupTypeMapping.objects mock whose .filter(...).order_by(...).values()- # raises DatabaseError when iterated.- from django.db import DatabaseError-- def _raise_db_error():- raise DatabaseError("db is down")-- mock_values_qs = MagicMock()- mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = mock_values_qs- mock_objects = MagicMock()- mock_objects.filter.return_value = mock_qs- return mock_objects--class TestTerminalFetchFailureMetric(SimpleTestCase):def setUp(self):self.project_id = 7777_clear_cache(self.project_id)- # client None skips the personhog leg, isolating the ORM failure- self._client_patcher = patch(_CLIENT_PATCH, return_value=None)+ self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())self._client_patcher.start()def tearDown(self):self._client_patcher.stop()_clear_cache(self.project_id)- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_single_project_db_error_increments_fetch_failures_not_personhog(- self, mock_personhog_errors, mock_fetch_failures, mock_objects- ):- mock_objects.filter.side_effect = _make_db_error_objects().filter-+ @patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog", side_effect=RuntimeError("grpc fail"))+ def test_single_project_failure_increments_fetch_failures(self, _mock_fetch, mock_fetch_failures):result = get_group_types_for_project(self.project_id)assert result == []mock_fetch_failures.labels.assert_called_once_with(- operation="get_group_types_for_project", source="django_orm", error_type="db_error"+ operation="get_group_types_for_project", source="personhog", error_type="db_error")- mock_personhog_errors.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_team_db_error_increments_fetch_failures_not_personhog(- self, mock_personhog_errors, mock_fetch_failures, mock_objects- ):- mock_objects.filter.side_effect = _make_db_error_objects().filter-+ @patch(+ "posthog.models.group_type_mapping._fetch_group_types_for_team_via_personhog",+ side_effect=RuntimeError("grpc fail"),+ )+ def test_team_failure_increments_fetch_failures(self, _mock_fetch, mock_fetch_failures):result = get_group_types_for_team(4242)assert result == []mock_fetch_failures.labels.assert_called_once_with(- operation="get_group_types_for_team", source="django_orm", error_type="db_error"+ operation="get_group_types_for_team", source="personhog", error_type="db_error")- mock_personhog_errors.labels.assert_not_called()- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")- @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_projects_db_error_increments_fetch_failures_not_personhog(- self, mock_personhog_errors, mock_fetch_failures, mock_objects- ):- mock_objects.filter.side_effect = _make_db_error_objects().filter-- # No stale, so it fails closed, but the counter still fires first+ @patch(+ "posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog",+ side_effect=RuntimeError("grpc fail"),+ )+ def test_projects_failure_increments_fetch_failures(self, _mock_fetch, mock_fetch_failures):with self.assertRaises(GroupTypesUnavailable):get_group_types_for_projects([self.project_id])mock_fetch_failures.labels.assert_called_once_with(- operation="get_group_types_for_projects", source="django_orm", error_type="db_error"+ operation="get_group_types_for_projects", source="personhog", error_type="db_error")- mock_personhog_errors.labels.assert_not_called()class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):@@ -1168,18 +595,21 @@ class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):self.project_ids = [101, 102]for pid in self.project_ids:_clear_cache(pid)- self._client_patcher = patch(_CLIENT_PATCH, return_value=None)+ self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())self._client_patcher.start()+ self._fetch_patcher = patch(+ "posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog",+ side_effect=RuntimeError("grpc fail"),+ )+ self._fetch_patcher.start()def tearDown(self):+ self._fetch_patcher.stop()self._client_patcher.stop()for pid in self.project_ids:_clear_cache(pid)- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_db_error_recovers_each_project_from_stale(self, mock_objects):- mock_objects.filter.side_effect = _make_db_error_objects().filter-+ def test_recovers_each_project_from_stale(self):stale_101 = [{"group_type": "org", "group_type_index": 0}]stale_102 = [{"group_type": "company", "group_type_index": 0}]safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", stale_101, 3600)@@ -1189,20 +619,13 @@ class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):assert result == {101: stale_101, 102: stale_102}- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_db_error_raises_group_types_unavailable_when_no_stale(self, mock_objects):- mock_objects.filter.side_effect = _make_db_error_objects().filter-+ def test_raises_group_types_unavailable_when_no_stale(self):with self.assertRaises(GroupTypesUnavailable) as ctx:get_group_types_for_projects(self.project_ids)assert set(ctx.exception.project_ids) == {101, 102}- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_db_error_raises_when_any_project_lacks_stale(self, mock_objects):- mock_objects.filter.side_effect = _make_db_error_objects().filter-- # Only 101 has a last-known-good; 102 is unrecoverable, so it fails closed+ def test_raises_when_any_project_lacks_stale(self):safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", [{"group_type": "org", "group_type_index": 0}], 3600)with self.assertRaises(GroupTypesUnavailable) as ctx:@@ -1210,11 +633,7 @@ class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):assert ctx.exception.project_ids == [102]- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_empty_stale_counts_as_recovered(self, mock_objects):- # A cached empty list is a known value, so it recovers rather than failing closed- mock_objects.filter.side_effect = _make_db_error_objects().filter-+ def test_empty_stale_counts_as_recovered(self):safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", [], 3600)safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}102", [], 3600)@@ -1223,57 +642,6 @@ class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):assert result == {101: [], 102: []}-class TestProjectsStaleCachePopulation(SimpleTestCase):- def setUp(self):- self.project_ids = [201, 202]- for pid in self.project_ids:- _clear_cache(pid)- self._client_patcher = patch(_CLIENT_PATCH, return_value=None)- self._client_patcher.start()-- def tearDown(self):- self._client_patcher.stop()- for pid in self.project_ids:- _clear_cache(pid)-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_orm_success_writes_non_empty_to_stale_only(self, mock_objects):- from posthog.utils import get_safe_cache-- orm_rows = [- {"project_id": 201, "group_type": "organization", "group_type_index": 0},- ]- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = [dict(r) for r in orm_rows]- mock_objects.filter.return_value = mock_qs-- result = get_group_types_for_projects(self.project_ids)-- # 201 had a mapping → persisted to stale; 202 was empty → stale left absent- assert result[201] == [{"group_type": "organization", "group_type_index": 0}]- assert result[202] == []- assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201") == [- {"group_type": "organization", "group_type_index": 0}- ]- assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}202") is None-- @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")- def test_empty_success_does_not_overwrite_existing_stale(self, mock_objects):- from posthog.utils import get_safe_cache-- prior = [{"group_type": "organization", "group_type_index": 0}]- safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201", prior, 3600)-- mock_qs = MagicMock()- mock_qs.order_by.return_value.values.return_value = [] # empty success- mock_objects.filter.return_value = mock_qs-- get_group_types_for_projects([201])-- # Empty result must not clobber the populated last-known-good- assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201") == prior--class TestRecordGroupTypesFetchFailureThrottle(SimpleTestCase):def setUp(self):self.operation = "get_group_types_for_projects"@@ -1378,74 +746,6 @@ class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):assert get_safe_cache(marker_key) is None-class TestGroupTypesForProjectPathParity(BaseTest):- """The personhog and ORM paths of get_group_types_for_project must return identical rows.-- The ORM path only runs as the fallback when personhog errors, so a shape or- value divergence would surface during incidents — compare the paths against- each other on the same data instead of against hand-written expectations.- Delete this test together with the ORM fallback.- """-- def test_personhog_and_orm_paths_return_identical_rows(self):- # Exact-millisecond timestamp: the proto carries epoch ms, so a sub-ms- # value would diverge from the ORM no matter what the code does.- created_at = datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC)- dashboard = Dashboard.objects.create(team=self.team, name="orgs")-- create_group_type_mapping(- team=self.team,- project_id=self.team.project_id,- group_type="organization",- group_type_index=0,- name_singular="Organization",- name_plural="Organizations",- default_columns=["name"],- detail_dashboard=dashboard,- created_at=created_at,- )- minimal = create_group_type_mapping(- team=self.team,- project_id=self.team.project_id,- group_type="company",- group_type_index=1,- )- # save() auto-fills created_at; NULL it to exercise the None case on both paths- GroupTypeMapping.objects.filter(pk=minimal.pk).update(created_at=None) # nosemgrep: no-direct-persons-db-orm-- fake = FakePersonHogClient()- fake.add_group_type_mapping(- project_id=self.team.project_id,- team_id=self.team.id,- group_type="organization",- group_type_index=0,- name_singular="Organization",- name_plural="Organizations",- default_columns=["name"],- detail_dashboard_id=dashboard.id,- created_at=int(created_at.timestamp() * 1000),- )- fake.add_group_type_mapping(- project_id=self.team.project_id,- team_id=self.team.id,- group_type="company",- group_type_index=1,- )-- with patch(_CLIENT_PATCH, return_value=fake):- _clear_cache(self.team.project_id)- personhog_rows = get_group_types_for_project(self.team.project_id)-- with patch(_CLIENT_PATCH, return_value=None):- _clear_cache(self.team.project_id)- orm_rows = get_group_types_for_project(self.team.project_id)-- # Guard against vacuous equality before comparing the paths- assert len(orm_rows) == 2- assert orm_rows[0]["detail_dashboard"] == dashboard.id- assert personhog_rows == orm_rows--class TestDictToGroupTypeMappingModel(SimpleTestCase):def test_builds_model_from_full_dict(self):row = {diff --git a/posthog/models/test/test_person_override_model.py b/posthog/models/test/test_person_override_model.pydeleted file mode 100644index f6aaba25de06..000000000000--- a/posthog/models/test/test_person_override_model.py+++ /dev/null@@ -1,790 +0,0 @@-import datetime as dt-import contextlib-from threading import Event, Thread-from uuid import uuid4--import pytest--from django.db.utils import DEFAULT_DB_ALIAS, ConnectionHandler, IntegrityError--from posthog.api.test.test_organization import create_organization-from posthog.api.test.test_team import create_team-from 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-pytestmark = pytest.mark.skip(reason="PersonOverride model is not used (see PR #23616)")---def organization():- organization = create_organization(name="test")-- yield organization-- organization.delete()---def team(organization):- team = create_team(organization=organization)-- yield team-- # Clean up any remaining Persons and PersonOverrides for all teams in org to avoid FK violations- # (some tests create additional teams beyond the fixture)- org_teams = Team.objects.filter(organization=organization)- Person.objects.filter(team__in=org_teams).delete()- PersonOverride.objects.filter(team__in=org_teams).delete()- org_teams.delete()---def people(team):- old_person_uuid = uuid4()- override_person_uuid = uuid4()- new_override_person_uuid = uuid4()-- 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)-- # Persons will be cleaned up by team fixture---def oldest_event():- return dt.datetime.now(dt.UTC)--[email protected]_db(transaction=True)-def test_person_override_disallows_same_old_person_id(team, oldest_event):- """Test a new old_person_id cannot match an existing old_person_id.-- This is enforced by a UNIQUE constraint on (team_id, old_person_id)- """- old_person_id = uuid4()- override_person_id = uuid4()- new_override_person_id = uuid4()-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )- person_override = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- person_override.save()-- assert person_override.old_person_id == old_mapping- assert person_override.override_person_id == override_mapping-- new_override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=new_override_person_id,- )-- with pytest.raises(IntegrityError):- PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=new_override_mapping,- oldest_event=oldest_event,- version=1,- ).save()--[email protected]_db(transaction=True)-def test_person_override_same_old_person_id_in_different_teams(organization, team, oldest_event):- """Test a new old_person_id can match an existing from a different team."""- old_person_id = uuid4()- override_person_id = uuid4()- new_team = Team.objects.create(- organization=organization,- api_token="a different token",- )-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )-- p1 = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- p1.save()-- assert p1.old_person_id == old_mapping- assert p1.override_person_id == override_mapping-- new_team_old_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=old_person_id,- )- new_team_override_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=override_person_id,- )-- p2 = PersonOverride.objects.create(- team=new_team,- old_person_id=new_team_old_mapping,- override_person_id=new_team_override_mapping,- oldest_event=oldest_event,- version=1,- )- p2.save()-- assert p1.old_person_id.uuid == p2.old_person_id.uuid- assert p1.override_person_id.uuid == p2.override_person_id.uuid- assert p1.old_person_id.id != p2.old_person_id.id- assert p1.override_person_id.id != p2.override_person_id.id- assert p1.team != p2.team--[email protected]_db(transaction=True)-def test_person_override_disallows_override_person_id_as_old_person_id(team, oldest_event):- """Test a new old_person_id cannot match an existing override_person_id.-- We re-use the override_person_id from the first model created as the old_person_id- of the second model. We expect an exception on saving this second model.- """- old_person_id = uuid4()- override_person_id = uuid4()- new_override_person_id = uuid4()-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )-- person_override = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- person_override.save()-- assert person_override.old_person_id == old_mapping- assert person_override.override_person_id == override_mapping-- new_override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=new_override_person_id,- )-- with pytest.raises(IntegrityError):- PersonOverride.objects.create(- team=team,- old_person_id=override_mapping,- override_person_id=new_override_mapping,- oldest_event=oldest_event,- version=1,- ).save()--[email protected]_db(transaction=True)-def test_person_override_allows_override_person_id_as_old_person_id_in_different_teams(- team, organization, oldest_event-):- """Test a new old_person_id can match an override in a different team."""- old_person_id = uuid4()- override_person_id = uuid4()- new_override_person_id = uuid4()- new_team = Team.objects.create(- organization=organization,- api_token="a much different token",- )-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )-- p1 = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- p1.save()-- assert p1.old_person_id == old_mapping- assert p1.override_person_id == override_mapping-- new_team_old_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=override_person_id,- )- new_team_override_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=new_override_person_id,- )- p2 = PersonOverride.objects.create(- team=new_team,- old_person_id=new_team_old_mapping,- override_person_id=new_team_override_mapping,- oldest_event=oldest_event,- version=1,- )- p2.save()-- assert p1.override_person_id.uuid == p2.old_person_id.uuid- assert p2.override_person_id == new_team_override_mapping- assert p1.team != p2.team--[email protected]_db(transaction=True)-def test_person_override_disallows_old_person_id_as_override_person_id(team, oldest_event):- """Test a new override_person_id cannot match an existing old_person_id.-- We re-use the old_person_id from the first model created as the override_person_id- of the second model. We expect an exception on saving this second model.- """- old_person_id = uuid4()- override_person_id = uuid4()- new_old_person_id = uuid4()-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- old_mapping.save()-- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )- override_mapping.save()-- person_override = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- person_override.save()-- assert person_override.old_person_id == old_mapping- assert person_override.override_person_id == override_mapping-- new_old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=new_old_person_id,- )- new_old_mapping.save()-- with pytest.raises(IntegrityError):- p = PersonOverride.objects.create(- team=team,- old_person_id=new_old_mapping,- override_person_id=old_mapping,- oldest_event=oldest_event,- version=1,- )- p.save()--[email protected]_db(transaction=True)-def test_person_override_old_person_id_as_override_person_id_in_different_teams(organization, team, oldest_event):- """Test a new override_person_id can match an old in a different team."""- old_person_id = uuid4()- override_person_id = uuid4()- new_old_person_id = uuid4()- new_team = Team.objects.create(- organization=organization,- api_token="a significantly different token",- )-- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )-- p1 = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- p1.save()-- assert p1.old_person_id == old_mapping- assert p1.override_person_id == override_mapping-- new_old_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=new_old_person_id,- )- new_override_mapping = PersonOverrideMapping.objects.create(- team_id=new_team.id,- uuid=old_mapping.uuid,- )-- p2 = PersonOverride.objects.create(- team=new_team,- old_person_id=new_old_mapping,- override_person_id=new_override_mapping,- oldest_event=oldest_event,- version=1,- )- p2.save()-- assert p1.old_person_id.uuid == p2.override_person_id.uuid- assert p1.old_person_id.team_id == p1.override_person_id.team_id- assert p2.old_person_id == new_old_mapping- assert p1.team != p2.team--[email protected]_db(transaction=True)-def test_person_override_allows_duplicate_override_person_id(team, oldest_event):- """Test duplicate override_person_ids with different old_person_ids are allowed."""- override_person_id = uuid4()- n_person_overrides = 2- created = []-- override_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=override_person_id,- )-- for _ in range(n_person_overrides):- old_person_id = uuid4()- old_mapping = PersonOverrideMapping.objects.create(- team_id=team.id,- uuid=old_person_id,- )-- person_override = PersonOverride.objects.create(- team=team,- old_person_id=old_mapping,- override_person_id=override_mapping,- oldest_event=oldest_event,- version=1,- )- person_override.save()-- created.append(person_override)-- assert all(p.override_person_id == override_mapping for p in created)- assert len({p.old_person_id.uuid for p in created}) == n_person_overrides---def create_connection(alias=DEFAULT_DB_ALIAS):- connection = ConnectionHandler().create_connection(alias)- try:- with connection.cursor() as cursor:- cursor.execute("SET lock_timeout TO '10s'")- try:- yield cursor- finally:- # Make sure that it there was a transaction still open, then roll it- # back.- cursor.execute("ROLLBACK")- cursor.close()-- finally:- connection.close()---def _merge_people(- team,- cursor,- old_person_uuid,- override_person_uuid,- oldest_event,- can_lock_event=None,- done_event=None,-):- """- Merge two people together, using the override_person_id as the canonical- person.-- This function is meant to be run in a separate thread, so that we can test- that the transaction is rolled back if there is a conflict.- This mimics how we expect the code to do person merges, i.e. in a transaction- that deletes the old person, adds old person->override person override and updates- all old person as override person rows to now point to the new override person.- Note that we don't actually handle the merge on the posthog_person table,- but rather simply DELETE the record associated with `old_person_id`. It may- be that we remove the implmentation of deleting merged persons, in which- case we'll need to update the constraint to also include e.g. the- `is_deleted` flag we may add.- """- cursor.execute(- """- DELETE FROM- posthog_person- WHERE- uuid = %(old_person_uuid)s- AND team_id = %(team_id)s;- """,- {"team_id": team.id, "old_person_uuid": old_person_uuid},- )-- # The following INSERTs and UPDATEs will lock posthog_personoverridemapping- # Until the constraints are checked, which happens when the transaction commits.- if can_lock_event is not None:- # Wait until we are allowed to lock.- # Used in concurrency testing.- can_lock_event.wait(10)-- cursor.execute(- """- WITH insert_id AS (- INSERT INTO posthog_personoverridemapping(- team_id,- uuid- )- VALUES (- %(team_id)s,- %(old_person_uuid)s- )- ON CONFLICT("team_id", "uuid") DO NOTHING- RETURNING id- )- SELECT * FROM insert_id- UNION ALL- -- ON CONFLICT nothing is returned, so we get the id here.- -- Fear not, the constraints on personoverride will handle any inconsistencies.- -- This mapping table is really nothing more than a mapping.- SELECT id- FROM posthog_personoverridemapping- WHERE uuid = %(old_person_uuid)s- """,- {"team_id": team.id, "old_person_uuid": old_person_uuid},- )- old_person_id = cursor.fetchone()[0]-- cursor.execute(- """- WITH insert_id AS (- INSERT INTO posthog_personoverridemapping(- team_id,- uuid- )- VALUES (- %(team_id)s,- %(override_person_uuid)s- )- ON CONFLICT("team_id", "uuid") DO NOTHING- RETURNING id- )- SELECT * FROM insert_id- UNION ALL- SELECT id- FROM posthog_personoverridemapping- WHERE uuid = %(override_person_uuid)s- """,- {"team_id": team.id, "override_person_uuid": override_person_uuid},- )- override_person_id = cursor.fetchone()[0]-- cursor.execute(- """- INSERT INTO posthog_personoverride(- team_id,- old_person_id,- override_person_id,- oldest_event,- version- )- VALUES (- %(team_id)s,- %(old_person_id)s,- %(override_person_id)s,- %(oldest_event)s,- 1- );- UPDATE- posthog_personoverride- SET- override_person_id = %(override_person_id)s,- version = version + 1- WHERE override_person_id = %(old_person_id)s- AND team_id = %(team_id)s;- """,- {- "team_id": team.id,- "old_person_id": old_person_id,- "override_person_id": override_person_id,- "oldest_event": oldest_event,- },- )-- if done_event is not None:- done_event.set()---"""-Concurrency tests for person overrides table-Goal: verify that we don't end up in a situation with the same uuid is both-an old person id and an override person id-- there are two cases that we want to check for- - concurrent merges- - concurrent merge and person deletion-In both cases one of the transactions will wait on the lock,-so they can only complete in one order (which is tested below).-Note that to test the race condition scenario we need to:- 1. create multiple concurrent transactions, such that we can verify- constraints are enforced at COMMIT time.- 2. enable transactions for the Django test. This is more so we can see data- from the main Django PostgreSQL connection session in the other- concurrent transactions. Not 100% required but makes things a little- easier to write.-"""--[email protected]_db(transaction=True)-def test_person_override_merge(people, team, oldest_event):- """Verify our merge function work as expected."""- old_person, override_person, _ = people-- with create_connection() as merge_cursor:- merge_cursor.execute("BEGIN")- _merge_people(team, merge_cursor, old_person.uuid, override_person.uuid, oldest_event)- merge_cursor.execute("COMMIT")-- assert [_[0] for _ in PersonOverrideMapping.objects.all().values_list("uuid")] == [- old_person.uuid,- override_person.uuid,- ]-- old_person_id = PersonOverrideMapping.objects.filter(uuid=old_person.uuid).all()[0].id- override_person_id = PersonOverrideMapping.objects.filter(uuid=override_person.uuid).all()[0].id-- assert list(PersonOverride.objects.all().values_list("old_person_id", "override_person_id")) == [- (old_person_id, override_person_id)- ]--[email protected]_db(transaction=True)-def test_person_override_allow_consecutive_merges(people, team, oldest_event):- """Verify our merge function works as expected when called consecutively."""- old_person, override_person, new_override_person = people-- with create_connection() as first_cursor:- first_cursor.execute("BEGIN")- _merge_people(team, first_cursor, old_person.uuid, override_person.uuid, oldest_event)- first_cursor.execute("COMMIT")-- with create_connection() as second_cursor:- second_cursor.execute("BEGIN")- _merge_people(- team,- second_cursor,- override_person.uuid,- new_override_person.uuid,- oldest_event,- )- second_cursor.execute("COMMIT")-- assert [_[0] for _ in PersonOverrideMapping.objects.all().values_list("uuid")] == [- old_person.uuid,- override_person.uuid,- new_override_person.uuid,- ]-- old_person_id = PersonOverrideMapping.objects.filter(uuid=old_person.uuid).all()[0].id- override_person_id = PersonOverrideMapping.objects.filter(uuid=override_person.uuid).all()[0].id- new_override_person_id = PersonOverrideMapping.objects.filter(uuid=new_override_person.uuid).all()[0].id-- mappings = list(PersonOverride.objects.all().values_list("old_person_id", "override_person_id"))-- assert sorted(mappings) == sorted(- [- (override_person_id, new_override_person_id),- (old_person_id, new_override_person_id),- ]- ), f"{mappings=} {old_person_id=}, {override_person_id=}, {new_override_person_id=}"--[email protected]_db(transaction=True)-def test_person_override_disallows_concurrent_merge(people, team, oldest_event):- """Test concurrent merges.-- Running two merges:- A: old_person -> override_person- B: override_person -> new_override_person-- Both merges are run in their own transactions, but for this test the B merge will be- committed first, before A has had a chance to lock the tables.-- Then A should raise an exception, as it now violates an integrity constraint (trying to- use override_person_id that already exists as old_person_id)- """- old_person, override_person, new_override_person = people-- with create_connection() as first_cursor, create_connection() as second_cursor:- # each transaction gets a "copy" of the DB state- first_cursor.execute("BEGIN")- second_cursor.execute("BEGIN")-- # Try to do the merges- # We need to use threads here otherwise we will timeout waiting for a lock, as when we are running in a single thread- # we cannot proceed while waiting.- # Spawning threads allows the main thread to continue and commit the transactions to release the locks.- # This allows us to control the order in which the transactions are committed, so that we can assert their- # behavior consistently.-- can_lock_event = Event()- done_t1_event = Event()- done_t2_event = Event()- t1 = Thread(- target=_merge_people,- args=(- team,- first_cursor,- old_person.uuid,- override_person.uuid,- oldest_event,- ),- kwargs={"can_lock_event": can_lock_event, "done_event": done_t1_event},- )- t2 = Thread(- target=_merge_people,- args=(- team,- second_cursor,- override_person.uuid,- new_override_person.uuid,- oldest_event,- ),- kwargs={"done_event": done_t2_event},- )- t1.start()- t2.start()-- # The main thread can now enforce the order of completion for these transactions.- # We expect the one finishing first to suceed, and the one finishing second to fail- done_t2_event.wait(10)- second_cursor.execute("COMMIT")-- with pytest.raises(IntegrityError):- can_lock_event.set()- done_t1_event.wait(10)- first_cursor.execute("COMMIT")-- assert [_[0] for _ in PersonOverrideMapping.objects.all().values_list("uuid")] == [- override_person.uuid,- new_override_person.uuid,- ]-- override_person_id = PersonOverrideMapping.objects.filter(uuid=override_person.uuid).all()[0].id- new_override_person_id = PersonOverrideMapping.objects.filter(uuid=new_override_person.uuid).all()[0].id-- assert list(PersonOverride.objects.all().values_list("old_person_id", "override_person_id")) == [- (override_person_id, new_override_person_id)- ]--[email protected]_db(transaction=True)-def test_person_override_disallows_concurrent_merge_different_order(people, team, oldest_event):- """Test concurrent merges but in a valid consecutive order.-- Running two merges:- A: old_person -> override_person- B: override_person -> new_override_person-- Both merges are run in their own transactions, and in this test the A merge will be- committed first, before B has had a chance to lock the tables.-- Then both should succeed as these merges are compatible: B will simply update- override_person to new_override_person when it is allowed to run.- This is just the concurrent version of the test scenario from test_person_override_allow_consecutive_merges.- """- old_person, override_person, new_override_person = people-- with create_connection() as first_cursor, create_connection() as second_cursor:- first_cursor.execute("BEGIN")- second_cursor.execute("BEGIN")-- can_lock_event = Event()- done_t1_event = Event()- done_t2_event = Event()- t1 = Thread(- target=_merge_people,- args=(- team,- first_cursor,- old_person.uuid,- override_person.uuid,- oldest_event,- ),- kwargs={"done_event": done_t1_event},- )- t2 = Thread(- target=_merge_people,- args=(- team,- second_cursor,- override_person.uuid,- new_override_person.uuid,- oldest_event,- ),- kwargs={"can_lock_event": can_lock_event, "done_event": done_t2_event},- )- t1.start()- t2.start()-- # The main thread can now enforce the order of completion for these transactions.- done_t1_event.wait(10)- first_cursor.execute("COMMIT")-- can_lock_event.set()- done_t2_event.wait(10)- second_cursor.execute("COMMIT")-- # The main difference from the previous thread is we now expect all 3 UUIDs to be there.- assert [_[0] for _ in PersonOverrideMapping.objects.all().values_list("uuid")] == [- old_person.uuid,- override_person.uuid,- new_override_person.uuid,- ]-- old_person_id = PersonOverrideMapping.objects.filter(uuid=old_person.uuid).all()[0].id- override_person_id = PersonOverrideMapping.objects.filter(uuid=override_person.uuid).all()[0].id- new_override_person_id = PersonOverrideMapping.objects.filter(uuid=new_override_person.uuid).all()[0].id-- # And the merge of old_person_id to be updated to new_override_person_id- assert list(PersonOverride.objects.all().values_list("old_person_id", "override_person_id", "version")) == [- (override_person_id, new_override_person_id, 1),- (old_person_id, new_override_person_id, 2),- ]diff --git a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.pyindex 5d21e9ffb493..c0c4d5b5505d 100644--- a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py+++ b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py@@ -6,7 +6,7 @@ from parameterized import parameterizedfrom posthog.schema import DateRange, HogQLQueryModifiers, WebStatsBreakdown, WebStatsTableQueryfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import Person, Team+from posthog.models import Teamfrom posthog.models.utils import uuid7from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL, WEB_STATS_INSERT_SQL@@ -283,7 +283,6 @@ class TestTimezonePreAggregatedIntegration(WebAnalyticsPreAggregatedTestBase, Flassert not comparison["raw_used"]finally:- Person.objects.filter(team=team).delete()team.delete()def test_timezone_boundary_behavior_explicit(self):@@ -372,7 +371,6 @@ class TestTimezonePreAggregatedIntegration(WebAnalyticsPreAggregatedTestBase, Fl)finally:- Person.objects.filter(team__in=[utc_team, pt_team, jst_team]).delete()utc_team.delete()pt_team.delete()jst_team.delete()@@ -477,5 +475,4 @@ class TestTimezonePreAggregatedIntegration(WebAnalyticsPreAggregatedTestBase, Flassert chrome_raw[1][0] == 2.0finally:- Person.objects.filter(team=india_team).delete()india_team.delete()diff --git a/posthog/person_db_router.py b/posthog/person_db_router.pyindex 4eecd2e3a1f3..9b26d19d8f16 100644--- a/posthog/person_db_router.py+++ b/posthog/person_db_router.py@@ -1,7 +1,59 @@# posthog/person_db_router.py+import threading+import contextlib+from django.conf import settings++class PersonsDBORMBlockedError(RuntimeError):+ """Raised when the Django ORM attempts to touch a persons-DB model while ORM+ access is blocked.++ personhog is the sole source of truth for person/group/cohort data. The test+ suite activates this block (via the personhog fake) so that any code path that+ still reaches for the persons DB through the ORM fails loudly instead of+ silently reading stale/empty rows. Use the personhog helpers+ (``posthog/models/person/util.py``, ``posthog/models/group_type_mapping.py``)+ for production reads and ``posthog/test/persons.py`` for test data.+ """+++# Thread-local toggle. Off by default so production, migrations, management+# commands and the e2e/demo data paths route to the persons DB as before; the+# test fixture flips it on for the duration of each test.+_orm_block = threading.local()+++def block_persons_orm() -> None:+ _orm_block.enabled = True+++def unblock_persons_orm() -> None:+ _orm_block.enabled = False+++def persons_orm_blocked() -> bool:+ return getattr(_orm_block, "enabled", False)+++def allow_persons_orm():+ """Temporarily allow direct persons-DB ORM access while the block is active.++ For maintenance paths that legitimately read/write the persons DB even when a+ test's personhog fake is active — management commands and the demo-data+ generator, which the router is designed to let "route to the persons DB as+ before". Saves and restores the previous block state so nesting is safe.+ """+ previously_blocked = persons_orm_blocked()+ _orm_block.enabled = False+ try:+ yield+ finally:+ _orm_block.enabled = previously_blocked++# Set of models (lowercase) that should live in the persons_db# Add other models from the plan here as needed.PERSONS_DB_MODELS = {@@ -54,6 +106,7 @@ class PersonDBRouter:Attempts to read person models go to persons_db (writer in tests, reader in production)."""if self.is_persons_model(model._meta.app_label, model._meta.model_name):+ self._raise_if_blocked(model)return PERSONS_DB_FOR_READreturn None # Allow default db selection@@ -62,9 +115,27 @@ class PersonDBRouter:Attempts to write person models go to persons_db_writer."""if self.is_persons_model(model._meta.app_label, model._meta.model_name):+ # Django also calls db_for_write to compute _state.db when an FK *instance*+ # is assigned during Model.__init__ (e.g. ``GroupTypeMapping(team=team)``).+ # In that case hints["instance"] is the *related* object — a different model+ # — and nothing is being written, so it must not trip the block. Real writes+ # pass the model's own instance (save/create) or no instance (queryset writes).+ instance = hints.get("instance")+ if instance is None or isinstance(instance, model):+ self._raise_if_blocked(model)return PERSONS_DB_FOR_WRITEreturn None # Allow default db selection+ @staticmethod+ def _raise_if_blocked(model) -> None:+ if persons_orm_blocked():+ raise PersonsDBORMBlockedError(+ f"Direct ORM access to persons-DB model {model._meta.label} is blocked. "+ f"personhog is the sole source of truth — read via the helpers in "+ f"posthog/models/person/util.py or posthog/models/group_type_mapping.py, "+ f"and create test data via posthog/test/persons.py."+ )+def allow_relation(self, obj1, obj2, **hints):"""Allow relations if a model in PERSONS_DB_MODELS is involved.diff --git a/posthog/personhog_client/README.md b/posthog/personhog_client/README.mdindex 5f783d47dac6..c114aac4ae89 100644--- a/posthog/personhog_client/README.md+++ b/posthog/personhog_client/README.md@@ -8,9 +8,10 @@ Personhog is an internal service that owns the source of truth for person-relate**All Django code must use this client (or the routed helpers built on it) instead of querying person/group tables via the ORM or raw SQL.**Direct ORM queries like `Person.objects.filter(...)` or `PersonDistinctId.objects.filter(...)` are not allowed for new code.-Routed helpers that handle the gate check, gRPC call, ORM fallback, and metrics already exist in+Routed helpers that handle the gRPC call and metrics already exist in`posthog/models/person/util.py` and `posthog/models/group_type_mapping.py` — use these when one fits your use case.When no existing helper covers your needs, follow the `_personhog_routed()` pattern in `posthog/models/person/util.py`.+personhog is the sole read path — there is no ORM fallback.## Database tables@@ -36,19 +37,6 @@ Do not query them directly — use the routed helpers or client RPCs.`get_personhog_client()` returns a thread-safe singleton `PersonHogClient` instance, configured from Django settings.Returns `None` when `PERSONHOG_ADDR` is not set (e.g. in local dev without personhog running).-## Rollout gate--The `use_personhog()` function in `gate.py` controls whether gRPC or ORM is used, based on three settings:--| Setting | Description |-| ------------------------------ | --------------------------------------------------------- |-| `PERSONHOG_ENABLED` | Master toggle — must be `True` for gRPC to be used |-| `PERSONHOG_ADDR` | gRPC address (e.g. `localhost:50051`) — must be non-empty |-| `PERSONHOG_ROLLOUT_PERCENTAGE` | `0`–`100` — percentage of calls routed to gRPC |--The `PersonHogGateMiddleware` (`middleware.py`) pins the gate decision for the lifetime of an HTTP request,-ensuring all person/group reads within a single request consistently hit the same backend.-## Proto converters`converters.py` provides functions to convert gRPC proto messages into Django model instances or dicts:@@ -111,17 +99,14 @@ def test_something(self):fake.assert_called("get_person_by_uuid", times=1)```-The `fake_personhog_client()` context manager also forces the gate ON by default.-Pass `gate_enabled=False` to simulate the gate being off.-## ObservabilityThe client emits Prometheus metrics at multiple layers:**Routing metrics** (`metrics.py`):-- `personhog_routing_total` — tracks which source (personhog vs django_orm) was used per operation-- `personhog_routing_errors_total` — errors that triggered ORM fallback+- `personhog_routing_total` — counts personhog reads per operation+- `personhog_routing_errors_total` — personhog read errors per operation- `personhog_team_mismatch_total` — persons dropped because personhog returned a mismatched team_id**gRPC request metrics** (`interceptor.py`):@@ -139,8 +124,6 @@ The client emits Prometheus metrics at multiple layers:## Directory layout- `client.py` — `PersonHogClient` with typed methods for each RPC, plus `get_personhog_client()` singleton-- `gate.py` — `use_personhog()` rollout gate-- `middleware.py` — `PersonHogGateMiddleware` that pins the gate decision per HTTP request- `converters.py` — proto-to-Django conversion functions- `fake_client.py` — `FakePersonHogClient` for tests- `interceptor.py` — gRPC interceptors for client name headers and request metricsdiff --git a/posthog/personhog_client/client.py b/posthog/personhog_client/client.pyindex c88a8ce2229c..13049469f3b5 100644--- a/posthog/personhog_client/client.py+++ b/posthog/personhog_client/client.py@@ -2,7 +2,8 @@ from __future__ import annotationsimport timeimport threading-from typing import Optional+from collections.abc import Callable+from typing import Optional, TypeVarfrom django.conf import settings@@ -373,6 +374,8 @@ class PersonHogClient:return self._stub.DeleteHashKeyOverridesByTeams(request, timeout=timeout or self._timeout)+_T = TypeVar("_T")+_client: Optional[PersonHogClient] = None_lock = threading.Lock()@@ -408,3 +411,52 @@ def get_personhog_client() -> Optional[PersonHogClient]:logger.info("personhog_client_initialized", addr=addr, timeout_ms=timeout_ms)return _client+++def require_personhog_client() -> PersonHogClient:+ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")+ return client+++def personhog_call(+ operation: str,+ fn: Callable[[], _T],+ *,+ caller_tag: str | None = None,+ reraise_as: type[Exception] | None = None,+) -> _T:+ """Execute a personhog operation with metrics and optional error wrapping.++ ``caller_tag`` sets the personhog caller-tag context for observability.+ ``reraise_as`` wraps the exception in the given type before re-raising.+ Error metrics and a warning log are always recorded on failure regardless+ of ``reraise_as``.+ """+ from posthog.personhog_client.caller_tag import personhog_caller_tag+ from posthog.personhog_client.metrics import (+ PERSONHOG_ROUTING_ERRORS_TOTAL,+ PERSONHOG_ROUTING_TOTAL,+ get_client_name,+ )++ tag_ctx = personhog_caller_tag(caller_tag) if caller_tag else None++ try:+ if tag_ctx:+ with tag_ctx:+ result = fn()+ else:+ result = fn()+ except Exception as exc:+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(+ operation=operation, source="personhog", error_type="grpc_error", client_name=get_client_name()+ ).inc()+ logger.warning("personhog_%s_failure", operation, exc_info=True)+ if reraise_as is not None:+ raise reraise_as(f"personhog {operation} failed") from exc+ raise++ PERSONHOG_ROUTING_TOTAL.labels(operation=operation, source="personhog", client_name=get_client_name()).inc()+ return resultdiff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 70b936c9830d..00036d88f40c 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -12,8 +12,7 @@ Usage in tests::assert len(result) == 1The fake uses real proto message classes so that converters / serialization-boundaries are exercised end-to-end. The gate is forced ON by default-(override with ``gate_enabled=False``).+boundaries are exercised end-to-end."""from __future__ import annotations@@ -92,6 +91,7 @@ class FakePersonHogClient:is_user_id: bool | None = None,distinct_ids: list[str] | None = None,distinct_id_versions: dict[str, int] | None = None,+ last_seen_at: int = 0,) -> person_pb2.Person:person = person_pb2.Person(id=person_id,@@ -101,6 +101,7 @@ class FakePersonHogClient:created_at=created_at,version=version,is_identified=is_identified,+ last_seen_at=last_seen_at,)if is_user_id is not None:person.is_user_id = is_user_id@@ -713,12 +714,11 @@ class FakePersonHogClient:@contextmanager-def fake_personhog_client(*, gate_enabled: bool = True):- """Context manager that patches the personhog client singleton and gate.+def fake_personhog_client():+ """Context manager that patches the personhog client singleton.- Yields a ``FakePersonHogClient`` that is pre-seeded as empty.- The gate (``use_personhog()``) returns ``gate_enabled`` for- every call — no randomness.+ Yields a ``FakePersonHogClient`` that is pre-seeded as empty. personhog is+ the sole read path, so patching ``get_personhog_client`` is all that's needed.Example::@@ -727,8 +727,41 @@ def fake_personhog_client(*, gate_enabled: bool = True):result = some_function_that_uses_personhog(1)"""fake = FakePersonHogClient()- with (- patch("posthog.personhog_client.client.get_personhog_client", return_value=fake),- patch("posthog.personhog_client.gate.use_personhog", return_value=gate_enabled),- ):+ with patch("posthog.personhog_client.client.get_personhog_client", return_value=fake):yield fake+++# ── Global singleton for conftest integration ───────────────────────++_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+++@contextmanager+def activate_personhog_fake():+ """Activate a FakePersonHogClient for the duration of a test.++ Patches get_personhog_client so all reads route through the fake and blocks+ persons-DB ORM access so a stray Person.objects.* call fails loudly. Test+ helpers in posthog.test.persons seed the fake explicitly when creating data.+ """+ from posthog.person_db_router import block_persons_orm, unblock_persons_orm # noqa: PLC0415++ fake = FakePersonHogClient()+ set_active_fake(fake)+ block_persons_orm()+ with patch("posthog.personhog_client.client.get_personhog_client", return_value=fake):+ try:+ yield fake+ finally:+ unblock_persons_orm()+ set_active_fake(None)diff --git a/posthog/personhog_client/gate.py b/posthog/personhog_client/gate.pydeleted file mode 100644index c204ce07f2ee..000000000000--- a/posthog/personhog_client/gate.py+++ /dev/null@@ -1,57 +0,0 @@-from __future__ import annotations--import random-import threading--from django.conf import settings--_request_local = threading.local()---def use_personhog() -> bool:- """Return whether to use personhog for the current operation.-- When called inside a pinned scope (e.g. HTTP request via middleware),- the first call rolls the dice and all subsequent calls on the same- thread reuse that decision — guaranteeing consistency within a request.-- Outside a pinned scope the decision is re-rolled every call (legacy behavior).- """- cached = getattr(_request_local, "personhog_decision", None)- if cached is not None:- return cached-- decision = _decide_personhog()-- if getattr(_request_local, "personhog_pinned", False):- _request_local.personhog_decision = decision-- return decision---def _decide_personhog() -> bool:- if not getattr(settings, "PERSONHOG_ENABLED", False):- return False-- if not getattr(settings, "PERSONHOG_ADDR", ""):- return False-- rollout_pct = getattr(settings, "PERSONHOG_ROLLOUT_PERCENTAGE", 0)-- if rollout_pct >= 100:- return True- if rollout_pct <= 0:- return False-- return random.randint(1, 100) <= rollout_pct---def pin_personhog_decision() -> None:- """Start caching the gate decision on this thread."""- _request_local.personhog_pinned = True---def unpin_personhog_decision() -> None:- """Clear the cached decision and stop caching."""- _request_local.personhog_decision = None- _request_local.personhog_pinned = Falsediff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.pyindex 530ded625aae..d4ad878db792 100644--- a/posthog/personhog_client/interceptor.py+++ b/posthog/personhog_client/interceptor.py@@ -154,6 +154,7 @@ _RETRYABLE_CODES = frozenset(grpc.StatusCode.UNAVAILABLE,grpc.StatusCode.DEADLINE_EXCEEDED,grpc.StatusCode.ABORTED,+ grpc.StatusCode.UNKNOWN,})@@ -161,10 +162,11 @@ _RETRYABLE_CODES = frozenset(class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):"""Retries transient gRPC errors with jittered backoff.- Covers three failure modes:+ Covers four failure modes:- UNAVAILABLE: client-to-router connection failure- ABORTED: HTTP/2 stream reset during router deploys- DEADLINE_EXCEEDED: transient timeout (event loop saturation, brief backend slowness)+ - UNKNOWN: catch-all for transient failures that don't map to a specific codeSits outside MetricsInterceptor so each attempt gets its own per-call metrics."""diff --git a/posthog/personhog_client/metrics.py b/posthog/personhog_client/metrics.pyindex 016a3f34d84e..6f6196cf1d8f 100644--- a/posthog/personhog_client/metrics.py+++ b/posthog/personhog_client/metrics.py@@ -17,7 +17,7 @@ PERSONHOG_ROUTING_TOTAL = Counter(PERSONHOG_ROUTING_ERRORS_TOTAL = Counter("personhog_routing_errors_total",- "Errors encountered during personhog routing (triggers fallback to ORM)",+ "Errors encountered during personhog routing",labelnames=["operation", "source", "error_type", "client_name"],)diff --git a/posthog/personhog_client/middleware.py b/posthog/personhog_client/middleware.pydeleted file mode 100644index 40205327f979..000000000000--- a/posthog/personhog_client/middleware.py+++ /dev/null@@ -1,22 +0,0 @@-from django.http import HttpRequest, HttpResponse--from posthog.personhog_client.gate import pin_personhog_decision, unpin_personhog_decision---class PersonHogGateMiddleware:- """Pin the personhog gate decision for the lifetime of an HTTP request.-- This ensures that all personhog-routed calls within a single request- consistently use the same backend (either all gRPC or all ORM),- avoiding mixed-source reads during partial rollout.- """-- def __init__(self, get_response):- self.get_response = get_response-- def __call__(self, request: HttpRequest) -> HttpResponse:- pin_personhog_decision()- try:- return self.get_response(request)- finally:- unpin_personhog_decision()diff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.pyindex 4bc12a7951a7..5c7b05e0aa04 100644--- a/posthog/personhog_client/test_fake_client.py+++ b/posthog/personhog_client/test_fake_client.py@@ -453,14 +453,3 @@ class TestFakePersonhogClientContextManager:client = get_personhog_client()assert client is fake-- def test_patches_gate(self):- with fake_personhog_client(gate_enabled=True):- from posthog.personhog_client.gate import use_personhog-- assert use_personhog() is True-- with fake_personhog_client(gate_enabled=False):- from posthog.personhog_client.gate import use_personhog-- assert use_personhog() is Falsediff --git a/posthog/personhog_client/test_gate.py b/posthog/personhog_client/test_gate.pydeleted file mode 100644index 83ca1740fa33..000000000000--- a/posthog/personhog_client/test_gate.py+++ /dev/null@@ -1,117 +0,0 @@-from unittest.mock import patch--from django.http import HttpResponse-from django.test import RequestFactory, SimpleTestCase, override_settings--from posthog.personhog_client.gate import pin_personhog_decision, unpin_personhog_decision, use_personhog-from posthog.personhog_client.middleware import PersonHogGateMiddleware--ENABLED_SETTINGS = {- "PERSONHOG_ENABLED": True,- "PERSONHOG_ADDR": "localhost:50051",- "PERSONHOG_ROLLOUT_PERCENTAGE": 50,-}---class TestPersonHogGatePinning(SimpleTestCase):- def setUp(self):- unpin_personhog_decision()-- def tearDown(self):- unpin_personhog_decision()-- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", return_value=True)- def test_unpinned_does_not_cache(self, mock_decide):- use_personhog()- use_personhog()- use_personhog()- assert mock_decide.call_count == 3-- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", return_value=True)- def test_pinned_caches_after_first_call(self, mock_decide):- pin_personhog_decision()- assert use_personhog() is True- assert use_personhog() is True- assert use_personhog() is True- assert mock_decide.call_count == 1-- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", side_effect=[True, False])- def test_unpin_clears_cached_decision(self, mock_decide):- pin_personhog_decision()- assert use_personhog() is True-- unpin_personhog_decision()- pin_personhog_decision()- assert use_personhog() is False-- @override_settings(PERSONHOG_ENABLED=False)- def test_disabled_always_returns_false(self):- pin_personhog_decision()- assert use_personhog() is False-- @override_settings(**{**ENABLED_SETTINGS, "PERSONHOG_ROLLOUT_PERCENTAGE": 100})- def test_full_rollout_always_returns_true(self):- pin_personhog_decision()- assert use_personhog() is True-- @override_settings(**{**ENABLED_SETTINGS, "PERSONHOG_ROLLOUT_PERCENTAGE": 0})- def test_zero_rollout_always_returns_false(self):- pin_personhog_decision()- assert use_personhog() is False---class TestPersonHogGateMiddleware(SimpleTestCase):- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", return_value=True)- def test_middleware_pins_decision_for_request(self, mock_decide):- """All use_personhog() calls within a request return the same value."""- captured = []-- def view(request):- captured.extend([use_personhog() for _ in range(5)])- return HttpResponse("ok")-- middleware = PersonHogGateMiddleware(view)- middleware(RequestFactory().get("/"))-- assert captured == [True, True, True, True, True]- assert mock_decide.call_count == 1-- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", side_effect=[True, False])- def test_middleware_unpins_between_requests(self, mock_decide):- """Each request gets a fresh decision."""- results = []-- def view(request):- results.append(use_personhog())- return HttpResponse("ok")-- middleware = PersonHogGateMiddleware(view)- middleware(RequestFactory().get("/first"))- middleware(RequestFactory().get("/second"))-- assert results == [True, False]- assert mock_decide.call_count == 2-- @override_settings(**ENABLED_SETTINGS)- @patch("posthog.personhog_client.gate._decide_personhog", return_value=True)- def test_middleware_unpins_on_exception(self, mock_decide):- """Decision is cleared even if the view raises."""-- def exploding_view(request):- use_personhog()- raise RuntimeError("boom")-- middleware = PersonHogGateMiddleware(exploding_view)- with self.assertRaises(RuntimeError):- middleware(RequestFactory().get("/"))-- # After the failed request, gate should be unpinned- assert not hasattr(use_personhog, "personhog_pinned") or True- # Calling again outside middleware should re-roll (call _decide again)- use_personhog()- assert mock_decide.call_count == 2diff --git a/posthog/personhog_client/test_helpers.py b/posthog/personhog_client/test_helpers.pyindex 7c9043f8c6a4..e74947ace14a 100644--- a/posthog/personhog_client/test_helpers.py+++ b/posthog/personhog_client/test_helpers.py@@ -25,7 +25,7 @@ class PersonhogTestMixin:def setUp(self) -> None:super().setUp() # type: ignore[misc]- from posthog.test.personhog_fake import get_active_fake+ from posthog.personhog_client.fake_client import get_active_fakeself._fake_client = get_active_fake()diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.pyindex b8d9577cdad2..b843dc38799d 100644--- a/posthog/personhog_client/test_retry_interceptor.py+++ b/posthog/personhog_client/test_retry_interceptor.py@@ -66,6 +66,7 @@ class TestRetryInterceptorBehavior:("unavailable", grpc.StatusCode.UNAVAILABLE),("deadline_exceeded", grpc.StatusCode.DEADLINE_EXCEEDED),("aborted", grpc.StatusCode.ABORTED),+ ("unknown", grpc.StatusCode.UNKNOWN),])@patch("posthog.personhog_client.interceptor.time.sleep")@@ -89,7 +90,6 @@ class TestRetryInterceptorBehavior:("failed_precondition", grpc.StatusCode.FAILED_PRECONDITION),("internal", grpc.StatusCode.INTERNAL),("resource_exhausted", grpc.StatusCode.RESOURCE_EXHAUSTED),- ("unknown", grpc.StatusCode.UNKNOWN),])def test_does_not_retry_non_retryable_error(self, _name: str, status_code: grpc.StatusCode):diff --git a/posthog/queries/actor_base_query.py b/posthog/queries/actor_base_query.pyindex 94c0185e210e..fea03cbd8230 100644--- a/posthog/queries/actor_base_query.py+++ b/posthog/queries/actor_base_query.py@@ -2,8 +2,7 @@ import uuidfrom datetime import datetimefrom typing import Any, Literal, Optional, TypedDict, Union-from django.db.models import OuterRef, Subquery-from django.db.models.query import Prefetch, QuerySet+from django.db.models.query import QuerySetimport structlog@@ -11,13 +10,12 @@ from posthog.schema import ActorsQueryfrom posthog.hogql_queries.actor_strategies import PersonStrategyfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator-from posthog.models import PersonDistinctId, Team+from posthog.models import Teamfrom posthog.models.group import Groupfrom posthog.models.person import Person-from posthog.models.person.person import READ_DB_FOR_PERSONSfrom posthog.models.person.util import _batched_get_distinct_ids_for_persons, _batched_get_persons_by_uuids+from posthog.personhog_client.client import personhog_callfrom posthog.personhog_client.converters import proto_person_to_model-from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_namelogger = structlog.get_logger(__name__)@@ -96,48 +94,13 @@ def get_people(people_ids: list[Any],value_per_actor_id: Optional[dict[str, float]] = None,distinct_id_limit: int | None = 1000,-) -> tuple[Union[QuerySet[Person], list[Person]], list[SerializedPerson]]:+) -> tuple[list[Person], list[SerializedPerson]]:"""Get people from raw SQL results in data model and dict formats"""- from posthog.personhog_client.gate import use_personhog-- if use_personhog():- try:- persons = _fetch_people_via_personhog(team.pk, people_ids, distinct_id_limit)- PERSONHOG_ROUTING_TOTAL.labels(- operation="get_people", source="personhog", client_name=get_client_name()- ).inc()- return persons, serialize_people(team, persons, value_per_actor_id)- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="get_people", source="personhog", error_type="grpc_error", client_name=get_client_name()- ).inc()- logger.warning("personhog_get_people_failure", team_id=team.pk, exc_info=True)-- distinct_id_subquery = Subquery(- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team.pk, person_id=OuterRef("person_id"))- .values_list("id", flat=True)[:distinct_id_limit]+ persons = personhog_call(+ "get_people",+ lambda: _fetch_people_via_personhog(team.pk, people_ids, distinct_id_limit),)- persons_qs: QuerySet[Person] = (- Person.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team.pk, uuid__in=people_ids)- .prefetch_related(- Prefetch(- "persondistinctid_set",- to_attr="distinct_ids_cache",- # nosemgrep: no-direct-persons-db-orm- queryset=PersonDistinctId.objects.db_manager(- READ_DB_FOR_PERSONS- ).filter( # nosemgrep: no-direct-persons-db-orm- id__in=distinct_id_subquery- ), # nosemgrep: no-direct-persons-db-orm- )- )- .order_by("-created_at", "uuid")- .only("id", "is_identified", "created_at", "properties", "uuid", "team_id")- )- PERSONHOG_ROUTING_TOTAL.labels(operation="get_people", source="django_orm", client_name=get_client_name()).inc()- return persons_qs, serialize_people(team, persons_qs, value_per_actor_id)+ return persons, serialize_people(team, persons, value_per_actor_id)# A faster get_people if you don't need the Person objectsdiff --git a/posthog/queries/test/test_actor_base_query_personhog_routing.py b/posthog/queries/test/test_actor_base_query_personhog_routing.pydeleted file mode 100644index 41117333259b..000000000000--- a/posthog/queries/test/test_actor_base_query_personhog_routing.py+++ /dev/null@@ -1,85 +0,0 @@-from unittest.mock import MagicMock, patch--from django.test import SimpleTestCase--from parameterized import parameterized--from posthog.queries.actor_base_query import get_people---class TestGetPeopleRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success",- True,- None,- "personhog",- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- "django_orm",- ),- (- "gate_off_uses_orm_directly",- False,- None,- "django_orm",- ),- ]- )- @patch("posthog.queries.actor_base_query._fetch_people_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.queries.actor_base_query.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.queries.actor_base_query.PERSONHOG_ROUTING_ERRORS_TOTAL")- @patch("posthog.queries.actor_base_query.serialize_people")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- expected_source,- mock_serialize,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- ):- mock_use_personhog.return_value = gate_on-- personhog_persons = [MagicMock(), MagicMock()]- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- else:- mock_fetch_personhog.return_value = personhog_persons-- mock_serialize.return_value = [{"type": "person", "id": "test"}]-- team = MagicMock()- team.pk = 1- people_ids = ["uuid-1", "uuid-2"]-- if gate_on and grpc_exception is None:- result_persons, _ = get_people(team, people_ids)- assert result_persons == personhog_persons- else:- with (- patch("posthog.queries.actor_base_query.Person.objects") as mock_person_objects,- patch("posthog.queries.actor_base_query.PersonDistinctId.objects"),- patch("posthog.queries.actor_base_query.Prefetch"),- patch("posthog.queries.actor_base_query.Subquery"),- ):- mock_qs = MagicMock()- mock_person_objects.db_manager.return_value.filter.return_value.prefetch_related.return_value.order_by.return_value.only.return_value = mock_qs-- result_persons, _ = get_people(team, people_ids)- assert result_persons == mock_qs-- mock_routing_counter.labels.assert_called_with(- operation="get_people", source=expected_source, client_name="posthog-django"- )-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()diff --git a/posthog/queries/test/test_actors_base_query.py b/posthog/queries/test/test_actors_base_query.pyindex fc6acff31b3d..6e7a3cdabc53 100644--- a/posthog/queries/test/test_actors_base_query.py+++ b/posthog/queries/test/test_actors_base_query.py@@ -8,7 +8,7 @@ from posthog.test.base import (snapshot_postgres_queries,)-from posthog.models import Group, Person+from posthog.models.person.util import get_persons_by_uuidsfrom posthog.queries.actor_base_query import (get_groups,get_people,@@ -32,7 +32,7 @@ class TestActorsBaseQuery(ClickhouseTestMixin, APIBaseTest):)flush_persons_and_events()- persons = Person.objects.filter(uuid=person.uuid)+ persons = get_persons_by_uuids(self.team.pk, [str(person.uuid)])result = serialize_people(self.team, persons)assert len(result) == 1@@ -145,7 +145,7 @@ class TestActorsBaseQuery(ClickhouseTestMixin, APIBaseTest):version=1,)- groups = Group.objects.filter(group_key__in=["company_a", "company_b"])+ groups, _ = get_groups(self.team.pk, 1, ["company_a", "company_b"])value_per_actor_id = {"company_a": 500.0,"company_b": 300.0,diff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.pyindex d4b2fa068383..b87621009e53 100644--- a/posthog/session_recordings/models/session_recording.py+++ b/posthog/session_recordings/models/session_recording.py@@ -6,15 +6,11 @@ from django.db import modelsimport structlogfrom posthog.models.person.missing_person import MissingPerson-from posthog.models.person.person import READ_DB_FOR_PERSONS, Person+from posthog.models.person.person import Personfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTModel-from posthog.personhog_client.metrics import (- PERSONHOG_ROUTING_ERRORS_TOTAL,- PERSONHOG_ROUTING_TOTAL,- PERSONHOG_TEAM_MISMATCH_TOTAL,- get_client_name,-)+from posthog.personhog_client.client import personhog_call+from posthog.personhog_client.metrics import PERSONHOG_TEAM_MISMATCH_TOTAL, get_client_namefrom posthog.session_recordings.models.metadata import RecordingMatchingEvents, RecordingMetadatafrom posthog.session_recordings.models.session_recording_event import SessionRecordingViewed@@ -169,34 +165,16 @@ class SessionRecording(UUIDTModel):if self._person:return- from posthog.personhog_client.gate import use_personhog-- if use_personhog() and self.distinct_id:- try:- person = _fetch_person_by_distinct_id_via_personhog(self.team.pk, self.distinct_id)- if person is not None:- self.person = person- PERSONHOG_ROUTING_TOTAL.labels(- operation="load_person", source="personhog", client_name=get_client_name()- ).inc()- return- except Exception:- PERSONHOG_ROUTING_ERRORS_TOTAL.labels(- operation="load_person", source="personhog", error_type="grpc_error", client_name=get_client_name()- ).inc()- logger.warning("personhog_load_person_failure", team_id=self.team.pk, exc_info=True)+ distinct_id = self.distinct_id+ if not distinct_id:+ return- try:- self.person = Person.objects.db_manager(READ_DB_FOR_PERSONS).get( # nosemgrep: no-direct-persons-db-orm- persondistinctid__distinct_id=self.distinct_id,- persondistinctid__team_id=self.team.pk,- team=self.team,- )- except Person.DoesNotExist:- pass- PERSONHOG_ROUTING_TOTAL.labels(- operation="load_person", source="django_orm", client_name=get_client_name()- ).inc()+ def _fn() -> None:+ person = _fetch_person_by_distinct_id_via_personhog(self.team.pk, distinct_id)+ if person is not None:+ self.person = person++ personhog_call("load_person", _fn)def check_viewed_for_user(self, user: Any, save_viewed=False) -> None:if not save_viewed:diff --git a/posthog/session_recordings/test/test_session_recording_personhog.py b/posthog/session_recordings/test/test_session_recording_personhog.pydeleted file mode 100644index cfda9c2a3d44..000000000000--- a/posthog/session_recordings/test/test_session_recording_personhog.py+++ /dev/null@@ -1,140 +0,0 @@-"""Tests for session recording person loading via the personhog path.--TestLoadPersonRouting — Pattern A routing test (gate/fallback logic).-TestLoadPersonIntegration — integration test for person loading.-"""--from posthog.test.base import BaseTest-from unittest.mock import ANY, MagicMock, PropertyMock, patch--from django.test import SimpleTestCase--from parameterized import parameterized--from posthog.models.person import Person-from posthog.session_recordings.models.session_recording import SessionRecording-from posthog.test.persons import create_person---class TestLoadPersonRouting(SimpleTestCase):- @parameterized.expand(- [- (- "personhog_success_person_found",- True,- None,- "personhog",- True,- ),- (- "personhog_success_person_not_found",- True,- None,- "personhog",- False,- ),- (- "personhog_failure_falls_back_to_orm",- True,- RuntimeError("grpc timeout"),- "django_orm",- True,- ),- (- "gate_off_uses_orm_directly",- False,- None,- "django_orm",- True,- ),- ]- )- @patch("posthog.session_recordings.models.session_recording._fetch_person_by_distinct_id_via_personhog")- @patch("posthog.personhog_client.gate.use_personhog")- @patch("posthog.session_recordings.models.session_recording.PERSONHOG_ROUTING_TOTAL")- @patch("posthog.session_recordings.models.session_recording.PERSONHOG_ROUTING_ERRORS_TOTAL")- @patch("posthog.session_recordings.models.session_recording.Person.objects")- def test_routing(- self,- _name,- gate_on,- grpc_exception,- expected_source,- person_found,- mock_person_objects,- mock_errors_counter,- mock_routing_counter,- mock_use_personhog,- mock_fetch_personhog,- ):- mock_use_personhog.return_value = gate_on-- mock_person = MagicMock()- if grpc_exception is not None:- mock_fetch_personhog.side_effect = grpc_exception- elif person_found:- mock_fetch_personhog.return_value = mock_person- else:- mock_fetch_personhog.return_value = None-- mock_orm_person = MagicMock()- if person_found:- mock_person_objects.db_manager.return_value.get.return_value = mock_orm_person- else:- mock_person_objects.db_manager.return_value.get.side_effect = Person.DoesNotExist-- recording = SessionRecording()- recording.distinct_id = "test-distinct-id"- recording.team_id = 1- # Use a real-looking mock for the team FK — bypass Django's descriptor.- mock_team = MagicMock()- mock_team.pk = 1-- # Patch `team` at the class level via patch.object so the original FK- # descriptor is restored afterwards. A bare `type(recording).team = ...`- # leaks a setter-less property into every later SessionRecording test in- # the same process (only visible when those tests run on the same shard).- 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=ANY)-- if gate_on and grpc_exception is None:- mock_person_objects.db_manager.assert_not_called()- if person_found:- assert recording._person == mock_person- else:- assert recording._person is None- else:- if person_found:- assert recording._person == mock_orm_person-- if grpc_exception is not None and gate_on:- mock_errors_counter.labels.assert_called_once()---class TestLoadPersonIntegration(BaseTest):- def test_person_found(self):- 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()-- assert recording._person is not None- assert str(recording._person.uuid) == str(person.uuid)- assert recording._person.properties == {"email": "[email protected]"}-- 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-- def test_cross_team_isolation(self):- other_team = self.organization.teams.create(name="Other Team")- 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()-- assert recording._person is Nonediff --git a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.pyindex 56bef14eb6a4..f9de469975e2 100644--- a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py+++ b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py@@ -6,7 +6,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.client import sync_execute-from posthog.models import Person, PersonalAPIKey, SessionRecording+from posthog.models import PersonalAPIKey, SessionRecordingfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary@@ -23,7 +23,6 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMasync_execute("TRUNCATE TABLE sharded_session_replay_events")SessionRecordingViewed.objects.all().delete()SessionRecording.objects.all().delete()- Person.objects.filter(team_id__isnull=False).delete()def produce_replay_summary(self,diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex e0023bbeb1b0..dc1c9df5b1e1 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -511,37 +511,6 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)response = self.client.get(f"/api/projects/{self.team.id}/session_recordings")response_data = response.json()- assert [r["person"]["id"] for r in response_data["results"]] == [p.pk, p.pk]- # each recording must carry the distinct_id that produced it- results_by_session = {r["id"]: r for r in response_data["results"]}- assert results_by_session["1"]["person"]["distinct_ids"] == ["d1"]- assert results_by_session["2"]["person"]["distinct_ids"] == ["d2"]-- def test_session_recording_for_user_with_multiple_distinct_ids_via_personhog(self) -> None:- from posthog.personhog_client.fake_client import fake_personhog_client-- base_time = (now() - timedelta(days=1)).replace(microsecond=0)- p = create_person(- team=self.team,- distinct_ids=["d1", "d2"],- properties={"$some_prop": "something", "email": "[email protected]"},- )- self.produce_replay_summary("d1", "1", base_time)- self.produce_replay_summary("d2", "2", base_time + relativedelta(seconds=30))-- with fake_personhog_client() as fake:- fake.add_person(- team_id=self.team.pk,- person_id=p.pk,- uuid=str(p.uuid),- properties={"$some_prop": "something", "email": "[email protected]"},- distinct_ids=["d1", "d2"],- created_at=int(p.created_at.timestamp() * 1000) if p.created_at else 0,- )-- response = self.client.get(f"/api/projects/{self.team.id}/session_recordings")- response_data = response.json()-assert [r["person"]["id"] for r in response_data["results"]] == [p.pk, p.pk]# each recording must carry the distinct_id that produced it, not the# last one processed — this was a bug where mutating a shared Person@@ -1027,6 +996,37 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)},)+ def test_load_person_found(self):+ 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()++ assert recording._person is not None+ assert str(recording._person.uuid) == str(person.uuid)+ assert recording._person.properties == {"email": "[email protected]"}++ def test_load_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++ def test_load_person_no_distinct_id_skips_load(self):+ recording = SessionRecording(team=self.team, session_id="test_session", distinct_id=None)+ recording.load_person()++ assert recording._person is None++ def test_load_person_cross_team_isolation(self):+ other_team = self.organization.teams.create(name="Other Team")+ 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()++ assert recording._person is None+def test_session_recording_doesnt_exist(self):response = self.client.get(f"/api/projects/{self.team.id}/session_recordings/non_existent_id")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)diff --git a/posthog/session_recordings/test/test_session_recordings_sharing.py b/posthog/session_recordings/test/test_session_recordings_sharing.pyindex cdce75930817..5c1f48873bd3 100644--- a/posthog/session_recordings/test/test_session_recordings_sharing.py+++ b/posthog/session_recordings/test/test_session_recordings_sharing.py@@ -11,7 +11,7 @@ from rest_framework import statusfrom posthog.api.test.test_team import create_teamfrom posthog.clickhouse.client import sync_executefrom posthog.constants import AvailableFeature-from posthog.models import Person, SessionRecording+from posthog.models import SessionRecordingfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.utils import uuid7@@ -33,7 +33,6 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchisync_execute("TRUNCATE TABLE sharded_session_replay_events")SessionRecordingViewed.objects.all().delete()SessionRecording.objects.all().delete()- Person.objects.filter(team_id__isnull=False).delete()with freeze_time("2023-01-01T12:00:00Z"):self.session_id = str(uuid7())diff --git a/posthog/settings/personhog.py b/posthog/settings/personhog.pyindex 16b1076611e6..579b217ca6dd 100644--- a/posthog/settings/personhog.py+++ b/posthog/settings/personhog.py@@ -1,9 +1,7 @@from posthog.settings.utils import get_from_env, str_to_boolPERSONHOG_ADDR = get_from_env("PERSONHOG_ADDR", "")-PERSONHOG_ENABLED = get_from_env("PERSONHOG_ENABLED", False, type_cast=str_to_bool)PERSONHOG_TIMEOUT_MS = get_from_env("PERSONHOG_TIMEOUT_MS", 5000, type_cast=int)-PERSONHOG_ROLLOUT_PERCENTAGE = get_from_env("PERSONHOG_ROLLOUT_PERCENTAGE", 0, type_cast=int)# gRPC channel optionsPERSONHOG_KEEPALIVE_TIME_MS = get_from_env("PERSONHOG_KEEPALIVE_TIME_MS", 30_000, type_cast=int)@@ -15,8 +13,8 @@ PERSONHOG_MAX_SEND_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_SEND_MESSAGE_LENPERSONHOG_MAX_RECV_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_RECV_MESSAGE_LENGTH", 128 * 1024 * 1024, type_cast=int)PERSONHOG_CLIENT_IDLE_TIMEOUT_MS = get_from_env("PERSONHOG_CLIENT_IDLE_TIMEOUT_MS", 0, type_cast=int)-# Retry settings for transient gRPC errors (before falling back to ORM)-PERSONHOG_MAX_RETRIES = get_from_env("PERSONHOG_MAX_RETRIES", 1, type_cast=int)+# Retry settings for transient gRPC errors+PERSONHOG_MAX_RETRIES = get_from_env("PERSONHOG_MAX_RETRIES", 2, type_cast=int)PERSONHOG_INITIAL_BACKOFF_MS = get_from_env("PERSONHOG_INITIAL_BACKOFF_MS", 50, type_cast=int)PERSONHOG_MAX_BACKOFF_MS = get_from_env("PERSONHOG_MAX_BACKOFF_MS", 1000, type_cast=int)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 514ef7487ad0..9d0f2d7ac2f3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -140,7 +140,6 @@ MIDDLEWARE = ["posthog.gzip_middleware.ScopedGZipMiddleware","posthog.middleware.per_request_logging_context_middleware","django_structlog.middlewares.RequestMiddleware",- "posthog.personhog_client.middleware.PersonHogGateMiddleware","posthog.middleware.Fix204Middleware","django.middleware.security.SecurityMiddleware","posthog.middleware.OAuthCoopMiddleware",diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex cb9e5dd8b377..509e729d51e1 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -9,7 +9,6 @@ from django.utils import timezonefrom dateutil.relativedelta import relativedeltafrom parameterized import parameterized-from posthog.models.person import Personfrom posthog.tasks.calculate_cohort import (COHORT_STUCK_COUNT_GAUGE,COHORTS_STALE_COUNT_GAUGE,@@ -26,6 +25,7 @@ from posthog.tasks.calculate_cohort import ()from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_idsMISSING_COHORT_ID = 12345@@ -51,8 +51,7 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla_calculate_cohort_from_list.assert_called_once_with(cohort_id, ["blabla"])calculate_cohort_from_list(cohort_id, ["blabla"], team_id=self.team.id, id_type="distinct_id")cohort = Cohort.objects.get(pk=cohort_id)- people = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people.count(), 1)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_create_trends_cohort(self, _calculate_cohort_from_list: MagicMock) -> None:@@ -83,8 +82,7 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla_calculate_cohort_from_list.assert_called_once_with(cohort_id, ["blabla"])calculate_cohort_from_list(cohort_id, ["blabla"], team_id=self.team.id, id_type="distinct_id")cohort = Cohort.objects.get(pk=cohort_id)- people = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people.count(), 1)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)def test_calculate_cohort_from_list_with_person_id_type(self) -> None:"""Test that calculate_cohort_from_list works correctly with person UUIDs"""@@ -103,13 +101,12 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla# Verify persons were added to cohortcohort.refresh_from_db()- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}- self.assertIn(str(person1.uuid), person_uuids_in_cohort)- self.assertIn(str(person2.uuid), person_uuids_in_cohort)+ member_ids = set(list_cohort_member_ids(team_id=cohort.team_id, cohort_id=cohort.pk))+ self.assertIn(person1.id, member_ids)+ self.assertIn(person2.id, member_ids)def test_calculate_cohort_from_list_with_distinct_id_type(self) -> None:"""Test that calculate_cohort_from_list works correctly with distinct IDs"""@@ -128,13 +125,12 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla# Verify persons were added to cohortcohort.refresh_from_db()- people_in_cohort = Person.objects.filter(cohort__id=cohort.pk, team_id=cohort.team_id)- self.assertEqual(people_in_cohort.count(), 2)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 2)# Verify specific persons are in the cohort- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}- self.assertIn(str(person1.uuid), person_uuids_in_cohort)- self.assertIn(str(person2.uuid), person_uuids_in_cohort)+ member_ids = set(list_cohort_member_ids(team_id=cohort.team_id, cohort_id=cohort.pk))+ self.assertIn(person1.id, member_ids)+ self.assertIn(person2.id, member_ids)@patch("posthog.tasks.calculate_cohort.increment_version_and_enqueue_calculate_cohort")def test_exponential_backoff(self, patch_increment_version_and_enqueue_calculate_cohort: MagicMock) -> None:diff --git a/posthog/tasks/test/test_deletion_tasks.py b/posthog/tasks/test/test_deletion_tasks.pyindex 33c1fd475adc..197af03b5764 100644--- a/posthog/tasks/test/test_deletion_tasks.py+++ b/posthog/tasks/test/test_deletion_tasks.py@@ -3,10 +3,7 @@ from typing import Anyfrom posthog.test.base import BaseTestfrom unittest.mock import patch-from parameterized import parameterized-from posthog.models.organization import Organization-from posthog.models.person import Person, PersonDistinctIdfrom posthog.models.project import Projectfrom posthog.models.team import Teamfrom posthog.personhog_client.fake_client import fake_personhog_client@@ -69,16 +66,8 @@ class TestDeleteProjectDataAndNotifyTask(BaseTest):class TestDeleteProjectPersonsEndToEnd(BaseTest):- @parameterized.expand(- [- ("via_orm", False),- ("via_personhog", True),- ]- )@patch("posthog.email.is_email_available", return_value=False)- def test_deletes_persons_and_distinct_ids_for_team(- self, _name: str, personhog_enabled: bool, mock_email: Any- ) -> None:+ def test_deletes_persons_and_distinct_ids_for_team(self, mock_email: Any) -> None:team = Team.objects.create(organization=self.organization, name="Team to delete")other_team = Team.objects.create(organization=self.organization, name="Other team")@@ -86,11 +75,10 @@ class TestDeleteProjectPersonsEndToEnd(BaseTest):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:- fake.add_person(team_id=team.id, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a", "b"])- fake.add_person(team_id=team.id, person_id=p2.pk, uuid=str(p2.uuid), distinct_ids=["c"])- fake.add_person(team_id=other_team.id, person_id=p_other.pk, uuid=str(p_other.uuid), distinct_ids=["d"])+ with fake_personhog_client() as fake:+ fake.add_person(team_id=team.id, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a", "b"])+ fake.add_person(team_id=team.id, person_id=p2.pk, uuid=str(p2.uuid), distinct_ids=["c"])+ fake.add_person(team_id=other_team.id, person_id=p_other.pk, uuid=str(p_other.uuid), distinct_ids=["d"])delete_project_data_and_notify_task(team_ids=[team.id],@@ -101,18 +89,11 @@ class TestDeleteProjectPersonsEndToEnd(BaseTest):self.assertFalse(Team.objects.filter(id=team.id).exists())- if personhog_enabled:- # Fake client doesn't touch Django DB — verify the RPC was called correctly- calls = fake.assert_called("delete_persons_batch_for_team")- team_ids_called = {c.request.team_id for c in calls}- self.assertIn(team.id, team_ids_called)- self.assertNotIn(other_team.id, team_ids_called)- else:- self.assertEqual(Person.objects.filter(team_id=team.id).count(), 0)- self.assertEqual(PersonDistinctId.objects.filter(team_id=team.id).count(), 0)-- self.assertTrue(Person.objects.filter(id=p_other.id).exists())- self.assertEqual(PersonDistinctId.objects.filter(team_id=other_team.id).count(), 1)+ # Fake client doesn't touch Django DB — verify the RPC was called correctly+ calls = fake.assert_called("delete_persons_batch_for_team")+ team_ids_called = {c.request.team_id for c in calls}+ self.assertIn(team.id, team_ids_called)+ self.assertNotIn(other_team.id, team_ids_called)class TestDeleteOrganizationDataAndNotifyTask(BaseTest):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 c4e35927e518..d635541783b7 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@@ -23,6 +23,8 @@ from posthog.temporal.backfill_group_type_created_at.types import (from posthog.test.persons import create_group_type_mappingfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+pytestmark = pytest.mark.persons_db_direct+CREATED_AT = datetime(2026, 5, 31, 22, 33, tzinfo=UTC)EARLIER = datetime(2026, 5, 12, 0, 0, tzinfo=UTC)LATER = datetime(2026, 6, 6, 0, 0, tzinfo=UTC)diff --git a/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py b/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.pyindex dfc7f3677dd8..c846c0b32594 100644--- a/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py+++ b/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py@@ -14,6 +14,8 @@ from posthog.temporal.backfill_group_type_created_at.types import ()from posthog.temporal.backfill_group_type_created_at.workflows import BackfillGroupTypeCreatedAtWorkflow+pytestmark = pytest.mark.persons_db_direct+TEST_TEAM_ID = 12345TEST_PROJECT_ID = 12345SAMPLE_UPDATES = [diff --git a/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py b/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.pyindex ee058d175643..25cfcd6d5618 100644--- a/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py+++ b/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py@@ -19,7 +19,7 @@ pytestmark = pytest.mark.django_dbclass TestDeletePersonsActivity:async def test_by_ids_resolves_uuids_then_deletes(self, activity_environment):- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:fake.add_person(team_id=1, person_id=10, uuid=str(uuid_lib.uuid4()), distinct_ids=["d1"])deleted, should_continue = await activity_environment.run(@@ -34,7 +34,7 @@ class TestDeletePersonsActivity:fake.assert_called("delete_persons")async def test_by_ids_should_continue_when_more_remain(self, activity_environment):- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:for pid in (1, 2, 3):fake.add_person(team_id=1, person_id=pid, uuid=str(uuid_lib.uuid4()), distinct_ids=[f"d{pid}"])@@ -47,7 +47,7 @@ class TestDeletePersonsActivity:assert should_continue is True # one of three ids is left for the next batchasync def test_whole_team_uses_batch_for_team_rpc(self, activity_environment):- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:for pid in (1, 2):fake.add_person(team_id=1, person_id=pid, uuid=str(uuid_lib.uuid4()))@@ -68,7 +68,7 @@ class TestDeletePersonsActivity:class TestPrecleanCohortMembersActivity:async def test_clears_team_cohort_memberships(self, activity_environment, ateam):cohort = await sync_to_async(Cohort.objects.create)(team=ateam, name="preclean-test")- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:fake.add_cohort_membership(person_id=5, cohort_id=cohort.id)await activity_environment.run(@@ -81,7 +81,7 @@ class TestPrecleanCohortMembersActivity:assert (cohort.id, 5) not in fake._cohort_membersasync def test_noop_when_team_has_no_cohorts(self, activity_environment, ateam):- with fake_personhog_client(gate_enabled=True) as fake:+ with fake_personhog_client() as fake:await activity_environment.run(preclean_cohort_members_activity,PrecleanCohortMembersActivityInputs(team_id=ateam.id),diff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.pyindex a632a4273483..295ede5a61da 100644--- a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py+++ b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py@@ -32,6 +32,8 @@ from posthog.temporal.tests.sync_person_distinct_ids.conftest import (insert_person_to_ch,)+pytestmark = pytest.mark.persons_db_direct+@pytest.mark.django_dbclass TestFindOrphanedPersons:diff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py b/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.pyindex 0c9001c38bc2..dcce474f1915 100644--- a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py+++ b/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py@@ -29,6 +29,8 @@ from posthog.temporal.tests.sync_person_distinct_ids.conftest import (insert_persons_to_ch_batch,)+pytestmark = pytest.mark.persons_db_direct+@pytest.mark.django_db(transaction=True)class TestSyncPersonDistinctIdsWorkflow:diff --git a/posthog/test/AGENTS.md b/posthog/test/AGENTS.mdindex dc0e8b21cf0b..e0beb3fc820c 100644--- a/posthog/test/AGENTS.md+++ b/posthog/test/AGENTS.md@@ -5,18 +5,22 @@**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.+They seed the active personhog fake (and, for persons, ClickHouse) so reads through personhog see the data.+They do NOT write to the persons DB — personhog is the sole source of truth.-Direct ORM calls skip the fake — tests will silently return empty results from any code path that reads through personhog.+The persons DB router raises `PersonsDBORMBlockedError` on any ORM access to a persons-DB model while a+test's personhog fake is active, so a direct `Person.objects.create(...)` / `.get(...)` / `.filter(...)` in a+test fails loudly. Route writes through the helpers below and reads through the personhog helpers in+`posthog/models/person/util.py` (`get_person_by_uuid`, `get_persons_by_distinct_ids`, …).## Quick reference```pythonfrom posthog.test.persons import (- create_person, # immediate: ORM + fake- delete_person, # unseed fake + delete from Postgres+ create_person, # immediate: ClickHouse + fake+ delete_person, # unseed fakeadd_distinct_id, # add a distinct ID to an existing person- update_person, # person.save() + re-seed fake+ update_person, # re-sync mutated person to ClickHouse + fakecreate_group,update_group,create_group_type_mapping,@@ -62,11 +66,14 @@ 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.+PostHog moved person/group reads from the Django ORM to a gRPC service (personhog), which is now the+sole source of truth. In tests, a `FakePersonHogClient` stands in for the real service, and the persons+DB is not used at all — the router blocks ORM access to persons-DB models while the fake is active.+The helpers seed the fake (and ClickHouse for persons) so code under test reads consistent data.-When the ORM fallback is fully removed, the ORM writes in these helpers get deleted — one place to change, not 75+ test files.+Tests that exercise the persons DB _layer itself_ (the temporal `sync_person_distinct_ids` / `backfill_*`+activities, the dagster persons-maintenance jobs, and `test_person_schema`) are excluded from the fake+in the root `conftest.py` and keep direct persons-DB access.## Other test utilities that create persons@@ -75,4 +82,4 @@ When the ORM fallback is fully removed, the ORM writes in these helpers get dele- `posthog/test/test_utils.py` → `create_group_type_mapping_without_created_at()` — uses the helper internallyIf 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.+Import `_seed_person_into_fake` / `_seed_group_into_fake` / etc. from `posthog.test.persons`.diff --git a/posthog/test/activity_log_utils.py b/posthog/test/activity_log_utils.pyindex 098ea3f49ef8..932da52a99d3 100644--- a/posthog/test/activity_log_utils.py+++ b/posthog/test/activity_log_utils.py@@ -95,12 +95,10 @@ class ActivityLogTestHelper(APILicensedTest):# Groupdef create_group(self, group_type_index: int = 0, group_key: Optional[str] = None, **kwargs) -> dict[str, Any]:"""Create a group via API."""- # First ensure group type exists- from posthog.models.group_type_mapping import GroupTypeMapping+ # First ensure group type exists (seeds the personhog fake, no persons DB write)+ from posthog.test.persons import create_group_type_mapping- GroupTypeMapping.objects.get_or_create(- team=self.team, group_type_index=group_type_index, defaults={"group_type": "organization"}- )+ create_group_type_mapping(team=self.team, group_type_index=group_type_index, group_type="organization")if not group_key:group_key = f"org:{uuid4()}"diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 7992991401a1..5089fb6b9ef7 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -114,7 +114,7 @@ from posthog.models.event.sql import (EVENTS_TABLE_SQL,TRUNCATE_EVENTS_RECENT_TABLE_SQL,)-from posthog.models.event.util import bulk_create_events+from posthog.models.event.util import _resolve_person_for_bulk_event, bulk_create_eventsfrom posthog.models.exchange_rate.sql import (DROP_EXCHANGE_RATE_DICTIONARY_SQL,DROP_EXCHANGE_RATE_TABLE_SQL,@@ -1516,11 +1516,9 @@ def _flush_ai_events(events: list[dict[str, Any]], person_mapping: dict) -> Noneteam = event.get("team")team_id = event.get("team_id") or (team.pk if team else None)if team_id:- from posthog.models import PersonDistinctId-- pdi = PersonDistinctId.objects.filter(team_id=team_id, distinct_id=distinct_id).first()- if pdi:- event["person_id"] = str(pdi.person.uuid)+ person = _resolve_person_for_bulk_event(team_id, distinct_id)+ if person is not None:+ event["person_id"] = str(person.uuid)from posthog.models.ai_events.test_util import bulk_create_ai_eventsdiff --git a/posthog/test/personhog_fake.py b/posthog/test/personhog_fake.pydeleted file mode 100644index 4f2c5c4b784b..000000000000--- a/posthog/test/personhog_fake.py+++ /dev/null@@ -1,278 +0,0 @@-"""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.pyindex 71bd22211485..f454efca39e7 100644--- a/posthog/test/persons.py+++ b/posthog/test/persons.py@@ -1,49 +1,73 @@"""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.+Every test that needs person/group/cohort data should use these helpers rather+than calling ORM methods directly. personhog is the sole source of truth, so+these helpers seed the active personhog fake (and, for persons, ClickHouse) —+they do NOT write to the persons DB. Person/group rows are returned as unsaved+Django instances carrying synthetic primary keys so attribute access and+serializers keep working without a database round-trip.++The persons DB router raises on any ORM access to persons-DB models while a+test's personhog fake is active, so a direct `Person.objects.create(...)` in a+test will fail loudly — route through these helpers instead."""from __future__ import annotations-import uuidimport datetime as dtfrom typing import TYPE_CHECKING, Any+from django.utils.timezone import now++from posthog.models import signalsfrom posthog.models.group.group import Groupfrom posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.models.person import Person, PersonDistinctId+from posthog.models.person.util import (+ create_person as _ch_create_person,+ create_person_distinct_id as _ch_create_person_distinct_id,+)+from posthog.models.utils import UUIDT+from posthog.person_db_router import persons_orm_blockedif TYPE_CHECKING:+ import uuid+from posthog.models.team import Teamfrom products.cohorts.backend.models.cohort import Cohort-# ── Internal state for deferred (batched) creation ───────────────────+# ── Internal state for deferred (batched) creation + synthetic ids ────_persons_cache: list[dict[str, Any]] = []_persons_ordering_int: int = 0+_next_pk: int = 0+++def _next_synthetic_pk() -> int:+ """Synthetic primary key for in-memory person/group rows (reset per test)."""+ global _next_pk+ _next_pk += 1+ return _next_pkdef _next_deterministic_uuid() -> uuid.UUID:"""Generate a deterministic UUID for consistent test ordering."""+ import uuid as _uuid # noqa: PLC0415+global _persons_ordering_int- result = uuid.UUID(int=_persons_ordering_int, version=4)+ result = _uuid.UUID(int=_persons_ordering_int, version=4)_persons_ordering_int += 1return resultdef reset_persons_state() -> None:- """Reset deferred persons cache and UUID counter. Called from BaseTest.tearDown."""- global _persons_ordering_int+ """Reset deferred persons cache, UUID counter, and pk counter. Called from BaseTest.tearDown."""+ global _persons_ordering_int, _next_pk_persons_cache.clear()_persons_ordering_int = 0+ _next_pk = 0def has_unflushed_persons() -> bool:@@ -58,7 +82,7 @@ def clear_persons_cache() -> None:def _get_active_fake():- from posthog.test.personhog_fake import _active_fake # noqa: PLC0415+ from posthog.personhog_client.fake_client import _active_fake # noqa: PLC0415return _active_fake@@ -69,7 +93,13 @@ def _datetime_to_ms(val: dt.datetime | None) -> int:return int(val.timestamp() * 1000)-def _seed_person_into_fake(person: Person, distinct_ids: list[str], *, created_at_ms: int | None = None) -> None:+def _seed_person_into_fake(+ person: Person,+ distinct_ids: list[str],+ *,+ created_at_ms: int | None = None,+ distinct_id_versions: dict[str, 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:@@ -78,13 +108,6 @@ def _seed_person_into_fake(person: Person, distinct_ids: list[str], *, created_aexisting_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,@@ -94,7 +117,8 @@ def _seed_person_into_fake(person: Person, distinct_ids: list[str], *, created_aversion=person.version or 0,is_identified=person.is_identified,distinct_ids=new_dids,- distinct_id_versions=distinct_id_versions,+ distinct_id_versions=distinct_id_versions or {},+ last_seen_at=_datetime_to_ms(person.last_seen_at),)for did_with_ver in fake._distinct_ids.get((person.team_id, person.pk), []):@@ -115,6 +139,7 @@ def _reseed_person_into_fake(person: Person) -> None:created_at=_datetime_to_ms(person.created_at),version=person.version or 0,is_identified=person.is_identified,+ last_seen_at=_datetime_to_ms(person.last_seen_at),)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@@ -206,58 +231,148 @@ def _remove_cohort_member_from_fake(cohort_id: int, person_id: int) -> None:fake._cohort_memberships[person_id] = [m for m in memberships if m.cohort_id != cohort_id]+# ── ClickHouse sync (replaces the post_save/post_delete signal mirror) ─+++def _ch_sync_person(person: Person, distinct_ids: list[str]) -> None:+ """Mirror a person + its distinct ids into ClickHouse, matching the old+ post_save signal behavior that fired on ORM creation. Like that signal it is+ a @mutable_receiver, so mute_selected_signals() suppresses the ClickHouse write."""+ if signals.is_muted:+ return+ _ch_create_person(+ team_id=person.team_id,+ properties=person.properties or {},+ uuid=str(person.uuid),+ is_identified=person.is_identified,+ version=person.version or 0,+ created_at=person.created_at,+ )+ for distinct_id in distinct_ids:+ _ch_create_person_distinct_id(person.team_id, str(distinct_id), str(person.uuid), version=0)+++# ── Person instance construction (unsaved, synthetic pk) ──────────────+++def _build_person(create_kwargs: dict[str, Any]) -> Person:+ if not create_kwargs.get("uuid"):+ create_kwargs["uuid"] = UUIDT()+ person = Person(**create_kwargs)+ person.id = _next_synthetic_pk()+ person.created_at = person.created_at or now()+ person.version = person.version or 0+ person._state.adding = False+ return person++# ── 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."""+ """Create a person for tests.++ Consumer tests (the personhog fake is active): seed ClickHouse + the fake,+ no persons DB write. Persons-DB-layer tests (the fake is off / excluded in+ conftest): write real persons-DB rows so the code under test, which reads the+ persons DB directly, sees them — matching the pre-personhog behavior.+ """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 [])++ dids = [str(d) for d in (distinct_ids or [])]++ if not persons_orm_blocked():+ return _create_person_in_orm(create_kwargs, dids)++ person = _build_person(create_kwargs)+ person._distinct_ids = list(dids)+ _ch_sync_person(person, dids)+ _seed_person_into_fake(person, dids)+ return person+++def _create_person_in_orm(create_kwargs: dict[str, Any], dids: list[str]) -> Person:+ """Write a real persons-DB person + distinct ids (for fake-off / excluded tests)."""+ if not create_kwargs.get("uuid"):+ create_kwargs["uuid"] = UUIDT()+ person = Person.objects.create(**create_kwargs)+ for distinct_id in dids:+ PersonDistinctId.objects.create(team_id=person.team_id, person=person, distinct_id=distinct_id, version=0)+ person._distinct_ids = list(dids)+ _ch_sync_person(person, dids)return persondef delete_person(person: Person) -> None:- """Delete a person via the personhog fake (unseeds) and from Postgres."""+ """Soft-delete a person in ClickHouse and unseed the personhog fake.++ Mirrors posthog.models.person.util.delete_person: writes CH tombstones with+ version + 100 (so the delete wins over normal updates) for the person and each+ of its distinct IDs, then removes it from the fake.+ """fake = _get_active_fake()if fake is None:- person.delete() # nosemgrep: no-direct-persons-db-ormreturnfrom posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2 # noqa: PLC0415+ dids_with_version = list(fake._distinct_ids.get((person.team_id, person.pk), []))+ _ch_create_person(+ team_id=person.team_id,+ properties=person.properties or {},+ uuid=str(person.uuid),+ is_identified=person.is_identified,+ version=(person.version or 0) + 100,+ created_at=person.created_at,+ is_deleted=True,+ )+ for did in dids_with_version:+ _ch_create_person_distinct_id(+ person.team_id, did.distinct_id, str(person.uuid), version=(did.version or 0) + 100, is_deleted=True+ )+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+ """Re-sync a mutated person into ClickHouse and the personhog fake."""+ _ch_create_person(+ team_id=person.team_id,+ properties=person.properties or {},+ uuid=str(person.uuid),+ is_identified=person.is_identified,+ version=person.version or 0,+ created_at=person.created_at,+ )_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,- )+ """Add a distinct ID to a person in ClickHouse + the personhog fake (or the persons DB when fake-off)."""+ if not signals.is_muted:+ _ch_create_person_distinct_id(person.team_id, str(distinct_id), str(person.uuid), version=version)++ existing_distinct_ids = getattr(person, "_distinct_ids", None)+ if existing_distinct_ids is not None and distinct_id not in existing_distinct_ids:+ existing_distinct_ids.append(distinct_id)++ if not persons_orm_blocked():+ return PersonDistinctId.objects.create(+ team_id=person.team_id, person=person, distinct_id=str(distinct_id), version=version+ )+_seed_distinct_id_into_fake(person.team_id, person.pk, distinct_id, version=version)- return pdi+ return PersonDistinctId(team_id=person.team_id, person=person, distinct_id=distinct_id, version=version)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.+ Does NOT write immediately. Call flush_persons_and_events() to bulk-insert+ all staged persons into ClickHouse + the personhog fake.Returns an unsaved Person instance (no pk). The pk is only availableafter flush.@@ -281,7 +396,7 @@ def stage_person_for_bulk_create(*args: Any, **kwargs: Any) -> Person:def flush_persons_to_db_and_clickhouse() -> dict[str, Person]:- """Bulk-insert all staged persons into Postgres + ClickHouse + personhog fake.+ """Bulk-insert all staged persons into ClickHouse + the personhog fake.Returns the person_mapping (distinct_id → Person) for event flushing.Called by flush_persons_and_events() in base.py.@@ -320,20 +435,32 @@ def _seed_persons_from_bulk_mapping(person_mapping: dict[str, Person]) -> None: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."""+ """Create a group for tests.++ Fake active: seed the personhog fake only (no persons DB write). Fake off+ (excluded layer/seed tests): write a real persons-DB row so code that reads+ the persons DB directly sees it.+ """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++ if not persons_orm_blocked():+ return Group.objects.create(**create_kwargs)++ group = Group(**create_kwargs)+ group.id = _next_synthetic_pk()+ group.created_at = group.created_at or now()+ group.version = group.version or 0+ group._state.adding = False_seed_group_into_fake(group)return groupdef update_group(group: Group) -> None:- """Save a group to Postgres and re-seed the personhog fake."""- group.save() # nosemgrep: no-direct-persons-db-orm+ """Re-seed a mutated group into the personhog fake."""_seed_group_into_fake(group)@@ -341,17 +468,29 @@ def update_group(group: Group) -> None:def create_group_type_mapping(*, team: Team | None = None, **kwargs: Any) -> GroupTypeMapping:- """Create a group type mapping in Postgres and seed the personhog fake."""+ """Create a group type mapping for tests.++ Fake active: seed the personhog fake only (no persons DB write). Fake off+ (excluded layer tests): write a real persons-DB row so code that reads the+ persons DB directly sees it.+ """if team is not None:kwargs["team"] = team- mapping = GroupTypeMapping.objects.create(**kwargs) # nosemgrep: no-direct-persons-db-orm++ if not persons_orm_blocked():+ return GroupTypeMapping.objects.create(**kwargs)++ mapping = GroupTypeMapping(**kwargs)+ mapping.id = _next_synthetic_pk()+ if mapping.created_at is None:+ mapping.created_at = now()+ mapping._state.adding = False_seed_group_type_mapping_into_fake(mapping)return mappingdef 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+ """Re-seed a mutated group type mapping into the personhog fake."""_seed_group_type_mapping_into_fake(mapping)@@ -359,24 +498,12 @@ def update_group_type_mapping(mapping: GroupTypeMapping) -> None: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-+ """Add persons to a cohort in the personhog fake."""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-+ """Remove persons from a cohort in the personhog fake."""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/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex f3381ef6f85d..e4fabb980365 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -45,8 +45,6 @@ post_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_whenpost_delete:posthog.models.oauth._block_cimd_url_on_application_deletepost_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removalpost_delete:posthog.models.organization.sync_billing_on_membership_removal-post_delete:posthog.models.person.util.person_deleted-post_delete:posthog.models.person.util.person_distinct_id_deletedpost_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_deletepost_delete:posthog.models.remote_config.product_tour_deletedpost_delete:posthog.models.remote_config.site_function_changed@@ -99,8 +97,6 @@ post_save:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__inipost_save:posthog.models.file_system.user_product_list.access_control_createdpost_save:posthog.models.organization.cache_organization_session_agepost_save:posthog.models.organization.sync_billing_on_membership_save-post_save:posthog.models.person.util.person_created-post_save:posthog.models.person.util.person_distinct_id_createdpost_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_savepost_save:posthog.models.remote_config.error_tracking_suppression_rule_savedpost_save:posthog.models.remote_config.feature_flag_saveddiff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.pyindex 9ae53e470d52..ac9bd34601a5 100644--- a/posthog/test/test_cohort_model.py+++ b/posthog/test/test_cohort_model.py@@ -10,14 +10,22 @@ from parameterized import parameterizedfrom posthog.clickhouse.client import sync_executefrom posthog.helpers.batch_iterators import FunctionBatchIterator-from posthog.models import Team+from posthog.models import Person, Team+from posthog.models.person.util import get_person_by_idfrom 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+from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_idsfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+def _require_person_by_id(team_id: int, person_id: int) -> Person:+ person = get_person_by_id(team_id, person_id)+ assert person is not None+ return person++class TestCohort(BaseTest):CLASS_DATA_LEVEL_SETUP = False # So that each test gets a different team_id, ensuring separation of CH data@@ -32,17 +40,17 @@ class TestCohort(BaseTest):cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)cohort.insert_users_by_list(["a header or something", "123", "000", "[email protected]"])cohort.refresh_from_db()- self.assertEqual(cohort.people.count(), 2)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 2)self.assertEqual(cohort.is_calculating, False)# If we accidentally call calculate_people it shouldn't erase peoplecohort.calculate_people_ch(pending_version=0)- self.assertEqual(cohort.people.count(), 2)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 2)# if we add people again, don't increase the number of people in cohortcohort.insert_users_by_list(["123"])cohort.refresh_from_db()- self.assertEqual(cohort.people.count(), 2)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 2)self.assertEqual(cohort.is_calculating, False)def test_insert_by_distinct_id_in_batches(self):@@ -64,7 +72,7 @@ class TestCohort(BaseTest):)self.assertEqual(batch_count, 5)cohort.refresh_from_db()- self.assertEqual(cohort.people.count(), 11)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 11)self.assertEqual(cohort.is_calculating, False)@pytest.mark.ee@@ -345,8 +353,9 @@ class TestCohort(BaseTest):# Fetch all persons in the cohortcohort.refresh_from_db()assert cohort.count == 11- assert cohort.people.count() == 11- cohort_person_uuids = {str(p.uuid) for p in cohort.people.all()}+ assert count_cohort_members(self.team.id, cohort.pk) == 11+ member_ids = list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.pk)+ cohort_person_uuids = {str(_require_person_by_id(self.team.id, pid).uuid) for pid in member_ids}assert cohort_person_uuids == set(uuids)assert cohort.is_calculating is False@@ -361,7 +370,7 @@ class TestCohort(BaseTest):# First insertion - add users 0-4 (batch size 3 will create batches: [0,1,2], [3,4])cohort.insert_users_by_list(["user0", "user1", "user2", "user3", "user4"], batch_size=3)cohort.refresh_from_db()- self.assertEqual(cohort.people.count(), 5)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 5)# Second insertion - try to add users 2-7 (users 2,3,4 are already in cohort)# This tests that our LEFT JOIN optimization works across batch boundaries@@ -369,12 +378,12 @@ class TestCohort(BaseTest):cohort.refresh_from_db()# Should have 8 people total (user0-user7) - no duplicates- self.assertEqual(cohort.people.count(), 8)+ self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 8)# Verify all expected people are in the cohort- cohort_person_distinct_ids = set()- for person in cohort.people.all():- cohort_person_distinct_ids.update(person.distinct_ids)+ cohort_person_distinct_ids: set[str] = set()+ for pid in list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.pk):+ cohort_person_distinct_ids.update(_require_person_by_id(self.team.id, pid).distinct_ids)expected_distinct_ids = {f"user{i}" for i in range(8)}self.assertEqual(cohort_person_distinct_ids, expected_distinct_ids)@@ -399,8 +408,9 @@ class TestCohort(BaseTest):)cohort.refresh_from_db()- assert cohort.people.count() == 1- assert str(cohort.people.first().uuid) == str(person.uuid)+ member_ids = list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.pk)+ assert len(member_ids) == 1+ assert str(_require_person_by_id(self.team.id, member_ids[0]).uuid) == str(person.uuid)@override_settings(DEBUG=False)def test_insert_re_raises_soft_time_limit_exceeded(self):diff --git a/posthog/test/test_journeys.py b/posthog/test/test_journeys.pyindex 126ae21e9d7d..fd1448c3d9ee 100644--- a/posthog/test/test_journeys.py+++ b/posthog/test/test_journeys.py@@ -11,8 +11,10 @@ from posthog.test.base import _create_event, flush_persons_and_eventsfrom django.utils import timezonefrom posthog.clickhouse.client import sync_execute-from posthog.models import Group, Person, PersonDistinctId, Team+from posthog.models import Person, Teamfrom posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.group.util import get_group_by_key+from posthog.models.person.util import get_person_by_distinct_iddef journeys_for(@@ -54,10 +56,9 @@ def journeys_for(distinct_ids=[distinct_id], team_id=team.pk, uuid=derived_uuid)else:- people[distinct_id] = Person.objects.get(- persondistinctid__distinct_id=distinct_id,- persondistinctid__team_id=team.pk,- )+ existing_person = get_person_by_distinct_id(team.pk, distinct_id)+ assert existing_person is not None+ people[distinct_id] = existing_personfor event in events:# Populate group properties as well@@ -65,16 +66,10 @@ def journeys_for(for property_key, value in (event.get("properties") or {}).items():if property_key.startswith("$group_"):group_type_index = property_key[-1]- try:- group = Group.objects.get(- team_id=team.pk,- group_type_index=group_type_index,- group_key=value,- )- group_mapping[f"group{group_type_index}"] = group-- except Group.DoesNotExist:+ group = get_group_by_key(team.pk, int(group_type_index), value)+ if group is None:continue+ group_mapping[f"group{group_type_index}"] = groupif "timestamp" not in event:event["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")@@ -195,22 +190,18 @@ class InMemoryEvent:def update_or_create_person(distinct_ids: list[str], team_id: int, **kwargs):- (person, _) = Person.objects.update_or_create(- persondistinctid__distinct_id__in=distinct_ids,- persondistinctid__team_id=team_id,- defaults={**kwargs, "team_id": team_id},- )+ from posthog.test.persons import create_person, update_person # noqa: PLC0415++ existing = Nonefor distinct_id in distinct_ids:- PersonDistinctId.objects.update_or_create(- distinct_id=distinct_id,- team_id=person.team_id,- defaults={- "person_id": person.id,- "team_id": team_id,- "distinct_id": distinct_id,- },- )- from posthog.test.persons import _seed_person_into_fake # noqa: PLC0415-- _seed_person_into_fake(person, distinct_ids)- return person+ existing = get_person_by_distinct_id(team_id, distinct_id)+ if existing is not None:+ break++ if existing is None:+ return create_person(team_id=team_id, distinct_ids=distinct_ids, **kwargs)++ for key, value in kwargs.items():+ setattr(existing, key, value)+ update_person(existing)+ return existingdiff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex b672cf63cab7..79a10954194f 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -2,7 +2,7 @@ import osimport jsonimport base64from datetime import datetime, timedelta-from typing import Any, cast+from typing import TYPE_CHECKING, Any, castfrom zoneinfo import ZoneInfoimport pytest@@ -20,8 +20,12 @@ from parameterized import parameterizedfrom rest_framework.request import Requestfrom posthog.exceptions import RequestParsingError, UnspecifiedCompressionFallbackParsingError-from posthog.models import EventDefinition, GroupTypeMapping, Organization, Team, User+from posthog.models import EventDefinition, Organization, Team, Userfrom posthog.settings.utils import get_from_env++if TYPE_CHECKING:+ from posthog.models.group_type_mapping import GroupTypeMapping+from posthog.utils import (PotentialSecurityProblemException,_build_flag_provider,@@ -851,13 +855,21 @@ class TestFlatten(TestCase):def create_group_type_mapping_without_created_at(**kwargs) -> "GroupTypeMapping":- from posthog.test.persons import create_group_type_mapping # noqa: PLC0415+ from posthog.person_db_router import PERSONS_DB_FOR_WRITE, persons_orm_blocked # noqa: PLC0415+ from posthog.test.persons import _seed_group_type_mapping_into_fake, create_group_type_mapping # noqa: PLC0415instance = 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-+ instance.created_at = None+ # Mirror create_group_type_mapping's own branch: when the fake is off (persons-DB-direct tests),+ # it wrote a real row whose GroupTypeMapping.save() auto-stamped created_at=now(). Null the+ # column with a direct UPDATE (which skips that auto-stamp) so the persons DB genuinely holds+ # a null created_at — making this helper's name true to form for the fake-off path too.+ if not persons_orm_blocked():+ from posthog.models.group_type_mapping import GroupTypeMapping # noqa: PLC0415++ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm+ pk=instance.pk+ ).update(created_at=None)_seed_group_type_mapping_into_fake(instance)return instancediff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 57803e857dd1..6b58e249c19c 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -567,70 +567,14 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Returns:Number of batches processed."""- from posthog.personhog_client.gate import use_personhog-- from products.cohorts.backend.models.util import count_cohort_members, insert_static_cohort+ from products.cohorts.backend.models.util import count_cohort_memberscurrent_batch_index = -1processing_error = None- personhog = use_personhog()try:- from django.db import connections, router-- if personhog:- for batch_index, batch in batch_iterator:- current_batch_index = batch_index- self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)- else:- db_write = router.db_for_write(Person) or "default"- db_read = router.db_for_read(Person) or "default"- persons_connection = connections[db_write]- cursor = persons_connection.cursor()- cohort_people_table = CohortPeople._meta.db_table- for batch_index, batch in batch_iterator:- current_batch_index = batch_index-- persons_query = (- Person.objects.db_manager(db_read) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id)- .filter(uuid__in=batch) # nosemgrep: no-direct-persons-db-orm- )- if insert_in_clickhouse:- # Both querysets must use db_write so Django can merge the- # .exclude() into a single NOT IN subquery. Using db_read- # for Person + db_write for CohortPeople causes a- # "Subqueries aren't allowed across different databases"- # ValueError when the aliases differ (production config).- insert_uuids_query = (- Person.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id, uuid__in=batch)- .exclude(- id__in=CohortPeople.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm- .filter(cohort_id=self.id)- .values_list("person_id", flat=True)- )- )- insert_static_cohort(- list(insert_uuids_query.values_list("uuid", flat=True)),- self.pk,- team_id=team_id,- )-- # Dedup via LEFT JOIN so the exclusion stays entirely in SQL,- # avoiding the O(cohort_size) memory cost of loading all- # existing member IDs into Python. Both tables live on the- # persons DB so the join works on the db_write cursor.- sql, params = persons_query.only("pk").query.sql_with_params()- query = f"""- INSERT INTO "{cohort_people_table}" ("person_id", "cohort_id", "version")- SELECT p."id", {self.pk}, {self.version or "NULL"}- FROM ({sql}) AS p- LEFT JOIN "{cohort_people_table}" AS cp- ON cp."person_id" = p."id" AND cp."cohort_id" = {self.pk}- WHERE cp."person_id" IS NULL- ON CONFLICT DO NOTHING- """- cursor.execute(query, params)+ for batch_index, batch in batch_iterator:+ current_batch_index = batch_index+ self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)except SoftTimeLimitExceeded as err:# Let a Celery soft-time-limit interruption propagate so the task's time limit@@ -771,8 +715,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):if person is None:raise Person.DoesNotExist- # Check if person is in the cohort — routed through personhog when enabled,- # falling back to the persons-DB ORM query otherwise.+ # Check if person is in the cohort via personhog.is_member = is_person_in_cohort(team_id=team_id, person_id=person.id, cohort_id=self.id)# Delete from PostgreSQL first (source of truth), then ClickHouse.diff --git a/products/cohorts/backend/models/test/test_cohort_personhog.py b/products/cohorts/backend/models/test/test_cohort_membership.pysimilarity index 86%rename from products/cohorts/backend/models/test/test_cohort_personhog.pyrename to products/cohorts/backend/models/test/test_cohort_membership.pyindex 7e1d8104ad1d..28992811727c 100644--- a/products/cohorts/backend/models/test/test_cohort_personhog.py+++ b/products/cohorts/backend/models/test/test_cohort_membership.py@@ -1,89 +1,13 @@-"""Tests that cohort person-lookup methods produce identical results-via the personhog path."""+"""Tests for cohort membership operations (insert, delete, count, list, check)."""from posthog.test.base import BaseTestfrom unittest.mock import patchfrom posthog.models import Team-from posthog.test.personhog_fake import get_active_fake+from posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import add_cohort_members, create_person-from products.cohorts.backend.models.cohort import Cohort, CohortPeople---class TestGetPersonUuidsByDistinctIds(BaseTest):- def _get_uuids(self, distinct_ids: list[str]) -> list[str]:- from posthog.models.person.util import get_person_uuids_by_distinct_ids-- return get_person_uuids_by_distinct_ids(self.team.pk, distinct_ids)-- def test_returns_uuids_for_matching_distinct_ids(self):- 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)}- 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 == []- 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"])-- assert result == []-- def test_cross_team_isolation(self):- other_team = self.organization.teams.create(name="Other Team")- 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 = 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 = 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 = [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 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-- create_person(team=self.team, distinct_ids=["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- assert "id" in mask- assert "team_id" in mask- assert "properties" not in mask+from products.cohorts.backend.models.cohort import Cohortclass TestRemoveUserByUuid(BaseTest):@@ -153,7 +77,7 @@ class TestRemoveUserByUuid(BaseTest):result = other_team_cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)assert result is False- assert CohortPeople.objects.filter(cohort=other_team_cohort, person=person).exists()+ assert (other_team_cohort.id, person.id) in get_active_fake()._cohort_membersmock_remove_ch.assert_not_called()@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@@ -369,7 +293,7 @@ class TestInsertCohortMembers(BaseTest):inserted = insert_cohort_members(self.team.id, other_cohort.id, [person.id], version=1)assert inserted == 0- assert not CohortPeople.objects.filter(cohort=other_cohort).exists()+ assert (other_cohort.id, person.id) not in get_active_fake()._cohort_membersget_active_fake().assert_not_called("insert_cohort_members")def test_skip_ownership_check_bypasses_team_validation(self):@@ -425,7 +349,7 @@ class TestDeleteCohortMember(BaseTest):result = delete_cohort_member(self.team.id, other_cohort.id, person.id)assert result is False- assert CohortPeople.objects.filter(cohort=other_cohort, person=person).exists()+ assert (other_cohort.id, person.id) in get_active_fake()._cohort_membersget_active_fake().assert_not_called("delete_cohort_member")diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex 1e3ae92656a1..8baeca2af765 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport copyimport uuid+from collections.abc import Sequencefrom datetime import datetime, timedeltafrom enum import StrEnumfrom typing import TYPE_CHECKING, Any, Optional, Union, cast@@ -626,7 +627,7 @@ def format_cohort_subquery(cohort: Cohort, index: int, custom_match_field="persoreturn person_query, params-def insert_static_cohort(person_uuids: list[Optional[uuid.UUID]], cohort_id: int, *, team_id: int):+def insert_static_cohort(person_uuids: Sequence[Optional[uuid.UUID]], cohort_id: int, *, team_id: int):tag_queries(product=ProductKey.COHORTS,cohort_id=cohort_id,@@ -1188,47 +1189,30 @@ def _check_cohort_membership_via_personhog(person_id: int, cohort_ids: list[int]def check_cohort_membership(team_id: int, person_id: int, cohort_ids: list[int]) -> dict[int, bool]:- """Return ``{cohort_id: is_member}`` for the given person.+ """Return ``{cohort_id: is_member}`` for the given person via personhog.- Routes through personhog when the gate is enabled, falling back to a Django- ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.Membership for cohorts the person is not in is returned as ``False`` ratherthan being omitted, so callers can index directly by cohort_id."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_callif not cohort_ids:return {}- # Local import to avoid circulars (cohort → person via CohortPeople FK).- from posthog.models.person.person import READ_DB_FOR_PERSONS-- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohort# Scope cohort_ids to the team via Cohort on the default DB before querying- # either the personhog RPC or the persons-DB CohortPeople table. Neither- # downstream path enforces team ownership (posthog_cohortpeople has no- # team_id column; the RPC just filters by person_id + cohort_id), so the- # tenant boundary has to be applied here. Cohorts belonging to a different- # team are reported as ``False`` rather than looked up. Same pattern as- # `posthog.models.team.util.delete_bulky_postgres_data`.+ # the personhog RPC. The RPC just filters by person_id + cohort_id and does+ # not enforce team ownership, so the tenant boundary has to be applied here.+ # Cohorts belonging to a different team are reported as ``False`` rather than+ # looked up. Same pattern as `posthog.models.team.util.delete_bulky_postgres_data`.scoped_cohort_ids = list(Cohort.objects.filter(id__in=cohort_ids, team_id=team_id).values_list("id", flat=True))if not scoped_cohort_ids:return dict.fromkeys(cohort_ids, False)- def orm_fn() -> dict[int, bool]:- member_ids = set(- CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(person_id=person_id, cohort_id__in=scoped_cohort_ids)- .values_list("cohort_id", flat=True)- )- return {cohort_id: cohort_id in member_ids for cohort_id in scoped_cohort_ids}-- scoped_result = _personhog_routed(+ scoped_result = personhog_call("check_cohort_membership",lambda: _check_cohort_membership_via_personhog(person_id, scoped_cohort_ids),- orm_fn,- team_id=team_id,)# Expand back to the caller's original cohort_ids; cohorts that were scoped# out (not owned by this team) register as non-member.@@ -1265,35 +1249,20 @@ def _list_cohort_member_ids_via_personhog(cohort_id: int) -> list[int]:def list_cohort_member_ids(team_id: int, cohort_id: int) -> list[int]:- """Return all person IDs belonging to a static cohort.-- Routes through personhog when the gate is enabled, falling back to a Django- ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.- """- from posthog.models.person.person import READ_DB_FOR_PERSONS- from posthog.models.person.util import _personhog_routed+ """Return all person IDs belonging to a static cohort via personhog."""+ from posthog.personhog_client.client import personhog_call- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohort- # Validate cohort ownership on the default DB before querying the persons DB- # or the personhog RPC — neither downstream path enforces team isolation- # (posthog_cohortpeople has no team_id column; the proto has no team_id field).+ # Validate cohort ownership on the default DB before querying the personhog+ # RPC — the proto has no team_id field, so the tenant boundary is applied here.# Same pattern as check_cohort_membership / delete_bulky_postgres_data.if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return []- def orm_fn() -> list[int]:- return list(- CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(cohort_id=cohort_id)- .values_list("person_id", flat=True)- )-- return _personhog_routed(+ return personhog_call("list_cohort_member_ids",lambda: _list_cohort_member_ids_via_personhog(cohort_id),- orm_fn,- team_id=team_id,)@@ -1328,46 +1297,22 @@ def insert_cohort_members() -> int:"""Insert person IDs into a static cohort's PG membership table.- Routes through personhog when the gate is enabled, falling back to a raw- SQL INSERT against ``posthog_cohortpeople`` (on the persons DB) otherwise.- Returns the number of newly inserted rows (duplicates are skipped).+ Routes through personhog. Returns the number of newly inserted rows+ (duplicates are skipped)."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_callif not person_ids:return 0- from posthog.models.person import Person-- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohortif not _skip_ownership_check and not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return 0- def orm_fn() -> int:- from django.db import connections, router-- db_write = router.db_for_write(Person) or "default"- cursor = connections[db_write].cursor()- table = CohortPeople._meta.db_table- placeholders = ",".join(["%s"] * len(person_ids))- query = f"""- INSERT INTO "{table}" ("person_id", "cohort_id", "version")- SELECT pid, %s, %s- FROM UNNEST(ARRAY[{placeholders}]) AS t(pid)- WHERE NOT EXISTS (- SELECT 1 FROM "{table}" AS cp- WHERE cp."person_id" = pid AND cp."cohort_id" = %s- )- """- cursor.execute(query, [cohort_id, version, *person_ids, cohort_id])- return cursor.rowcount-- return _personhog_routed(+ return personhog_call("insert_cohort_members",lambda: _insert_cohort_members_via_personhog(cohort_id, person_ids, version),- orm_fn,- team_id=team_id,)@@ -1384,30 +1329,20 @@ def _delete_cohort_member_via_personhog(cohort_id: int, person_id: int) -> bool:def delete_cohort_member(team_id: int, cohort_id: int, person_id: int) -> bool:- """Remove a single person from a static cohort's PG membership table.+ """Remove a single person from a static cohort's membership via personhog.- Routes through personhog when the gate is enabled, falling back to a Django- ORM DELETE against ``posthog_cohortpeople`` (on the persons DB) otherwise.Returns ``True`` if a row was deleted, ``False`` otherwise."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_call- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohortif not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return False- def orm_fn() -> bool:- deleted_count, _ = CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm- cohort_id=cohort_id, person_id=person_id- ).delete() # nosemgrep: no-direct-persons-db-orm- return deleted_count > 0-- return _personhog_routed(+ return personhog_call("delete_cohort_member",lambda: _delete_cohort_member_via_personhog(cohort_id, person_id),- orm_fn,- team_id=team_id,)@@ -1441,31 +1376,18 @@ def _delete_cohort_members_bulk_via_personhog(cohort_ids: list[int], batch_size:def delete_cohort_members_bulk(team_id: int, cohort_ids: list[int], batch_size: int = 10_000) -> int:- """Delete all PG cohort membership rows for the given cohort IDs.+ """Delete all cohort membership rows for the given cohort IDs via personhog.- Routes through personhog when the gate is enabled, falling back to the- Django ORM ``_raw_delete`` against ``posthog_cohortpeople`` otherwise.Returns the total number of deleted rows."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_callif not cohort_ids:return 0- from products.cohorts.backend.models.cohort import CohortPeople-- def orm_fn() -> int:- from django.db import router-- qs = CohortPeople.objects.filter(cohort_id__in=cohort_ids) # nosemgrep: no-direct-persons-db-orm- db_alias = router.db_for_write(CohortPeople)- return qs._raw_delete(db_alias)-- return _personhog_routed(+ return personhog_call("delete_cohort_members_bulk",lambda: _delete_cohort_members_bulk_via_personhog(cohort_ids, batch_size),- orm_fn,- team_id=team_id,)@@ -1490,31 +1412,20 @@ def _count_cohort_members_via_personhog(cohort_ids: list[int], consistency: Readdef count_cohort_members(team_id: int, cohort_id: int, *, consistency: ReadConsistency = "eventual") -> int:"""Return the number of persons in a static cohort.- Routes through personhog when the gate is enabled, falling back to a Django- ORM COUNT against ``posthog_cohortpeople`` (on the persons DB) otherwise.+ Routes through personhog.Use ``consistency="strong"`` when reading immediately after a write(e.g. after inserting or deleting cohort members) to avoid stale counts- from replication lag (ORM) or eventual consistency (personhog).+ from personhog's eventual consistency."""- from posthog.models.person.util import _personhog_routed+ from posthog.personhog_client.client import personhog_call- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohortif not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return 0- def orm_fn() -> int:- qs = CohortPeople.objects.filter(cohort_id=cohort_id) # nosemgrep: no-direct-persons-db-orm- if consistency == "strong":- from posthog.person_db_router import PERSONS_DB_FOR_WRITE-- qs = qs.using(PERSONS_DB_FOR_WRITE)- return qs.count()-- return _personhog_routed(+ return personhog_call("count_cohort_members",lambda: _count_cohort_members_via_personhog([cohort_id], consistency),- orm_fn,- team_id=team_id,)diff --git a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.pyindex d073a9e8a1f0..ed6e00d55bac 100644--- a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py@@ -1,5 +1,6 @@from io import StringIO+import pytestfrom posthog.test.base import BaseTestfrom django.core.management import call_command@@ -13,6 +14,8 @@ from products.customer_analytics.backend.models.account import Accountfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfigfrom products.notebooks.backend.models import Notebook, ResourceNotebook+pytestmark = pytest.mark.persons_db_direct+class TestSeedCustomerAnalyticsAccounts(BaseTest):def tearDown(self):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 212493766e3b..040d1ad1983f 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@@ -29,6 +29,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import count_cohort_membersfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.utils import (@@ -1216,7 +1217,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):if filter_name == "cohort_static" and cohort:cohort.insert_users_by_list(["user_control_1", "user_control_2", "user_test_2"])- self.assertEqual(cohort.people.count(), 3)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.id, consistency="strong"), 3)elif filter_name == "cohort_dynamic" and cohort:cohort.calculate_people_ch(pending_version=0)diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.pyindex 91e66ab40bb7..7eab9df46364 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py@@ -20,6 +20,7 @@ from posthog.models.group.util import create_groupfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import count_cohort_membersfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest@@ -507,7 +508,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):"distinct_test_5",])- self.assertEqual(cohort.people.count(), 6)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.id, consistency="strong"), 6)elif name == "cohort_dynamic" and cohort:cohort.calculate_people_ch(pending_version=0)diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.pyindex 1f7329b17fd3..9ad88a4b655d 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py@@ -38,6 +38,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import count_cohort_membersfrom products.experiments.backend.hogql_queries.experiment_trends_query_runner import ExperimentTrendsQueryRunnerfrom products.experiments.backend.hogql_queries.types import ExperimentMetricTypefrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout@@ -951,7 +952,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):if name == "cohort_static" and cohort:cohort.insert_users_by_list(["user_control_1", "user_control_2", "user_test_2"])- self.assertEqual(cohort.people.count(), 3)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.id, consistency="strong"), 3)elif name == "cohort_dynamic" and cohort:cohort.calculate_people_ch(pending_version=0)diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 3f28f90df918..13331aad75c7 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -7,15 +7,11 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.models.group_type_mapping import (- GROUP_TYPES_STALE_CACHE_KEY_PREFIX,- GroupTypeMapping,- GroupTypesUnavailable,-)+from posthog.models.group_type_mapping import GROUP_TYPES_STALE_CACHE_KEY_PREFIX, GroupTypesUnavailablefrom 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.personhog_client.fake_client import get_active_fakefrom 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@@ -358,7 +354,6 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):@patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")def test_writes_when_genuinely_empty(self, mock_emptied_counter):# A team that truly has no group types must still rebuild normally- GroupTypeMapping.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)@@ -1631,7 +1626,7 @@ class TestVerifyFlagDefinitions(BaseTest):assert len(cohorts_diff) == 1def test_verify_returns_mismatch_when_group_type_mapping_changed(self):- create_group_type_mapping(+ mapping = create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="company",@@ -1650,9 +1645,7 @@ class TestVerifyFlagDefinitions(BaseTest):update_flag_definitions_cache(self.team)- 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 8d3459d977b9..6c56821837e5 100644--- a/products/feature_flags/backend/test/test_max_tools.py+++ b/products/feature_flags/backend/test/test_max_tools.py@@ -5,9 +5,8 @@ from parameterized import parameterizedfrom posthog.schema import FeatureFlagGroupType, GroupPropertyFilter, PersonPropertyFilter, PropertyOperator-from posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.sync import database_sync_to_async-from posthog.test.persons import _seed_group_type_mapping_into_fake+from posthog.test.persons import create_group_type_mappingfrom products.feature_flags.backend.max_tools import (CreateFeatureFlagTool,@@ -183,14 +182,13 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert len(flag.filters["groups"][0]["properties"]) == 1async def test_create_flag_with_group_type(self):- mapping = await GroupTypeMapping.objects.acreate(+ await database_sync_to_async(create_group_type_mapping)(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()@@ -211,14 +209,13 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert flag.filters["aggregation_group_type_index"] == 0async def test_create_flag_with_group_and_property(self):- mapping = await GroupTypeMapping.objects.acreate(+ await database_sync_to_async(create_group_type_mapping)(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()@@ -395,14 +392,13 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert not existsasync def test_create_multivariate_with_property_filters(self):- mapping = await GroupTypeMapping.objects.acreate(+ await database_sync_to_async(create_group_type_mapping)(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/growth/backend/api/test_identity_matching.py b/products/growth/backend/api/test_identity_matching.pyindex fe748b2dbce5..e51763b1cec3 100644--- a/products/growth/backend/api/test_identity_matching.py+++ b/products/growth/backend/api/test_identity_matching.py@@ -4,7 +4,6 @@ from typing import Anyfrom uuid import uuid4from posthog.test.base import APIBaseTest-from unittest.mock import patchfrom django.test import override_settings@@ -12,7 +11,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.client import sync_execute-from posthog.models import Person+from posthog.test.persons import create_personfrom products.growth.backend.constants import (IDENTITY_MATCHING_CANDIDATE_PAIRS_DATASET,@@ -225,7 +224,7 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):assert run_a_rules["low_confidence"] == 0def test_links_are_enriched_with_resolved_persons(self) -> None:- Person.objects.create(+ create_person(team=self.team,distinct_ids=["phone-1"],properties={@@ -236,7 +235,7 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):},last_seen_at=datetime(2026, 6, 1, 12, 0, tzinfo=UTC),)- Person.objects.create(+ create_person(team=self.team,distinct_ids=["[email protected]"],properties={"email": "[email protected]", "name": "Anna", "$geoip_city_name": "Lisbon"},@@ -245,10 +244,7 @@ class TestIdentityMatchingLinksAPI(APIBaseTest):# An orphan with no person profile must resolve to null, not error.self._insert_link(self.team.pk, RUN_A, "ghost-2", "[email protected]", score=4.0, tier="medium")- # Pin person resolution to the ORM path so it reads the persons created above; personhog- # keeps its own store (unseeded here), and its routing is covered in test_util_personhog_routing.- with patch("posthog.personhog_client.gate.use_personhog", return_value=False):- response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")+ response = self.client.get(f"/api/projects/{self.team.pk}/identity_matching_links/")assert response.status_code == status.HTTP_200_OKby_orphan = {row["orphan_distinct_id"]: row for row in response.json()["results"]}diff --git a/pytest.ini b/pytest.iniindex 0b80cacbcab2..4b248ff108b4 100644--- a/pytest.ini+++ b/pytest.ini@@ -16,6 +16,7 @@ markers =async_migrationsrequires_secrets: test needs internal secrets or infra and is skipped on external PRsquarantine: applied automatically to tests quarantined via .test_quarantine.json (hogli test:quarantine)+ persons_db_direct: test exercises the persons DB directly and must not have the personhog fake / ORM block activeasyncio_mode = autoasyncio_default_fixture_loop_scope = modulediff --git a/tools/hogli-commands/hogli_commands/devenv/generator.py b/tools/hogli-commands/hogli_commands/devenv/generator.pyindex f109317dfac1..3371e4552473 100644--- a/tools/hogli-commands/hogli_commands/devenv/generator.py+++ b/tools/hogli-commands/hogli_commands/devenv/generator.py@@ -360,9 +360,7 @@ printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this tooriginal_shell = proc_config.get("shell", "")if original_shell:- env_exports = (- "export PERSONHOG_ADDR='127.0.0.1:50052' PERSONHOG_ENABLED='true' PERSONHOG_ROLLOUT_PERCENTAGE='100'"- )+ env_exports = "export PERSONHOG_ADDR='127.0.0.1:50052'"proc_config["shell"] = f"{env_exports} && {original_shell}"return proc_configdiff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.pyindex dd87a0943268..e1e6c05f7950 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py@@ -869,11 +869,10 @@ class TestPersonhogEnvInjection:if proc_name not in config.procs:continueshell = config.procs[proc_name]["shell"]- for var in ["PERSONHOG_ADDR", "PERSONHOG_ENABLED", "PERSONHOG_ROLLOUT_PERCENTAGE"]:- if should_inject:- assert var in shell, f"{var} should be in {proc_name} shell"- else:- assert var not in shell, f"{var} should not be in {proc_name} shell"+ if should_inject:+ assert "PERSONHOG_ADDR" in shell, f"PERSONHOG_ADDR should be in {proc_name} shell"+ else:+ assert "PERSONHOG_ADDR" not in shell, f"PERSONHOG_ADDR should not be in {proc_name} shell"class TestParseExcludeInput: