Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(django): migrate a couple cohort orm paths (#60977)

Nick Best6914856134c5
diff --git a/posthog/models/cohort/cohort.py b/posthog/models/cohort/cohort.py
index 589e24a41dd0..e5001b70c199 100644
--- a/posthog/models/cohort/cohort.py
+++ b/posthog/models/cohort/cohort.py
@@ -26,9 +26,8 @@ from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.filters.filter import Filter
-from posthog.models.person import Person, PersonDistinctId
-from posthog.models.person.person import READ_DB_FOR_PERSONS
-from posthog.models.person.util import get_person_by_uuid, get_persons_by_distinct_ids
+from posthog.models.person import Person
+from posthog.models.person.util import get_person_by_uuid
from posthog.models.property import Property, PropertyGroup
from posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr
from posthog.settings.base_variables import TEST
@@ -59,10 +58,6 @@ REALTIME_COHORT_MAX_PERSON_COUNT = 20_000_000
logger = structlog.get_logger(__name__)
-DELETE_QUERY = """
-DELETE FROM "posthog_cohortpeople" WHERE "cohort_id" = {cohort_id}
-"""
-
DEFAULT_COHORT_INSERT_BATCH_SIZE = 1000
@@ -419,50 +414,6 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
duration=(time.monotonic() - start_time),
)
- def _get_uuids_for_distinct_ids_batch(self, distinct_ids: list[str], team_id: int) -> list[str]:
- """
- Get UUIDs for a batch of distinct IDs, excluding those already in this cohort.
-
- Args:
- distinct_ids: List of distinct IDs to convert to UUIDs
- team_id: Team ID to filter by
-
- Remarks:
- This used to be a single query with a complex JOIN, but that query was timing out.
- So we split it into two queries that are much simpler and should hopefully not time out.
-
- Returns:
- List of UUIDs for persons with the given distinct IDs who are not already in this cohort
- """
- if not distinct_ids:
- return []
-
- # Get person UUIDs for this batch of distinct IDs.
- # This is limited to the batch size so it will be no more than 1000 items in-memory at a time.
- # You're going to be tempted to exclude people already in the cohort, but that's not only NOT
- # necessary, but it leads to query timeouts. The insert_users_list_by_uuid handles ensuring we
- # don't insert people that are already in the cohort efficiently.
- from posthog.personhog_client.gate import use_personhog
-
- if use_personhog():
- persons = get_persons_by_distinct_ids(team_id, list(distinct_ids))
- return [str(person.uuid) for person in persons]
-
- # ORM path: lightweight values_list queries — no full model instantiation
- person_ids_qs = (
- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm
- .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) # nosemgrep: no-direct-persons-db-orm
- .filter(team_id=team_id, id__in=person_ids_qs)
- .values_list("uuid", flat=True)
- ]
-
def insert_users_by_list(
self,
items: list[str],
@@ -487,19 +438,14 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
# Make sure persons are created in tests before running this
flush_persons_and_events()
- # Process distinct IDs in batches to avoid memory issues
def create_uuid_batch(batch_index: int, batch_size: int) -> list[str]:
- """Create a batch of UUIDs from distinct IDs, excluding those already in cohort."""
+ from posthog.models.person.util import get_person_uuids_by_distinct_ids
+
start_idx = batch_index * batch_size
end_idx = start_idx + batch_size
- batch_distinct_ids = items[start_idx:end_idx]
+ return get_person_uuids_by_distinct_ids(team_id, items[start_idx:end_idx])
- return self._get_uuids_for_distinct_ids_batch(batch_distinct_ids, team_id)
-
- # Use FunctionBatchIterator to process distinct IDs in batches
batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))
-
- # Call the batching method with ClickHouse insertion enabled
return self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)
def insert_users_list_by_uuid(
diff --git a/posthog/models/cohort/test/test_cohort_personhog.py b/posthog/models/cohort/test/test_cohort_personhog.py
index 091a42c7d944..191eb899203f 100644
--- a/posthog/models/cohort/test/test_cohort_personhog.py
+++ b/posthog/models/cohort/test/test_cohort_personhog.py
@@ -15,30 +15,29 @@ from posthog.personhog_client.test_helpers import PersonhogTestMixin
@parameterized_class(("personhog",), [(False,), (True,)])
-class TestGetUuidsForDistinctIdsBatch(PersonhogTestMixin, BaseTest):
- def _create_static_cohort(self) -> Cohort:
- return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")
+class TestGetPersonUuidsByDistinctIds(PersonhogTestMixin, 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 = self._seed_person(team=self.team, distinct_ids=["d1", "d2"])
p2 = self._seed_person(team=self.team, distinct_ids=["d3"])
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch(["d1", "d3"], team_id=self.team.pk)
+ result = self._get_uuids(["d1", "d3"])
assert set(result) == {str(p1.uuid), str(p2.uuid)}
self._assert_personhog_called("get_persons_by_distinct_ids_in_team")
def test_returns_empty_list_for_empty_input(self):
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch([], team_id=self.team.pk)
+ result = self._get_uuids([])
assert result == []
self._assert_personhog_not_called("get_persons_by_distinct_ids_in_team")
def test_returns_empty_list_when_no_persons_match(self):
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch(["nonexistent"], team_id=self.team.pk)
+ result = self._get_uuids(["nonexistent"])
assert result == []
@@ -46,50 +45,72 @@ class TestGetUuidsForDistinctIdsBatch(PersonhogTestMixin, BaseTest):
other_team = self.organization.teams.create(name="Other Team")
self._seed_person(team=other_team, distinct_ids=["d1"])
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch(["d1"], team_id=self.team.pk)
+ result = self._get_uuids(["d1"])
assert result == []
def test_deduplicates_persons_with_multiple_distinct_ids(self):
p = self._seed_person(team=self.team, distinct_ids=["d1", "d2", "d3"])
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch(["d1", "d2", "d3"], team_id=self.team.pk)
+ result = self._get_uuids(["d1", "d2", "d3"])
assert result == [str(p.uuid)]
def test_handles_mix_of_found_and_missing_distinct_ids(self):
p = self._seed_person(team=self.team, distinct_ids=["exists"])
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch(["exists", "missing1", "missing2"], team_id=self.team.pk)
+ result = self._get_uuids(["exists", "missing1", "missing2"])
assert result == [str(p.uuid)]
def test_multiple_persons_each_with_single_distinct_id(self):
persons = [self._seed_person(team=self.team, distinct_ids=[f"d{i}"]) for i in range(5)]
- cohort = self._create_static_cohort()
- result = cohort._get_uuids_for_distinct_ids_batch([f"d{i}" for i in range(5)], team_id=self.team.pk)
+ result = self._get_uuids([f"d{i}" for i in range(5)])
assert set(result) == {str(p.uuid) for p in persons}
-class TestGetUuidsForDistinctIdsBatchFallback(BaseTest):
+class TestGetPersonUuidsByDistinctIdsFallback(BaseTest):
"""Routing test: verifies ORM fallback when the personhog gate is disabled."""
def test_falls_back_to_orm_when_personhog_disabled(self):
+ from posthog.models.person.util import get_person_uuids_by_distinct_ids
+
p = Person.objects.create(team=self.team, distinct_ids=["d1"])
- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")
with fake_personhog_client(gate_enabled=False) as fake:
- result = cohort._get_uuids_for_distinct_ids_batch(["d1"], team_id=self.team.pk)
+ result = get_person_uuids_by_distinct_ids(self.team.pk, ["d1"])
assert result == [str(p.uuid)]
fake.assert_not_called("get_persons_by_distinct_ids_in_team")
+class TestGetPersonUuidsByDistinctIdsFieldMask(BaseTest):
+ """Verify the personhog path sends a UUID-only field mask."""
+
+ def test_sends_uuid_only_field_mask(self):
+ from posthog.models.person.util import get_person_uuids_by_distinct_ids
+
+ p = Person.objects.create(team=self.team, distinct_ids=["d1"])
+
+ with fake_personhog_client(gate_enabled=True) as fake:
+ fake.add_person(
+ team_id=self.team.pk,
+ person_id=p.pk,
+ uuid=str(p.uuid),
+ distinct_ids=["d1"],
+ )
+ get_person_uuids_by_distinct_ids(self.team.pk, ["d1"])
+
+ 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
+
+
@parameterized_class(("personhog",), [(False,), (True,)])
class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):
CLASS_DATA_LEVEL_SETUP = False
diff --git a/posthog/models/person/test/test_batched_personhog_helpers.py b/posthog/models/person/test/test_batched_personhog_helpers.py
index cf61b52e8064..aba655223769 100644
--- a/posthog/models/person/test/test_batched_personhog_helpers.py
+++ b/posthog/models/person/test/test_batched_personhog_helpers.py
@@ -11,6 +11,7 @@ from posthog.models.person.util import (
get_persons_mapped_by_distinct_id,
)
from posthog.personhog_client.fake_client import fake_personhog_client
+from posthog.personhog_client.proto import ReadOptions
from posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2
@@ -180,6 +181,38 @@ class TestBatchedGetPersonsByDistinctIds(SimpleTestCase):
assert len(result) == 1
+ def test_forwards_read_options_to_request(self):
+ opts = ReadOptions(field_mask=["uuid", "id", "team_id"])
+ with fake_personhog_client() as fake:
+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["did-1"])
+
+ _batched_get_persons_by_distinct_ids(1, ["did-1"], "test", read_options=opts)
+
+ calls = fake.assert_called("get_persons_by_distinct_ids_in_team", times=1)
+ assert list(calls[0].request.read_options.field_mask) == ["uuid", "id", "team_id"]
+
+ def test_no_read_options_by_default(self):
+ with fake_personhog_client() as fake:
+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["did-1"])
+
+ _batched_get_persons_by_distinct_ids(1, ["did-1"], "test")
+
+ calls = fake.assert_called("get_persons_by_distinct_ids_in_team", times=1)
+ assert list(calls[0].request.read_options.field_mask) == []
+
+ @patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2)
+ def test_read_options_forwarded_to_all_batches(self):
+ opts = ReadOptions(field_mask=["uuid"])
+ with fake_personhog_client() as fake:
+ for i in range(3):
+ fake.add_person(team_id=1, person_id=i + 1, uuid=f"uuid-{i}", distinct_ids=[f"did-{i}"])
+
+ _batched_get_persons_by_distinct_ids(1, ["did-0", "did-1", "did-2"], "test", read_options=opts)
+
+ calls = fake.assert_called("get_persons_by_distinct_ids_in_team", times=2)
+ for call in calls:
+ assert list(call.request.read_options.field_mask) == ["uuid"]
+
class TestBatchedGetDistinctIdsForPersons(SimpleTestCase):
@parameterized.expand(
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 0a38cdeee58a..506476c1fadc 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -46,6 +46,7 @@ from posthog.personhog_client.proto import (
GetPersonRequest,
GetPersonsByDistinctIdsInTeamRequest,
GetPersonsByUuidsRequest,
+ ReadOptions,
)
from posthog.settings import TEST
@@ -96,6 +97,7 @@ def _batched_get_persons_by_distinct_ids(
distinct_ids: list[str],
operation: str,
deduplicate_by_person: bool = True,
+ read_options: ReadOptions | None = None,
) -> list[person_pb2.PersonWithDistinctIds]:
client = _get_client()
seen_person_ids: set[int] = set()
@@ -104,7 +106,7 @@ def _batched_get_persons_by_distinct_ids(
for i in range(0, len(distinct_ids), PERSONHOG_BATCH_SIZE):
batch = distinct_ids[i : i + PERSONHOG_BATCH_SIZE]
resp = client.get_persons_by_distinct_ids_in_team(
- GetPersonsByDistinctIdsInTeamRequest(team_id=team_id, distinct_ids=batch)
+ GetPersonsByDistinctIdsInTeamRequest(team_id=team_id, distinct_ids=batch, read_options=read_options)
)
present_results = [r for r in resp.results if r.person and r.person.id]
@@ -607,6 +609,49 @@ def validate_person_uuids_exist(team_id: int, uuids: list[str]) -> list[str]:
)
+_UUID_ONLY_READ_OPTIONS = ReadOptions(field_mask=["uuid", "id", "team_id"])
+
+
+def get_person_uuids_by_distinct_ids(team_id: int, distinct_ids: list[str]) -> list[str]:
+ """Return person UUIDs for the given distinct IDs.
+
+ Lightweight UUID-only variant — uses field masking to skip fetching
+ properties and other heavy fields from personhog.
+ """
+ if not distinct_ids:
+ return []
+
+ def personhog_fn() -> list[str]:
+ results = _batched_get_persons_by_distinct_ids(
+ team_id,
+ distinct_ids,
+ "get_person_uuids_by_distinct_ids",
+ read_options=_UUID_ONLY_READ_OPTIONS,
+ )
+ 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(
+ "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.
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index d98a6963a37c..ef19ca2debf4 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -480,7 +480,6 @@
'__repr__',
'__str__',
'_get_existing_ch_member_uuids',
- '_get_uuids_for_distinct_ids_batch',
'_get_uuids_for_emails_batch_ch',
'_insert_batch_via_personhog',
'_insert_users_list_with_batching',