:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cohorts): pg fallback read email not supported (#60999)
Nick Bestd17134996a57
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex a62489a13ce1..ae1cc60438ee 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -14,6 +14,7 @@ from unittest import mockfrom unittest.mock import ANY, MagicMock, patchfrom django.core.files.uploadedfile import SimpleUploadedFile+from django.test import override_settingsfrom django.test.client import Clientfrom django.utils import timezone@@ -5408,11 +5409,18 @@ [email protected]content_type="application/csv",)- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts/",- {"name": "test_email_only", "csv": csv, "is_static": True},- format="multipart",- )+ # pmat_email materialized column doesn't exist in the test CH schema,+ # so we mock the CH lookup to return the expected UUIDs.+ with patch.object(+ Cohort,+ "_get_uuids_for_emails_batch_ch",+ return_value=[str(person1.uuid), str(person2.uuid)],+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {"name": "test_email_only", "csv": csv, "is_static": True},+ format="multipart",+ )self.assertEqual(response.status_code, 201)cohort = Cohort.objects.get(pk=response.json()["id"])@@ -5535,166 +5543,70 @@ Jane Smith,user456,[email protected]self.assertNotIn(str(person_with_email2.uuid), person_uuids_in_cohort)@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay", side_effect=calculate_cohort_from_list)- def test_static_cohort_csv_upload_respects_email_property_key_casing(self, patch_calculate_cohort_from_list):+ def test_static_cohort_csv_upload_email_lookup_uses_clickhouse(self, patch_calculate_cohort_from_list):"""- CSV upload with an email column matches against the exact property key from the CSV header.-- Before the fix: only the lowercase 'email' property key was queried.- After the fix: the property key matches the CSV header casing.-- Note: this exercises the Postgres path because the `cohort-email-lookup-clickhouse`- feature flag defaults off in tests. CH path coverage is handled separately below.+ CSV upload with an email column always uses the ClickHouse pmat_email+ materialized column for lookup, regardless of CSV header casing."""- # Create persons with different email property key casings- person_lowercase = Person.objects.create(- team=self.team, distinct_ids=["user_lowercase"], properties={"email": "[email protected]"}- )- person_titlecase = Person.objects.create(- team=self.team, distinct_ids=["user_titlecase"], properties={"Email": "[email protected]"}- )- person_uppercase = Person.objects.create(- team=self.team, distinct_ids=["user_uppercase"], properties={"EMAIL": "[email protected]"}- )-- # Test 1: CSV with lowercase 'email' header should match lowercase property- csv_lowercase = SimpleUploadedFile(- "email_lowercase.csv",- str.encode(-"""- ),- content_type="application/csv",+ person = Person.objects.create(+ team=self.team, distinct_ids=["user_email"], properties={"email": "[email protected]"})- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts/",- {"name": "test_email_lowercase", "csv": csv_lowercase, "is_static": True},- format="multipart",- )-- self.assertEqual(response.status_code, 201)- cohort_lowercase = Cohort.objects.get(pk=response.json()["id"])- people_in_cohort = Person.objects.filter(cohort__id=cohort_lowercase.pk, team_id=cohort_lowercase.team_id)- self.assertEqual(people_in_cohort.count(), 1)- self.assertIn(str(person_lowercase.uuid), {str(p.uuid) for p in people_in_cohort})-- # Test 2: CSV with title case 'Email' header should match title case property- csv_titlecase = SimpleUploadedFile(- "email_titlecase.csv",- str.encode(-"""- ),- content_type="application/csv",- )-- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts/",- {"name": "test_email_titlecase", "csv": csv_titlecase, "is_static": True},- format="multipart",- )-- self.assertEqual(response.status_code, 201)- cohort_titlecase = Cohort.objects.get(pk=response.json()["id"])- people_in_cohort = Person.objects.filter(cohort__id=cohort_titlecase.pk, team_id=cohort_titlecase.team_id)- self.assertEqual(people_in_cohort.count(), 1)- self.assertIn(str(person_titlecase.uuid), {str(p.uuid) for p in people_in_cohort})-- # Test 3: CSV with uppercase 'EMAIL' header should match uppercase property- csv_uppercase = SimpleUploadedFile(- "email_uppercase.csv",- str.encode(-"""- ),+ csv_file = SimpleUploadedFile(+ "emails.csv",+ str.encode("email\[email protected]\n"),content_type="application/csv",)- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts/",- {"name": "test_email_uppercase", "csv": csv_uppercase, "is_static": True},- format="multipart",- )+ # pmat_email materialized column doesn't exist in the test CH schema,+ # so we mock the CH lookup to return the expected UUID.+ with patch.object(+ Cohort,+ "_get_uuids_for_emails_batch_ch",+ return_value=[str(person.uuid)],+ ) as ch_mock:+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {"name": "test_email_ch", "csv": csv_file, "is_static": True},+ format="multipart",+ )+ ch_mock.assert_called_once()self.assertEqual(response.status_code, 201)- cohort_uppercase = Cohort.objects.get(pk=response.json()["id"])- people_in_cohort = Person.objects.filter(cohort__id=cohort_uppercase.pk, team_id=cohort_uppercase.team_id)+ 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_uppercase.uuid), {str(p.uuid) for p in people_in_cohort})-- # Test 4: CSV with mixed case emails should match their respective casings in a multi-column format- csv_mixed = SimpleUploadedFile(- "email_mixed.csv",- str.encode(- """name,Email-User 1,[email protected]-User 2,[email protected]-"""- ),- content_type="application/csv",- )-- response = self.client.post(- f"/api/projects/{self.team.id}/cohorts/",- {"name": "test_email_mixed", "csv": csv_mixed, "is_static": True},- format="multipart",- )+ self.assertIn(str(person.uuid), {str(p.uuid) for p in people_in_cohort})- self.assertEqual(response.status_code, 201)- cohort_mixed = Cohort.objects.get(pk=response.json()["id"])- people_in_cohort = Person.objects.filter(cohort__id=cohort_mixed.pk, team_id=cohort_mixed.team_id)-- # Should only find person_titlecase because CSV header is "Email" (title case)- # Before the fix, this would fail because it only looked at lowercase "email"- self.assertEqual(people_in_cohort.count(), 1)- person_uuids_in_cohort = {str(p.uuid) for p in people_in_cohort}- self.assertIn(str(person_titlecase.uuid), person_uuids_in_cohort)- self.assertNotIn(str(person_uppercase.uuid), person_uuids_in_cohort)- self.assertNotIn(str(person_lowercase.uuid), person_uuids_in_cohort)+ def test_insert_users_by_email_always_uses_clickhouse(self):+ cohort = Cohort.objects.create(team=self.team, name="ch-only", is_static=True)+ with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=[]) as ch_mock:+ cohort.insert_users_by_email(["[email protected]"], team_id=self.team.id)+ ch_mock.assert_called_once()@parameterized.expand([- ("default lowercase key uses CH", "email", True),- ("explicit lowercase key uses CH", "email", True),- ("titlecase key forces PG", "Email", False),- ("uppercase key forces PG", "EMAIL", False),+ ("lowercase", "email"),+ ("titlecase", "Email"),+ ("uppercase", "EMAIL"),+ ("none", None),])- @patch("posthog.models.cohort.cohort.posthoganalytics.feature_enabled", return_value=True)- def test_insert_users_by_email_routes_to_clickhouse_only_for_default_key(- self, _name, email_property_key, expects_ch, _patch_feature_flag- ):- cohort = Cohort.objects.create(team=self.team, name=f"ch-routing-{email_property_key}", is_static=True)- with (- patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=[]) as ch_mock,- patch.object(Cohort, "_get_uuids_for_emails_batch_pg", return_value=[]) as pg_mock,- ):+ def test_email_property_key_is_accepted_and_always_routes_to_clickhouse(self, _name, email_property_key):+ cohort = Cohort.objects.create(team=self.team, name="key-compat", is_static=True)+ with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=[]) as ch_mock:cohort.insert_users_by_email(["[email protected]"], team_id=self.team.id, email_property_key=email_property_key)+ ch_mock.assert_called_once()- if expects_ch:- ch_mock.assert_called_once()- pg_mock.assert_not_called()- else:- ch_mock.assert_not_called()- pg_mock.assert_called_once()- # Non-default keys must reach the PG helper with the exact casing from the caller.- # The model passes email_property_key positionally, so check args[2] with a kwarg fallback.- call_args = pg_mock.call_args- actual_key = call_args.kwargs.get(- "email_property_key", call_args.args[2] if len(call_args.args) > 2 else None- )- self.assertEqual(actual_key, email_property_key)-- @patch("posthog.models.cohort.cohort.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.models.cohort.cohort.sync_execute", side_effect=RuntimeError("CH down"))- def test_clickhouse_email_lookup_falls_back_to_postgres_on_failure(self, _patch_sync_execute, _patch_feature_flag):- # When the CH primitive raises, _get_uuids_for_emails_batch_ch swallows the exception- # and re-runs the lookup against Postgres with the default 'email' key.- cohort = Cohort.objects.create(team=self.team, name="ch-fallback", is_static=True)- with patch.object(Cohort, "_get_uuids_for_emails_batch_pg", return_value=[]) as pg_mock:+ @override_settings(DEBUG=False)+ def test_clickhouse_email_lookup_failure_records_error_on_cohort(self):+ cohort = Cohort.objects.create(team=self.team, name="ch-error", is_static=True)++ with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", side_effect=RuntimeError("CH down")):cohort.insert_users_by_email(["[email protected]"], team_id=self.team.id)- pg_mock.assert_called()+ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ self.assertIsNotNone(cohort.last_error_at)+ self.assertIsNone(cohort.last_calculation)diff --git a/posthog/models/cohort/cohort.py b/posthog/models/cohort/cohort.pyindex c95f9a686e02..e38aa82c0a82 100644--- a/posthog/models/cohort/cohort.py+++ b/posthog/models/cohort/cohort.py@@ -13,7 +13,6 @@ from django.dispatch import receiverfrom django.utils import timezoneimport structlog-import posthoganalyticsfrom posthog.schema import ProductKey@@ -531,146 +530,43 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):items: List of email addresses of users to be inserted into the cohort.team_id: ID of the team for which to insert the users. Defaults to `self.team`, because of a lot of existing usage in tests.batch_size: Number of records to process in each batch. Defaults to 1000.- email_property_key: Exact person property key (e.g., 'email', 'Email', 'EMAIL').- Defaults to 'email' when not provided.+ email_property_key: Accepted for backwards compatibility but ignored — all lookups+ use the ClickHouse pmat_email materialized column."""if team_id is None:team_id = self.team_id- if email_property_key is None:- email_property_key = "email"-if TEST:from posthog.test.base import flush_persons_and_events# Make sure persons are created in tests before running thisflush_persons_and_events()- # ClickHouse fast path is only wired up for the lowercase 'email' property- # (via the pmat_email materialized column), so non-default keys force the PG path.- use_clickhouse = email_property_key == "email" and posthoganalytics.feature_enabled(- "cohort-email-lookup-clickhouse",- str(team_id),- groups={"project": str(team_id)},- group_properties={- "project": {- "id": str(team_id),- }- },- send_feature_flag_events=False,- )-- # Process emails in batches to avoid memory issuesdef create_uuid_batch(batch_index: int, batch_size: int) -> list[str]:- """Create a batch of UUIDs from email addresses, excluding those already in cohort."""start_idx = batch_index * batch_sizeend_idx = start_idx + batch_size- batch_emails = items[start_idx:end_idx]- uuids = self._get_uuids_for_emails_batch(- batch_emails, team_id, email_property_key=email_property_key, use_clickhouse=use_clickhouse- )- return uuids+ return self._get_uuids_for_emails_batch_ch(items[start_idx:end_idx], team_id)- # Use FunctionBatchIterator to process emails in batchesbatch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))-- # Call the batching method with ClickHouse insertion enabledreturn self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)- def _get_uuids_for_emails_batch(- self, emails: list[str], team_id: int, email_property_key: str = "email", use_clickhouse: bool = False- ) -> list[str]:- """- Get UUIDs for a batch of email addresses, excluding those already in this cohort.-- Args:- emails: List of email addresses to convert to UUIDs- team_id: Team ID to filter by- email_property_key: Exact person property key to match against (e.g., 'email', 'Email', 'EMAIL').- use_clickhouse: Whether to use ClickHouse instead of PostgreSQL-- Returns:- List of UUIDs for persons with the given email addresses who are not already in this cohort- """- if not emails:- return []-- if use_clickhouse:- return self._get_uuids_for_emails_batch_ch(emails, team_id)-- return self._get_uuids_for_emails_batch_pg(emails, team_id, email_property_key)-- def _get_uuids_for_emails_batch_pg(- self, emails: list[str], team_id: int, email_property_key: str = "email"- ) -> list[str]:- """- Get UUIDs for email addresses using PostgreSQL (fallback path).-- Args:- emails: List of email addresses to convert to UUIDs- team_id: Team ID to filter by- email_property_key: Exact person property key to match against (e.g., 'email', 'Email', 'EMAIL').-- Returns:- List of UUIDs for persons with the given email addresses- """- if not emails:- return []-- filter_kwargs = {f"properties__{email_property_key}__in": emails}-- uuids = [- str(uuid)- for uuid in Person.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id)- .filter(**filter_kwargs)- .values_list("uuid", flat=True)- ]- return uuids-def _get_uuids_for_emails_batch_ch(self, emails: list[str], team_id: int) -> list[str]:- """- Get UUIDs for email addresses using ClickHouse (fast path).- Uses direct ClickHouse SQL for optimal performance.-- Note: This method currently only supports the lowercase 'email' property key- via the pmat_email materialized column.-- Args:- emails: List of email addresses to convert to UUIDs- team_id: Team ID to filter by-- Returns:- List of UUIDs for persons with the given email addresses- """if not emails:return []- try:- # Use optimized ClickHouse query with GROUP BY HAVING- query = """- SELECT person.id- FROM person- WHERE person.team_id = %(team_id)s- AND person.pmat_email IN %(emails)s- GROUP BY person.id- HAVING argMax(person.is_deleted, person.version) = 0- SETTINGS optimize_aggregation_in_order = 1- """-- tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)- result = sync_execute(query, {"team_id": team_id, "emails": emails})- return [str(row[0]) for row in result]+ query = """+ SELECT person.id+ FROM person+ WHERE person.team_id = %(team_id)s+ AND person.pmat_email IN %(emails)s+ GROUP BY person.id+ HAVING argMax(person.is_deleted, person.version) = 0+ SETTINGS optimize_aggregation_in_order = 1+ """- except Exception:- # Log error before falling back to PostgreSQL- logger.exception(- "ClickHouse email lookup failed, falling back to PostgreSQL",- team_id=team_id,- email_count=len(emails),- )- # Fallback to PostgreSQL method (CH path is only used for the default 'email' key)- return self._get_uuids_for_emails_batch_pg(emails, team_id)+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)+ result = sync_execute(query, {"team_id": team_id, "emails": emails})+ return [str(row[0]) for row in result]def insert_users_list_by_uuid_into_pg_only(self,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.ambrindex bff2cb8a4a1d..d98a6963a37c 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@@ -481,9 +481,7 @@'__str__','_get_existing_ch_member_uuids','_get_uuids_for_distinct_ids_batch',- '_get_uuids_for_emails_batch','_get_uuids_for_emails_batch_ch',- '_get_uuids_for_emails_batch_pg','_insert_batch_via_personhog','_insert_users_list_with_batching','_meta',