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.

fix(customer-analytics): prioritize account email domains (#102276)

Arthur Moreira de Deus7f6e7e8cecb2
diff --git a/docs/internal/customer-analytics-email-matching.md b/docs/internal/customer-analytics-email-matching.md
new file mode 100644
index 000000000000..ee97429cbfcd
--- /dev/null
+++ b/docs/internal/customer-analytics-email-matching.md
@@ -0,0 +1,66 @@
+# Customer analytics email matching
+
+The shared matcher checks each participant address in this order:
+
+1. The account's `known_emails` property.
+2. The account's `email_domains` property.
+3. The person's associated group.
+4. Organization membership, when the Gmail owner's staff-only account member search is enabled.
+
+A known email overrides a domain assignment.
+A unique domain assignment takes priority over person groups and organization membership, including ambiguous results from those later sources.
+Direct email matching and calendar matching skip organization membership.
+
+The first match wins for each address.
+No match allows the next step.
+An ambiguous result stops matching for that address.
+For example, if two accounts claim a domain, the matcher does not use a person group to choose between them.
+Use `known_emails` to assign individual addresses on shared domains.
+
+## Matching flow
+
+This flow runs independently for each participant address.
+Skip person-group matching when no account group type is configured.
+Skip organization membership unless one active Gmail owner passes the staff and feature-flag checks.
+
+```mermaid
+flowchart TD
+ Input[Participant email] --> Normalize[Trim whitespace and lowercase]
+ Normalize --> Eligible{"Contains @ and is not<br/>an @posthog.com address?"}
+ Eligible -->|No| Unmatched[No account match]
+ Eligible -->|Yes| Stage["Try the next enabled stage<br/>1. Known email<br/>2. Email domain<br/>3. Person's group<br/>4. Organization membership"]
+ Stage --> Result{Stage result?}
+ Result -->|One account| Matched[Keep the match and stop]
+ Result -->|Ambiguous| Unmatched
+ Result -->|No match| More{More enabled stages?}
+ More -->|Yes| Stage
+ More -->|No| Unmatched
+
+ classDef phBlue fill:#1d4aff,stroke:#1d4aff,color:#fff;
+ classDef phYellow fill:#f9bd2b,stroke:#f9bd2b,color:#000;
+ classDef phGray fill:#e5e7eb,stroke:#c7ccd1,color:#000;
+ class Input,Matched,Unmatched phYellow;
+ class Normalize,Stage phBlue;
+ class Eligible,Result,More phGray;
+```
+
+Ambiguity stops all later stages for that address.
+A lookup error can fail the task instead of allowing fallback.
+
+## Thread links
+
+Each participant can match a different account.
+When several participants match the same account, the thread keeps one link with the highest-priority source from the order above.
+A recalculation replaces the thread's account links and removes stale links without deleting messages.
+
+Deployment alone does not recalculate existing links.
+After deployment, use `schedule_email_thread_link_recalculation(team_id)` from `products.customer_analytics.backend.facade.email_matching` to update an affected project.
+Check that a unique domain assignment wins over a competing group or membership match, while a known email still overrides the domain.
+Calendar rematching processes only meetings without an account; it does not replace existing assignments.
+
+## Unchanged safeguards
+
+Addresses are trimmed and lowercased before matching.
+The exact `@posthog.com` suffix is excluded before all steps.
+The person-group lookup uses the project's configured account group type.
+The organization-membership step keeps its existing Gmail-owner gate and local-region lookup; it does not query EU membership data from the US.
diff --git a/products/customer_analytics/backend/facade/email_matching.py b/products/customer_analytics/backend/facade/email_matching.py
index 1280a2cdcd2f..5c1213119d50 100644
--- a/products/customer_analytics/backend/facade/email_matching.py
+++ b/products/customer_analytics/backend/facade/email_matching.py
@@ -20,7 +20,7 @@ from products.customer_analytics.backend.logic.email_account_matching import (
logger = structlog.get_logger(__name__)
-_MATCH_SOURCE_PRIORITY = {"known_email": 0, "person_group": 1, "organization_member": 2, "email_domain": 3}
+_MATCH_SOURCE_PRIORITY = {"known_email": 0, "email_domain": 1, "person_group": 2, "organization_member": 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
diff --git a/products/customer_analytics/backend/logic/email_account_matching.py b/products/customer_analytics/backend/logic/email_account_matching.py
index 0bbe5667821c..4d5c0a417542 100644
--- a/products/customer_analytics/backend/logic/email_account_matching.py
+++ b/products/customer_analytics/backend/logic/email_account_matching.py
@@ -159,6 +159,16 @@ def _match_accounts_for_emails(
source=KNOWN_EMAIL_MATCH,
value_for_email=lambda email: email,
)
+ domain_matches, domain_ambiguous = _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)
+ ambiguous.update(domain_ambiguous)
+
person_group_matches, person_group_ambiguous = _match_accounts_by_person_group(
team,
_unresolved_emails(normalized_emails, matched, ambiguous),
@@ -174,14 +184,6 @@ def _match_accounts_for_emails(
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
diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.py
index 4e1f25ab3ab9..cf5a0d483c87 100644
--- a/products/customer_analytics/backend/test/test_calendar_sync.py
+++ b/products/customer_analytics/backend/test/test_calendar_sync.py
@@ -234,15 +234,21 @@ class TestCalendarSync(BaseTest):
assert str(participants["[email protected]"].person_id) == person_uuid
assert participants["[email protected]"].person_id is None
- def test_ambiguous_email_domain_matches_nothing(self):
- for name in ("Acme US", "Acme EU"):
- account = Account.objects.for_team(self.team.id).create(
- team=self.team, name=name, external_id=name.lower().replace(" ", "-")
- )
- account.properties = {"email_domains": ["acme.com"]}
+ @patch("products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email")
+ def test_ambiguous_email_domain_does_not_fall_through_to_person_group(self, 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"])
+ Account.objects.for_team(self.team.id).create(team=self.team, name="Grouped", external_id="group-account")
+ mock_group_keys.side_effect = lambda _team_id, emails, _index: {
+ email: "group-account" for email in emails if email == "[email protected]"
+ }
+ for name in ("First", "Second"):
+ account = Account.objects.for_team(self.team.id).create(team=self.team, name=name, external_id=name.lower())
+ account.properties = {"email_domains": ["example.com"]}
account.save()
- self._sync([_pages_response([_event()])])
+ event = _event(attendees=[{"email": "[email protected]", "responseStatus": "accepted"}])
+ self._sync([_pages_response([event])])
assert Meeting.objects.for_team(self.team.id).get().account_id is None
@parameterized.expand(
diff --git a/products/customer_analytics/backend/test/test_email_account_matching.py b/products/customer_analytics/backend/test/test_email_account_matching.py
index 264d27c39235..e6c1b2f42ed5 100644
--- a/products/customer_analytics/backend/test/test_email_account_matching.py
+++ b/products/customer_analytics/backend/test/test_email_account_matching.py
@@ -41,29 +41,33 @@ class TestEmailAccountMatching(BaseTest):
},
)
- @patch(
- "products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email",
- return_value={"[email protected]": "group-account"},
- )
- def test_matches_multiple_accounts_with_explicit_precedence(self, _mock_group_keys: MagicMock) -> None:
+ @parameterized.expand([("unique_group", "group-account"), ("ambiguous_group", None)])
+ @patch("products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email")
+ def test_matches_multiple_accounts_with_explicit_precedence(
+ self, _name: str, lower_priority_group_key: str | None, 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"])
known = self._create_account(
name="Known",
external_id="known-account",
- known_emails=["[email protected]"],
- email_domains=["shared.example"],
+ known_emails=["[email protected]"],
+ email_domains=["shared.example.com"],
)
grouped = self._create_account(name="Grouped", external_id="group-account")
domain = self._create_account(
name="Domain",
external_id="domain-account",
- email_domains=["domain.example"],
+ email_domains=["shared.example.com", "domain.example.com"],
)
+ mock_group_keys.side_effect = lambda _team_id, emails, _index: {
+ email: "group-account" if email == "[email protected]" else lower_priority_group_key
+ for email in emails
+ }
matches = match_email_accounts(
self.team.id,
)
assert {(match.account_id, match.match_source) for match in matches} == {
@@ -102,15 +106,34 @@ class TestEmailAccountMatching(BaseTest):
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))
+ @parameterized.expand(
+ [
+ ("no_domain", 0, "organization_member"),
+ ("unique_domain", 1, "email_domain"),
+ ("ambiguous_domain", 2, None),
+ ]
+ )
+ def test_matches_organization_member_for_gmail_email(
+ self, _name: str, domain_account_count: int, expected_source: str | None
+ ) -> None:
+ member = self._create_account_member(email="[email protected]")
+ member_account = self._create_account(name="Member", external_id=str(self.organization.id))
+ domain_accounts = [
+ self._create_account(
+ name=f"Domain {index}", external_id=f"domain-account-{index}", email_domains=["example.com"]
+ )
+ for index in range(domain_account_count)
+ ]
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")
- ]
+ if expected_source is None:
+ assert matches == {}
+ else:
+ expected_account = domain_accounts[0] if domain_accounts else member_account
+ assert [(str(match.account.id), match.source) for match in matches.values()] == [
+ (str(expected_account.id), expected_source)
+ ]
def test_direct_matching_does_not_use_organization_membership(self) -> None:
member = self._create_account_member(email="[email protected]")
@@ -200,17 +223,23 @@ class TestEmailAccountMatching(BaseTest):
mock_list_threads.side_effect = [
[
EmailThreadForAccountMatching(
- id="thread-1", participant_emails=["[email protected]"], gmail_owner_id=None
+ id="thread-1",
+ participant_emails=["[email protected]", "[email protected]"],
+ gmail_owner_id=None,
),
EmailThreadForAccountMatching(
- id="thread-2", participant_emails=["[email protected]"], gmail_owner_id=None
+ id="thread-2",
+ participant_emails=["[email protected]", "[email protected]"],
+ gmail_owner_id=None,
),
],
[],
]
mock_match.return_value = {
"[email protected]": MatchedAccount(account=first, source="person_group"),
- "[email protected]": MatchedAccount(account=second, source="email_domain"),
+ "[email protected]": MatchedAccount(account=first, source="email_domain"),
+ "[email protected]": MatchedAccount(account=second, source="known_email"),
+ "[email protected]": MatchedAccount(account=second, source="email_domain"),
}
processed = recalculate_email_thread_links(self.team.id, batch_size=100)
@@ -218,14 +247,19 @@ class TestEmailAccountMatching(BaseTest):
assert processed == 2
mock_match.assert_called_once_with(
self.team,
+ [
+ ],
)
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"]
- ] == [(str(first.id), "first-account", "person_group")]
+ ] == [(str(first.id), "first-account", "email_domain")]
assert [(link.account_id, link.match_source) for link in links_by_thread["thread-2"]] == [
- (str(second.id), "email_domain")
+ (str(second.id), "known_email")
]
@patch("products.customer_analytics.backend.facade.email_matching.conversations.replace_email_thread_account_links")