: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(customer-analytics): match Gmail emails to account members (#94201)
Arthur Moreira de Deusc206de2ee507
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 04b18dd9e24a..b1d1c7316225 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -21,6 +21,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom temporalio.service import RPCErrorfrom posthog.models.comment import Comment+from posthog.models.integration import Integrationfrom posthog.models.team import Teamfrom posthog.temporal.common.client import sync_connect@@ -464,15 +465,50 @@ def list_email_threads_for_account_matching(if after_id is not None:threads = threads.filter(id__gt=after_id)- return [- EmailThreadForAccountMatching(- id=str(thread.id),- participant_emails=[- participant.email for participant in cast(list[EmailThreadParticipant], thread.customer_participants)- ],+ thread_page = list(threads.order_by("id")[:limit])+ gmail_sources_by_thread_id: dict[str, list[str]] = {}+ integration_ids: set[int] = set()+ invalid_source_thread_ids: set[str] = set()+ for thread_id, source_id in (+ EmailThreadMessage.objects.for_team(team_id)+ .filter(thread_id__in=[thread.id for thread in thread_page], source_type="gmail")+ .values_list("thread_id", "source_id")+ ):+ normalized_thread_id = str(thread_id)+ gmail_sources_by_thread_id.setdefault(normalized_thread_id, []).append(source_id)+ integration_id, separator, message_id = source_id.partition(":")+ if not separator or not integration_id.isdigit() or not message_id:+ invalid_source_thread_ids.add(normalized_thread_id)+ continue+ integration_ids.add(int(integration_id))++ integration_owner_ids = dict(+ Integration.objects.filter(+ team_id=team_id,+ id__in=integration_ids,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ ).values_list("id", "created_by_id")+ )+ matching_threads: list[EmailThreadForAccountMatching] = []+ for thread in thread_page:+ normalized_thread_id = str(thread.id)+ gmail_owner_id: int | None = None+ source_ids = gmail_sources_by_thread_id.get(normalized_thread_id, [])+ if source_ids and normalized_thread_id not in invalid_source_thread_ids:+ owner_ids = {integration_owner_ids.get(int(source_id.partition(":")[0])) for source_id in source_ids}+ if None not in owner_ids and len(owner_ids) == 1:+ gmail_owner_id = owner_ids.pop()+ matching_threads.append(+ EmailThreadForAccountMatching(+ id=normalized_thread_id,+ participant_emails=[+ participant.email+ for participant in cast(list[EmailThreadParticipant], thread.customer_participants)+ ],+ gmail_owner_id=gmail_owner_id,+ ))- for thread in threads.order_by("id")[:limit]- ]+ return matching_threads@transaction.atomicdiff --git a/products/conversations/backend/facade/types.py b/products/conversations/backend/facade/types.pyindex 8d7d3f5de54e..6c8a2844a3f6 100644--- a/products/conversations/backend/facade/types.py+++ b/products/conversations/backend/facade/types.py@@ -73,6 +73,7 @@ class EmailThreadAccountLinkInput:class EmailThreadForAccountMatching:id: strparticipant_emails: list[str]+ gmail_owner_id: int | None@dataclass(frozen=True)diff --git a/products/conversations/backend/migrations/0064_alter_emailthreadaccountlink_match_source.py b/products/conversations/backend/migrations/0064_alter_emailthreadaccountlink_match_source.pynew file mode 100644index 000000000000..662487283f8b--- /dev/null+++ b/products/conversations/backend/migrations/0064_alter_emailthreadaccountlink_match_source.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.17 on 2026-09-03 12:46++from django.db import migrations, models++import products.conversations.backend.models.email_thread+++class Migration(migrations.Migration):+ dependencies = [("conversations", "0063_emailmessagemapping_full_body_plain")]++ operations = [+ migrations.AlterField(+ model_name="emailthreadaccountlink",+ name="match_source",+ field=models.CharField(+ choices=products.conversations.backend.models.email_thread.email_thread_account_match_source_choices,+ max_length=32,+ ),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex 9395c1e8d242..43d1b287dfce 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0063_emailmessagemapping_full_body_plain+0064_alter_emailthreadaccountlink_match_sourcediff --git a/products/conversations/backend/models/email_thread.py b/products/conversations/backend/models/email_thread.pyindex 00c1fbbe2ca8..56d6a5bc84c7 100644--- a/products/conversations/backend/models/email_thread.py+++ b/products/conversations/backend/models/email_thread.py@@ -1,4 +1,5 @@from django.db import models+from django.utils.functional import Promisefrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel@@ -9,9 +10,14 @@ EMAIL_THREAD_COMMENT_SCOPE = "EmailThread"class EmailThreadAccountMatchSource(models.TextChoices):KNOWN_EMAIL = "known_email", "Known email"PERSON_GROUP = "person_group", "Person group"+ ORGANIZATION_MEMBER = "organization_member", "Organization member"EMAIL_DOMAIN = "email_domain", "Email domain"+def email_thread_account_match_source_choices() -> list[tuple[str, str | Promise]]:+ return list(EmailThreadAccountMatchSource.choices)++class EmailThreadMessageDirection(models.TextChoices):INBOUND = "inbound", "Inbound"OUTBOUND = "outbound", "Outbound"@@ -51,7 +57,7 @@ class EmailThreadAccountLink(TeamScopedRootMixin, UUIDModel):thread = models.ForeignKey("conversations.EmailThread", on_delete=models.CASCADE, related_name="account_links")account_id = models.CharField(max_length=64)account_external_id = models.CharField(max_length=400, null=True, blank=True)- match_source = models.CharField(max_length=32, choices=EmailThreadAccountMatchSource.choices)+ match_source = models.CharField(max_length=32, choices=email_thread_account_match_source_choices)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/conversations/backend/tests/test_email_thread_account_links.py b/products/conversations/backend/tests/test_email_thread_account_links.pyindex 71118fe26af0..44924bbe6d85 100644--- a/products/conversations/backend/tests/test_email_thread_account_links.py+++ b/products/conversations/backend/tests/test_email_thread_account_links.py@@ -5,6 +5,9 @@ from posthog.test.base import BaseTestfrom django.utils import timezonefrom posthog.models.comment import Comment+from posthog.models.integration import Integration+from posthog.models.team import Team+from posthog.models.user import Userfrom products.conversations.backend.facade.api import (list_account_email_thread_messages,@@ -77,6 +80,7 @@ class TestEmailThreadAccountLinks(BaseTest):matching_threads = list_email_threads_for_account_matching(self.team.id)assert len(matching_threads) == 1assert matching_threads[0].participant_emails == ["[email protected]"]+ assert matching_threads[0].gmail_owner_id is Nonereplace_email_thread_account_links(self.team.id,@@ -148,7 +152,7 @@ class TestEmailThreadAccountLinks(BaseTest):EmailThreadAccountLinkInput(account_id="account-2",account_external_id="renamed-group-2",- match_source="person_group",+ match_source="organization_member",)],)@@ -156,5 +160,97 @@ class TestEmailThreadAccountLinks(BaseTest):assert not EmailThreadAccountLink.objects.for_team(self.team.id).filter(account_id="account-1").exists()remaining = EmailThreadAccountLink.objects.for_team(self.team.id).get()assert remaining.account_external_id == "renamed-group-2"- assert remaining.match_source == "person_group"+ assert remaining.match_source == "organization_member"assert list_account_email_thread_messages(self.team.id, "account-1", str(self.thread.id)) is None++ def test_resolves_one_gmail_owner_across_integrations(self) -> None:+ first_integration = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="first-gmail-owner",+ created_by=self.user,+ )+ second_integration = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="second-gmail-owner",+ created_by=self.user,+ )+ self.message.source_type = "gmail"+ self.message.source_id = f"{first_integration.id}:gmail-message-1"+ self.message.save(update_fields=["source_type", "source_id"])+ second_comment = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(self.thread.id),+ content="Second message",+ )+ second_message = EmailThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ comment=second_comment,+ message_id="<[email protected]>",+ sent_at=self.message.sent_at + timedelta(minutes=1),+ sender_email="[email protected]",+ to_recipients=[],+ cc_recipients=[],+ direction=EmailThreadMessageDirection.INBOUND,+ source_type="gmail",+ source_id=f"{second_integration.id}:gmail-message-2",+ )++ [matching_thread] = list_email_threads_for_account_matching(self.team.id)++ assert matching_thread.gmail_owner_id == self.user.id++ other_owner = User.objects.create(email="[email protected]")+ other_integration = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="other-gmail-owner",+ created_by=other_owner,+ )+ second_message.source_id = f"{other_integration.id}:gmail-message-2"+ second_message.save(update_fields=["source_id"])++ [matching_thread] = list_email_threads_for_account_matching(self.team.id)++ assert matching_thread.gmail_owner_id is None++ def test_rejects_invalid_or_unowned_gmail_sources(self) -> None:+ unowned_integration = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="unowned-gmail",+ created_by=None,+ )+ other_team = Team.objects.create(organization=self.organization)+ other_team_integration = Integration.objects.create(+ team=other_team,+ kind="google-calendar",+ integration_id="other-team-gmail",+ created_by=self.user,+ )+ other_kind_integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="not-gmail",+ created_by=self.user,+ )+ self.message.source_type = "gmail"+ self.message.save(update_fields=["source_type"])++ for source_id in (+ "malformed",+ "999999999:gmail-message",+ f"{unowned_integration.id}:gmail-message",+ f"{other_team_integration.id}:gmail-message",+ f"{other_kind_integration.id}:gmail-message",+ ):+ with self.subTest(source_id=source_id):+ self.message.source_id = source_id+ self.message.save(update_fields=["source_id"])++ [matching_thread] = list_email_threads_for_account_matching(self.team.id)++ assert matching_thread.gmail_owner_id is Nonediff --git a/products/customer_analytics/backend/facade/email_matching.py b/products/customer_analytics/backend/facade/email_matching.pyindex 486610a7fef0..1280a2cdcd2f 100644--- a/products/customer_analytics/backend/facade/email_matching.py+++ b/products/customer_analytics/backend/facade/email_matching.py@@ -5,19 +5,22 @@ import structlogfrom celery import current_appfrom posthog.models.team import Team+from posthog.models.user import Userfrom products.conversations.backend.facade import api as conversations-from products.conversations.backend.facade.types import EmailThreadAccountLinkInput+from products.conversations.backend.facade.types import EmailThreadAccountLinkInput, EmailThreadForAccountMatchingfrom products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.logic.account_member_search import is_account_member_search_enabledfrom products.customer_analytics.backend.logic.email_account_matching import (MatchedAccount,match_accounts_for_emails,+ match_accounts_for_gmail_emails,normalize_emails,)logger = structlog.get_logger(__name__)-_MATCH_SOURCE_PRIORITY = {"known_email": 0, "person_group": 1, "email_domain": 2}+_MATCH_SOURCE_PRIORITY = {"known_email": 0, "person_group": 1, "organization_member": 2, "email_domain": 3}_RECALCULATION_TASK = "customer_analytics.recalculate_email_thread_account_links"_RECALCULATION_THREADS_TASK = "customer_analytics.recalculate_email_thread_account_links_for_threads"_RECALCULATION_LOCK_SECONDS = 15 * 60@@ -134,16 +137,27 @@ def recalculate_email_thread_links(if not threads:return processed- # One matcher pass per page, not per thread: participants and domains that recur- # across a customer's threads collapse into a single set of queries.- page_matches = match_accounts_for_emails(- team, [email for thread in threads for email in thread.participant_emails]- )+ owner_ids = {thread.gmail_owner_id for thread in threads if thread.gmail_owner_id is not None}+ owners_by_id = User.objects.in_bulk(owner_ids)+ enabled_owner_ids = {+ owner_id for owner_id, owner in owners_by_id.items() if is_account_member_search_enabled(team, owner)+ }+ threads_by_member_search: dict[bool, list[EmailThreadForAccountMatching]] = {}+ for thread in threads:+ member_search_enabled = thread.gmail_owner_id in enabled_owner_ids+ threads_by_member_search.setdefault(member_search_enabled, []).append(thread)+ matches_by_member_search = {+ member_search_enabled: (+ match_accounts_for_gmail_emails if member_search_enabled else match_accounts_for_emails+ )(team, [email for thread in matching_threads for email in thread.participant_emails])+ for member_search_enabled, matching_threads in threads_by_member_search.items()+ }for thread in threads:+ group_matches = matches_by_member_search[thread.gmail_owner_id in enabled_owner_ids]thread_matches = {- email: page_matches[email]+ email: group_matches[email]for email in normalize_emails(thread.participant_emails)- if email in page_matches+ if email in group_matches}matches = _dedupe_account_matches(thread_matches)conversations.replace_email_thread_account_links(diff --git a/products/customer_analytics/backend/logic/account_member_search.py b/products/customer_analytics/backend/logic/account_member_search.pyindex 7426e4669f23..ad4bc9b4eff1 100644--- a/products/customer_analytics/backend/logic/account_member_search.py+++ b/products/customer_analytics/backend/logic/account_member_search.py@@ -21,12 +21,16 @@ ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS = 100EU_ORGANIZATION_MEMBERS_VIEW = "eu_org_members"-def _is_account_member_search_enabled(team: Team, user: User) -> bool:- return user.is_staff and posthog_feature_flag_enabled(- CUSTOMER_ANALYTICS_CSP_FLAG,- str(user.distinct_id),- organization_id=team.organization_id,- team_id=team.id,+def is_account_member_search_enabled(team: Team, user: User) -> bool:+ return (+ user.is_active+ and user.is_staff+ and posthog_feature_flag_enabled(+ CUSTOMER_ANALYTICS_CSP_FLAG,+ str(user.distinct_id),+ organization_id=team.organization_id,+ team_id=team.id,+ ))@@ -84,7 +88,7 @@ def _list_eu_organization_ids(team: Team, user: User, email: str) -> tuple[str,def list_account_external_ids_by_member_email(*, team: Team, user: User, email: str) -> tuple[str, ...]:- if not _is_account_member_search_enabled(team, user):+ if not is_account_member_search_enabled(team, user):return ()organization_ids = _list_us_organization_ids(email)diff --git a/products/customer_analytics/backend/logic/email_account_matching.py b/products/customer_analytics/backend/logic/email_account_matching.pyindex 8063d7e0d6a8..2bb2470dad9a 100644--- a/products/customer_analytics/backend/logic/email_account_matching.py+++ b/products/customer_analytics/backend/logic/email_account_matching.py@@ -1,8 +1,14 @@+from collections.abc import Callablefrom dataclasses import dataclass+from django.db.models import QuerySet+from django.db.models.functions import Lower+import structlog+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team+from posthog.models.user import Userfrom products.conversations.backend.facade.api import resolve_group_keys_by_emailfrom products.customer_analytics.backend.models import Account@@ -11,6 +17,7 @@ logger = structlog.get_logger(__name__)KNOWN_EMAIL_MATCH = "known_email"PERSON_GROUP_MATCH = "person_group"+ORGANIZATION_MEMBER_MATCH = "organization_member"EMAIL_DOMAIN_MATCH = "email_domain"@@ -33,48 +40,152 @@ def normalize_emails(emails: list[str]) -> set[str]:return {email.strip().lower() for email in emails if "@" in email}-def match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, MatchedAccount]:- normalized_emails = sorted(normalize_emails(emails))- if not normalized_emails:- return {}+def _find_accounts_by_known_email(team: Team, email: str) -> QuerySet[Account]:+ return Account.objects.for_team(team.id).filter(_properties__known_emails__contains=[email])+++def _find_accounts_by_email_domain(team: Team, domain: str) -> QuerySet[Account]:+ return Account.objects.for_team(team.id).filter(_properties__email_domains__contains=[domain])- matched: dict[str, MatchedAccount] = {}- ambiguous: set[str] = set()- for email in normalized_emails:- candidates = list(Account.objects.for_team(team.id).filter(_properties__known_emails__contains=[email])[:2])+def _match_accounts_by_account_property(+ team: Team,+ emails: list[str],+ *,+ find_accounts: Callable[[Team, str], QuerySet[Account]],+ source: str,+ value_for_email: Callable[[str], str],+) -> tuple[dict[str, MatchedAccount], set[str]]:+ matches: dict[str, MatchedAccount] = {}+ ambiguous: set[str] = set()+ for email in emails:+ value = value_for_email(email)+ candidates = list(find_accounts(team, value)[:2])if len(candidates) == 1:- matched[email] = MatchedAccount(account=candidates[0], source=KNOWN_EMAIL_MATCH)+ matches[email] = MatchedAccount(account=candidates[0], source=source)elif len(candidates) > 1:ambiguous.add(email)- _record_ambiguity(team_id=team.id, source=KNOWN_EMAIL_MATCH, candidate_count=len(candidates))+ _record_ambiguity(team_id=team.id, source=source, candidate_count=len(candidates))+ return matches, ambiguous++def _match_accounts_by_person_group(team: Team, emails: list[str]) -> tuple[dict[str, MatchedAccount], set[str]]:group_type_index = team.customer_analytics_config.account_group_type_index- if group_type_index is not None:- unresolved = [email for email in normalized_emails if email not in matched and email not in ambiguous]- email_to_group_key = resolve_group_keys_by_email(team.id, unresolved, group_type_index)- group_keys = {group_key for group_key in email_to_group_key.values() if group_key is not None}- accounts_by_external_id = {- account.external_id: account- for account in Account.objects.for_team(team.id).filter(external_id__in=group_keys)- }- for email, group_key in email_to_group_key.items():- if group_key is None:- ambiguous.add(email)- _record_ambiguity(team_id=team.id, source=PERSON_GROUP_MATCH, candidate_count=None)- continue- account = accounts_by_external_id.get(group_key)- if account is not None:- matched[email] = MatchedAccount(account=account, source=PERSON_GROUP_MATCH)-- for email in normalized_emails:- if email in matched or email in ambiguous:+ if group_type_index is None:+ return {}, set()++ matches: dict[str, MatchedAccount] = {}+ ambiguous: set[str] = set()+ email_to_group_key = resolve_group_keys_by_email(team.id, emails, group_type_index)+ group_keys = {group_key for group_key in email_to_group_key.values() if group_key is not None}+ accounts_by_external_id = {+ account.external_id: account for account in Account.objects.for_team(team.id).filter(external_id__in=group_keys)+ }+ for email, group_key in email_to_group_key.items():+ if group_key is None:+ ambiguous.add(email)+ _record_ambiguity(team_id=team.id, source=PERSON_GROUP_MATCH, candidate_count=None)+ continue+ account = accounts_by_external_id.get(group_key)+ if account is not None:+ matches[email] = MatchedAccount(account=account, source=PERSON_GROUP_MATCH)+ return matches, ambiguous+++def _match_accounts_by_organization_membership(+ team: Team, emails: list[str]+) -> tuple[dict[str, MatchedAccount], set[str]]:+ member_emails = [email for email in emails if email.rsplit("@", 1)[-1] != "posthog.com"]+ users_by_email: dict[str, list[User]] = {}+ for user in (+ User.objects.annotate(normalized_email=Lower("email"))+ .filter(normalized_email__in=member_emails, is_active=True)+ .only("id", "email")+ ):+ users_by_email.setdefault(user.email.lower(), []).append(user)++ ambiguous = {email for email, users in users_by_email.items() if len(users) > 1}+ users_by_id = {users[0].id: users[0] for email, users in users_by_email.items() if email not in ambiguous}+ if not users_by_id:+ return {}, ambiguous++ memberships = list(OrganizationMembership.objects.filter(user_id__in=users_by_id))+ accounts_by_organization_id = {+ account.external_id: account+ for account in Account.objects.for_team(team.id).filter(+ external_id__in={str(membership.organization_id) for membership in memberships}+ )+ if account.external_id is not None+ }++ candidates_by_email: dict[str, dict[str, Account]] = {}+ for membership in memberships:+ account = accounts_by_organization_id.get(str(membership.organization_id))+ if account is None:continue- domain = email.rsplit("@", 1)[-1]- candidates = list(Account.objects.for_team(team.id).filter(_properties__email_domains__contains=[domain])[:2])+ email = users_by_id[membership.user_id].email.lower()+ candidates_by_email.setdefault(email, {})[str(account.id)] = account++ matches: dict[str, MatchedAccount] = {}+ for email, candidates in candidates_by_email.items():if len(candidates) == 1:- matched[email] = MatchedAccount(account=candidates[0], source=EMAIL_DOMAIN_MATCH)- elif len(candidates) > 1:- _record_ambiguity(team_id=team.id, source=EMAIL_DOMAIN_MATCH, candidate_count=len(candidates))+ matches[email] = MatchedAccount(account=next(iter(candidates.values())), source=ORGANIZATION_MEMBER_MATCH)+ else:+ ambiguous.add(email)+ _record_ambiguity(team_id=team.id, source=ORGANIZATION_MEMBER_MATCH, candidate_count=None)+ return matches, ambiguous+++def _unresolved_emails(emails: list[str], matched: dict[str, MatchedAccount], ambiguous: set[str]) -> list[str]:+ return [email for email in emails if email not in matched and email not in ambiguous]+++def _match_accounts_for_emails(+ team: Team,+ emails: list[str],+ *,+ use_organization_membership: bool,+) -> dict[str, MatchedAccount]:+ normalized_emails = sorted(normalize_emails(emails))+ if not normalized_emails:+ return {}+ matched, ambiguous = _match_accounts_by_account_property(+ team,+ normalized_emails,+ find_accounts=_find_accounts_by_known_email,+ source=KNOWN_EMAIL_MATCH,+ value_for_email=lambda email: email,+ )+ person_group_matches, person_group_ambiguous = _match_accounts_by_person_group(+ team,+ _unresolved_emails(normalized_emails, matched, ambiguous),+ )+ matched.update(person_group_matches)+ ambiguous.update(person_group_ambiguous)++ if use_organization_membership:+ organization_matches, organization_ambiguous = _match_accounts_by_organization_membership(+ team,+ _unresolved_emails(normalized_emails, matched, ambiguous),+ )+ matched.update(organization_matches)+ ambiguous.update(organization_ambiguous)++ domain_matches, _ = _match_accounts_by_account_property(+ team,+ _unresolved_emails(normalized_emails, matched, ambiguous),+ find_accounts=_find_accounts_by_email_domain,+ source=EMAIL_DOMAIN_MATCH,+ value_for_email=lambda email: email.rsplit("@", 1)[-1],+ )+ matched.update(domain_matches)return matched+++def match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, MatchedAccount]:+ return _match_accounts_for_emails(team, emails, use_organization_membership=False)+++def match_accounts_for_gmail_emails(team: Team, emails: list[str]) -> dict[str, MatchedAccount]:+ return _match_accounts_for_emails(team, emails, use_organization_membership=True)diff --git a/products/customer_analytics/backend/test/test_email_account_matching.py b/products/customer_analytics/backend/test/test_email_account_matching.pyindex edebad269764..82345a503401 100644--- a/products/customer_analytics/backend/test/test_email_account_matching.py+++ b/products/customer_analytics/backend/test/test_email_account_matching.py@@ -3,6 +3,9 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterized+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User+from products.conversations.backend.facade.types import EmailThreadForAccountMatchingfrom products.customer_analytics.backend.facade import apifrom products.customer_analytics.backend.facade.email_matching import (@@ -12,7 +15,10 @@ from products.customer_analytics.backend.facade.email_matching import (schedule_email_thread_link_recalculation,schedule_email_thread_link_recalculation_for_threads,)-from products.customer_analytics.backend.logic.email_account_matching import MatchedAccount+from products.customer_analytics.backend.logic.email_account_matching import (+ MatchedAccount,+ match_accounts_for_gmail_emails,+)from products.customer_analytics.backend.models import Account@@ -66,6 +72,72 @@ class TestEmailAccountMatching(BaseTest):(str(domain.id), "email_domain"),}+ def _create_account_member(self, *, email: str, organization: Organization | None = None) -> User:+ member = User.objects.create(email=email)+ OrganizationMembership.objects.create(user=member, organization=organization or self.organization)+ return member++ def test_matches_organization_member_for_gmail_email(self) -> None:+ member = self._create_account_member(email="[email protected]")+ account = self._create_account(name="Customer", external_id=str(self.organization.id))++ matches = match_accounts_for_gmail_emails(self.team, [member.email])++ assert [(str(match.account.id), match.source) for match in matches.values()] == [+ (str(account.id), "organization_member")+ ]++ def test_direct_matching_does_not_use_organization_membership(self) -> None:+ member = self._create_account_member(email="[email protected]")+ self._create_account(name="Customer", external_id=str(self.organization.id))++ matches = match_email_accounts(self.team.id, [member.email])++ assert matches == []++ def test_gmail_membership_skips_only_posthog_domain(self) -> None:+ posthog_member = self._create_account_member(email="[email protected]")+ subdomain_member = self._create_account_member(email="[email protected]")+ account = self._create_account(name="Customer", external_id=str(self.organization.id))++ matches = match_accounts_for_gmail_emails(self.team, [posthog_member.email, subdomain_member.email])++ assert [(email, str(match.account.id), match.source) for email, match in matches.items()] == [+ (subdomain_member.email, str(account.id), "organization_member")+ ]++ def test_matches_a_mixed_case_organization_member_email(self) -> None:+ self._create_account_member(email="[email protected]")+ account = self._create_account(name="Customer", external_id=str(self.organization.id))++ matches = match_accounts_for_gmail_emails(self.team, ["[email protected]"])++ assert [(str(match.account.id), match.source) for match in matches.values()] == [+ (str(account.id), "organization_member")+ ]++ def test_does_not_match_case_folded_duplicate_users(self) -> None:+ self._create_account_member(email="[email protected]")+ other_organization = Organization.objects.create(name="Other customer")+ self._create_account_member(email="[email protected]", organization=other_organization)+ self._create_account(name="First customer", external_id=str(self.organization.id))+ self._create_account(name="Second customer", external_id=str(other_organization.id))++ matches = match_accounts_for_gmail_emails(self.team, ["[email protected]"])++ assert matches == {}++ def test_does_not_match_an_organization_member_of_multiple_accounts(self) -> None:+ member = self._create_account_member(email="[email protected]")+ other_organization = Organization.objects.create(name="Other customer")+ OrganizationMembership.objects.create(user=member, organization=other_organization)+ self._create_account(name="First customer", external_id=str(self.organization.id))+ self._create_account(name="Second customer", external_id=str(other_organization.id))++ matches = match_accounts_for_gmail_emails(self.team, [member.email])++ assert matches == {}+@patch("products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email",return_value={},@@ -102,8 +174,12 @@ class TestEmailAccountMatching(BaseTest):second = self._create_account(name="Second", external_id="second-account")mock_list_threads.side_effect = [[- EmailThreadForAccountMatching(id="thread-1", participant_emails=["[email protected]"]),- EmailThreadForAccountMatching(id="thread-2", participant_emails=["[email protected]"]),+ EmailThreadForAccountMatching(+ id="thread-1", participant_emails=["[email protected]"], gmail_owner_id=None+ ),+ EmailThreadForAccountMatching(+ id="thread-2", participant_emails=["[email protected]"], gmail_owner_id=None+ ),],[],]@@ -115,8 +191,10 @@ class TestEmailAccountMatching(BaseTest):processed = recalculate_email_thread_links(self.team.id, batch_size=100)assert processed == 2- # The whole page is matched in a single pass, not once per thread.- mock_match.assert_called_once()+ mock_match.assert_called_once_with(+ self.team,+ ["[email protected]", "[email protected]"],+ )links_by_thread = {call.args[1]: call.args[2] for call in mock_replace.call_args_list}assert [(link.account_id, link.account_external_id, link.match_source) for link in links_by_thread["thread-1"]@@ -125,6 +203,75 @@ class TestEmailAccountMatching(BaseTest):(str(second.id), "email_domain")]+ @patch("products.customer_analytics.backend.facade.email_matching.conversations.replace_email_thread_account_links")+ @patch(+ "products.customer_analytics.backend.facade.email_matching.conversations.list_email_threads_for_account_matching"+ )+ @patch("products.customer_analytics.backend.logic.account_member_search.posthog_feature_flag_enabled")+ def test_recalculation_checks_each_gmail_owner_without_sharing_matches(+ self,+ mock_flag: MagicMock,+ mock_list_threads: MagicMock,+ mock_replace: MagicMock,+ ) -> None:+ self.user.is_staff = True+ self.user.save(update_fields=["is_staff"])+ disabled_owner = User.objects.create(+ email="[email protected]",+ is_staff=True,+ distinct_id="disabled-owner",+ )+ nonstaff_owner = User.objects.create(+ email="[email protected]",+ distinct_id="nonstaff-owner",+ )+ inactive_owner = User.objects.create(+ email="[email protected]",+ is_active=False,+ is_staff=True,+ distinct_id="inactive-owner",+ )+ member = self._create_account_member(email="[email protected]")+ account = self._create_account(name="Customer", external_id=str(self.organization.id))+ mock_flag.side_effect = lambda _flag, distinct_id, **_kwargs: distinct_id == str(self.user.distinct_id)+ mock_list_threads.return_value = [+ EmailThreadForAccountMatching(+ id="enabled-thread",+ participant_emails=[member.email],+ gmail_owner_id=self.user.id,+ ),+ EmailThreadForAccountMatching(+ id="disabled-thread",+ participant_emails=[member.email],+ gmail_owner_id=disabled_owner.id,+ ),+ EmailThreadForAccountMatching(+ id="nonstaff-thread",+ participant_emails=[member.email],+ gmail_owner_id=nonstaff_owner.id,+ ),+ EmailThreadForAccountMatching(+ id="inactive-thread",+ participant_emails=[member.email],+ gmail_owner_id=inactive_owner.id,+ ),+ ]++ processed = recalculate_email_thread_links(self.team.id)++ assert processed == 4+ assert {call.args[1] for call in mock_flag.call_args_list} == {+ str(self.user.distinct_id),+ "disabled-owner",+ }+ links_by_thread = {call.args[1]: call.args[2] for call in mock_replace.call_args_list}+ assert [(link.account_id, link.match_source) for link in links_by_thread["enabled-thread"]] == [+ (str(account.id), "organization_member")+ ]+ assert links_by_thread["disabled-thread"] == []+ assert links_by_thread["nonstaff-thread"] == []+ assert links_by_thread["inactive-thread"] == []+@patch("products.customer_analytics.backend.facade.api.schedule_email_thread_link_recalculation")def test_account_matching_changes_schedule_recalculation(self, mock_schedule: MagicMock) -> None:with self.captureOnCommitCallbacks(execute=True):