: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): exclude internal email account matches (#101855)
Arthur Moreira de Deus628ca3644f79
diff --git a/docs/internal/customer-analytics-email-matching.md b/docs/internal/customer-analytics-email-matching.mdnew file mode 100644index 000000000000..213a8ea93fad--- /dev/null+++ b/docs/internal/customer-analytics-email-matching.md@@ -0,0 +1,36 @@+# Customer analytics email matching++Customer analytics uses a shared matcher to link email threads and calendar meetings to accounts.+The matcher checks each participant address in this order:++1. The account's `known_emails` property.+2. The person's associated group.+3. Organization membership, when the Gmail owner's staff-only account member search is enabled.+4. The account's `email_domains` property.++An ambiguous match stops further matching for that address.+Other participants can still match accounts.++## Internal email exclusion++The matcher removes addresses with the exact `@posthog.com` suffix before any matching step.+It trims whitespace and converts addresses to lowercase before this check.+This keeps internal participants from linking customer correspondence to internal accounts.+Subdomains and similar domain names do not match this exclusion.+Other participant addresses keep their existing matching behavior.++This rule uses `POSTHOG_INTERNAL_EMAIL_SUFFIX`.+It does not depend on account names or the `exclude_from_crm` group property.++## Existing links++The exclusion applies when the matcher processes new or updated email threads and calendar meetings.+Deployment alone does not change stored associations.++To update existing email links, call `schedule_email_thread_link_recalculation(team_id)` from `products.customer_analytics.backend.facade.email_matching` for the affected project after deployment.+The task replaces each thread's account links, including removing links that no longer match.+It preserves the email thread and its messages.+Check that customer links remain and excluded addresses no longer produce account links.++The calendar rematch task processes only meetings without an account.+It does not remove existing meeting assignments.diff --git a/products/customer_analytics/backend/logic/email_account_matching.py b/products/customer_analytics/backend/logic/email_account_matching.pyindex 2bb2470dad9a..0bbe5667821c 100644--- a/products/customer_analytics/backend/logic/email_account_matching.py+++ b/products/customer_analytics/backend/logic/email_account_matching.py@@ -6,6 +6,7 @@ from django.db.models.functions import Lowerimport structlog+from posthog.constants import POSTHOG_INTERNAL_EMAIL_SUFFIXfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -95,11 +96,10 @@ def _match_accounts_by_person_group(team: Team, emails: list[str]) -> tuple[dictdef _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)+ .filter(normalized_email__in=emails, is_active=True).only("id", "email")):users_by_email.setdefault(user.email.lower(), []).append(user)@@ -146,7 +146,9 @@ def _match_accounts_for_emails(*,use_organization_membership: bool,) -> dict[str, MatchedAccount]:- normalized_emails = sorted(normalize_emails(emails))+ normalized_emails = sorted(+ email for email in normalize_emails(emails) if not email.endswith(POSTHOG_INTERNAL_EMAIL_SUFFIX)+ )if not normalized_emails:return {}diff --git a/products/customer_analytics/backend/test/test_email_account_matching.py b/products/customer_analytics/backend/test/test_email_account_matching.pyindex 82345a503401..264d27c39235 100644--- a/products/customer_analytics/backend/test/test_email_account_matching.py+++ b/products/customer_analytics/backend/test/test_email_account_matching.py@@ -72,6 +72,31 @@ class TestEmailAccountMatching(BaseTest):(str(domain.id), "email_domain"),}+ @parameterized.expand([("known_email",), ("person_group",), ("email_domain",)])+ @patch("products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email")+ def test_posthog_email_is_excluded_from_all_matching_steps(self, source: str, mock_group_keys: MagicMock) -> None:+ self.team.customer_analytics_config.account_group_type_index = 0+ self.team.customer_analytics_config.save(update_fields=["account_group_type_index"])+ self._create_account(+ name="Internal account",+ external_id="internal-account",+ known_emails=["[email protected]"] if source == "known_email" else [],+ email_domains=["posthog.com"] if source == "email_domain" else [],+ )+ customer = self._create_account(name="Customer", external_id="customer", email_domains=["example.com"])+ mock_group_keys.side_effect = lambda _team_id, emails, _index: {+ email: "internal-account" for email in emails if email == "[email protected]" and source == "person_group"+ }++ matches = match_email_accounts(self.team.id, [" [email protected] ", "[email protected]"])++ assert [(match.account_id, match.match_source) for match in matches] == [(str(customer.id), "email_domain")]+ assert match_email_accounts(self.team.id, ["[email protected]"]) == []+ gmail_matches = match_accounts_for_gmail_emails(self.team, [" [email protected] ", "[email protected]"])+ assert [(email, match.account.id, match.source) for email, match in gmail_matches.items()] == [+ ("[email protected]", customer.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)