: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(conversations): prefer identified persons in email person lookup (#71821)
Abhischek4901473d7182
diff --git a/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr b/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambrindex 06999649c0fa..42ba206626e3 100644--- a/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr+++ b/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr@@ -5,6 +5,8 @@persons.properties___email AS emailFROM(SELECT tupleElement(argMax(tuple(nullIf(nullIf(person.pmat_email, ''), 'null')), person.version), 1) AS properties___email,+ argMax(person.is_identified, person.version) AS is_identified,+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,person.id AS idFROM personWHERE and(equals(person.team_id, 99999), in(id,@@ -15,6 +17,9 @@HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE in(lower(persons.properties___email),['[email protected]'])+ ORDER BY persons.is_identified DESC,+ persons.created_at ASC,+ persons.id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -35,6 +40,8 @@persons.properties___email AS emailFROM(SELECT tupleElement(argMax(tuple(nullIf(nullIf(person.pmat_email, ''), 'null')), person.version), 1) AS properties___email,+ argMax(person.is_identified, person.version) AS is_identified,+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,person.id AS idFROM personWHERE and(equals(person.team_id, 99999), in(id,@@ -45,6 +52,9 @@HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE in(lower(persons.properties___email),['[email protected]'])+ ORDER BY persons.is_identified DESC,+ persons.created_at ASC,+ persons.id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 50734bf28d48..04941aa14d8b 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1494,6 +1494,30 @@ class TestTicketEmailFallbackPersonLookup(ClickhouseTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["results"][0]["person"] is None+ def test_lookup_prefers_identified_person_when_email_is_shared(self, mock_on_commit):+ # The stub is inserted first so that, without deterministic ordering, an+ # unordered read would return it first and win the first-match pick. Its only+ # distinct_id is the email address itself, which resolves no membership or+ # analytics groups downstream — the identified person must win.+ _create_person(+ team=self.team,+ distinct_ids=["[email protected]"],+ properties={"email": "[email protected]"},+ immediate=True,+ )+ identified = _create_person(+ team=self.team,+ distinct_ids=["real-app-distinct-id"],+ properties={"email": "[email protected]"},+ is_identified=True,+ immediate=True,+ )++ person = _get_persons_by_email(self.team, ["[email protected]"]).get("[email protected]")++ assert person is not None+ assert str(person.uuid) == str(identified.uuid)+@snapshot_clickhouse_queriesdef test_email_fallback_uses_bloom_filter_lower_skip_index(self, mock_on_commit):_create_person(diff --git a/products/conversations/backend/person_lookup.py b/products/conversations/backend/person_lookup.pyindex ae6d3b69d49b..0adbc8ea0427 100644--- a/products/conversations/backend/person_lookup.py+++ b/products/conversations/backend/person_lookup.py@@ -10,10 +10,16 @@ from posthog.models.team import Teamfrom posthog.personhog_client.caller_tag import personhog_caller_tag# Case-insensitive batch email lookup. Exposed so tests can EXPLAIN the exact query that runs.+# Identified persons sort first: several persons can share an email (e.g. an identified app+# user plus an email-only stub whose sole distinct_id is the address itself), and only the+# identified one carries distinct_ids that membership and analytics lookups can resolve.+# created_at prefers the oldest person, and id breaks same-millisecond ties so the+# pick is fully deterministic.PERSON_EMAIL_LOOKUP_QUERY = """SELECT id, properties.emailFROM personsWHERE lower(properties.email) IN {emails}+ORDER BY is_identified DESC, created_at ASC, id ASC"""@@ -24,10 +30,11 @@ def _get_persons_by_email() -> dict[str, Person]:"""Batch look up persons by their properties.email value via ClickHouse.- Returns a dict mapping lowercase email -> Person for the first match.- Only checks ``properties.email`` (the canonical, materialized key with- a skip index). Uses the HogQL ``persons`` virtual table (argMax dedup- handled automatically).+ Returns a dict mapping lowercase email -> Person, preferring identified+ persons over unidentified ones (oldest first within each). Only checks+ ``properties.email`` (the canonical, materialized key with a skip index).+ Uses the HogQL ``persons`` virtual table (argMax dedup handled+ automatically)."""if not emails:return {}