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): scope email property rematches (#119826)

Arthur Moreira de Deusa83b1e7d0971
diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
index 6b616d300a05..efd10b669ab2 100644
--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py
+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
@@ -484,6 +484,50 @@ class TestCustomerEmailIngestion(MailgunWebhookTestMixin, BaseTest):
assert not Ticket.objects.filter(team=self.team).exists()
assert not EmailOutboxMessage.objects.filter(team=self.team).exists()
+ @parameterized.expand(
+ [
+ ("other_account", "other", {("identity", "person_group"), ("other", "known_email")}),
+ ("linked_account", "identity", {("identity", "person_group")}),
+ ]
+ )
+ def test_append_only_rematch_keeps_existing_account_links(
+ self, _name: str, known_email_account: str, expected_links: set[tuple[str, str]]
+ ) -> None:
+ account_model = apps.get_model("customer_analytics", "Account")
+ external_ids_by_account_id = {
+ str(
+ account_model.objects.for_team(self.team.id)
+ .create(
+ team=self.team,
+ name=external_id,
+ external_id=external_id,
+ _properties={
+ "known_emails": ["[email protected]"] if external_id == known_email_account else []
+ },
+ )
+ .id
+ ): external_id
+ for external_id in ("identity", "other")
+ }
+ response = self._post_email(message_id="<[email protected]>")
+ assert response.status_code == 202
+ thread = EmailThread.objects.for_team(self.team.id).get()
+ identity_account_id = next(
+ account_id for account_id, external_id in external_ids_by_account_id.items() if external_id == "identity"
+ )
+ EmailThreadAccountLink.objects.for_team(self.team.id).create(
+ team=self.team,
+ thread=thread,
+ account_id=identity_account_id,
+ account_external_id="identity",
+ match_source="person_group",
+ )
+
+ recalculate_email_thread_links(self.team.id, thread_ids=[str(thread.id)], append_only=True)
+
+ links = EmailThreadAccountLink.objects.for_team(self.team.id).filter(thread=thread)
+ assert {(external_ids_by_account_id[link.account_id], link.match_source) for link in links} == expected_links
+
@parameterized.expand(
[
("different_envelope", {"sender": "[email protected]"}),
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index 67cee1566a32..ed31ad9a2920 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -803,6 +803,8 @@ def list_email_threads_for_account_matching(
team_id: int,
*,
thread_ids: list[str] | None = None,
+ participant_emails: list[str] | None = None,
+ participant_domains: list[str] | None = None,
after_id: str | None = None,
limit: int = 100,
) -> list[EmailThreadForAccountMatching]:
@@ -812,6 +814,11 @@ def list_email_threads_for_account_matching(
)
if thread_ids is not None:
threads = threads.filter(id__in=thread_ids)
+ if participant_emails is not None or participant_domains is not None:
+ matching_participants = Q(email__in=participant_emails or [])
+ for domain in participant_domains or []:
+ matching_participants |= Q(email__endswith=f"@{domain}")
+ threads = threads.filter(Exists(participants.filter(matching_participants, thread_id=OuterRef("id"))))
if after_id is not None:
threads = threads.filter(id__gt=after_id)
@@ -861,22 +868,62 @@ def list_email_threads_for_account_matching(
return matching_threads
+def _validate_match_source(link: EmailThreadAccountLinkInput) -> None:
+ if link.match_source not in EmailThreadAccountMatchSource.values:
+ raise ValueError(f"Unknown email account match source: {link.match_source}")
+
+
+def create_email_thread_account_links(
+ team_id: int,
+ thread_id: str,
+ links: list[EmailThreadAccountLinkInput],
+) -> None:
+ thread = EmailThread.objects.for_team(team_id).select_for_update().get(id=thread_id)
+ linked_account_ids = set(
+ EmailThreadAccountLink.objects.for_team(team_id).filter(thread=thread).values_list("account_id", flat=True)
+ )
+ links_by_account_id = {link.account_id: link for link in links}
+ for link in links_by_account_id.values():
+ _validate_match_source(link)
+ EmailThreadAccountLink.objects.for_team(team_id).bulk_create(
+ [
+ EmailThreadAccountLink(
+ team_id=team_id,
+ thread=thread,
+ account_id=account_id,
+ account_external_id=link.account_external_id,
+ match_source=link.match_source,
+ )
+ for account_id, link in links_by_account_id.items()
+ if account_id not in linked_account_ids
+ ]
+ )
+
+
@transaction.atomic
def replace_email_thread_account_links(
team_id: int,
thread_id: str,
links: list[EmailThreadAccountLinkInput],
+ *,
+ match_sources: list[str] | None = None,
) -> None:
thread = EmailThread.objects.for_team(team_id).select_for_update().get(id=thread_id)
links_by_account_id = {link.account_id: link for link in links}
- EmailThreadAccountLink.objects.for_team(team_id).filter(thread=thread).exclude(
- account_id__in=links_by_account_id
- ).delete()
+ existing_links = EmailThreadAccountLink.objects.for_team(team_id).filter(thread=thread)
+ preserved_account_ids: set[str] = set()
+ if match_sources is not None:
+ preserved_account_ids = set(
+ existing_links.exclude(match_source__in=match_sources).values_list("account_id", flat=True)
+ )
+ existing_links = existing_links.filter(match_source__in=match_sources)
+ existing_links.exclude(account_id__in=links_by_account_id).delete()
- valid_sources = set(EmailThreadAccountMatchSource.values)
for account_id, link in links_by_account_id.items():
- if link.match_source not in valid_sources:
- raise ValueError(f"Unknown email account match source: {link.match_source}")
+ _validate_match_source(link)
+ if account_id in preserved_account_ids:
+ continue
EmailThreadAccountLink.objects.for_team(team_id).update_or_create(
team_id=team_id,
thread=thread,
diff --git a/products/conversations/backend/tests/test_email_thread_account_links.py b/products/conversations/backend/tests/test_email_thread_account_links.py
index 44924bbe6d85..8a8ce348e0b3 100644
--- a/products/conversations/backend/tests/test_email_thread_account_links.py
+++ b/products/conversations/backend/tests/test_email_thread_account_links.py
@@ -4,6 +4,8 @@ from posthog.test.base import BaseTest
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.models.comment import Comment
from posthog.models.integration import Integration
from posthog.models.team import Team
@@ -163,6 +165,94 @@ class TestEmailThreadAccountLinks(BaseTest):
assert remaining.match_source == "organization_member"
assert list_account_email_thread_messages(self.team.id, "account-1", str(self.thread.id)) is None
+ @parameterized.expand(
+ [
+ ("known_email", ["[email protected]"], [], True),
+ ("email_domain", [], ["example.com"], True),
+ ("either_field", ["[email protected]"], ["example.com"], True),
+ ("different_domain", [], ["other.example.com"], False),
+ ("internal_participant", ["[email protected]"], [], False),
+ ("empty_fields", [], [], False),
+ ]
+ )
+ def test_filters_matching_threads_by_customer_email_properties(
+ self, _name: str, emails: list[str], domains: list[str], expected_match: bool
+ ) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ other_thread = EmailThread.objects.for_team(other_team.id).create(
+ team=other_team,
+ canonical_thread_key="<[email protected]>",
+ subject="Other team",
+ )
+ EmailThreadParticipant.objects.for_team(other_team.id).create(
+ team=other_team,
+ thread=other_thread,
+ kind=EmailThreadParticipantKind.CUSTOMER,
+ )
+
+ threads = list_email_threads_for_account_matching(
+ self.team.id, participant_emails=emails, participant_domains=domains
+ )
+
+ assert [thread.id for thread in threads] == ([str(self.thread.id)] if expected_match else [])
+ assert (
+ list_email_threads_for_account_matching(
+ self.team.id,
+ participant_emails=emails,
+ participant_domains=domains,
+ after_id=str(self.thread.id),
+ )
+ == []
+ )
+
+ @parameterized.expand([("known_email",), ("email_domain",)])
+ def test_property_replacement_preserves_identity_links(self, property_source: str) -> None:
+ replace_email_thread_account_links(
+ self.team.id,
+ str(self.thread.id),
+ [
+ EmailThreadAccountLinkInput(account_id=account_id, account_external_id=account_id, match_source=source)
+ for account_id, source in (
+ ("removed-property-account", property_source),
+ ("group-account", "person_group"),
+ ("member-account", "organization_member"),
+ )
+ ],
+ )
+
+ replace_email_thread_account_links(
+ self.team.id,
+ str(self.thread.id),
+ [
+ EmailThreadAccountLinkInput(
+ account_id=account_id, account_external_id=account_id, match_source=property_source
+ )
+ for account_id in ("new-property-account", "group-account")
+ ],
+ match_sources=["known_email", "email_domain"],
+ )
+
+ assert set(
+ EmailThreadAccountLink.objects.for_team(self.team.id)
+ .filter(thread=self.thread)
+ .values_list("account_id", "match_source")
+ ) == {
+ ("new-property-account", property_source),
+ ("group-account", "person_group"),
+ ("member-account", "organization_member"),
+ }
+
+ replace_email_thread_account_links(
+ self.team.id, str(self.thread.id), [], match_sources=["known_email", "email_domain"]
+ )
+
+ assert set(
+ EmailThreadAccountLink.objects.for_team(self.team.id)
+ .filter(thread=self.thread)
+ .values_list("account_id", "match_source")
+ ) == {("group-account", "person_group"), ("member-account", "organization_member")}
+
def test_resolves_one_gmail_owner_across_integrations(self) -> None:
first_integration = Integration.objects.create(
team=self.team,
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 79f23b5ab01c..7947c642ce44 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -97,7 +97,10 @@ from products.customer_analytics.backend.events import emit_account_tags_added,
from products.customer_analytics.backend.facade.contracts import (
InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,
)
-from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculation
+from products.customer_analytics.backend.facade.email_matching import (
+ schedule_email_thread_link_recalculation,
+ schedule_email_thread_link_recalculation_for_account_properties,
+)
from products.customer_analytics.backend.facade.enums import (
AccountPropertyPinKind,
AccountRelationshipSource,
@@ -3795,14 +3798,22 @@ def update_account(
returns the model, so it must not be called across the product boundary."""
update_fields: list[str] = []
matching_expanded = False
+ matching_changed = False
+ external_id_changed = False
+ previous_known_emails: list[str] = []
+ previous_email_domains: list[str] = []
if not isinstance(name, _Unset):
account.name = _cap_to_field_length("name", name)
update_fields.append("name")
if not isinstance(external_id, _Unset):
- account.external_id = _cap_to_field_length("external_id", external_id) if external_id is not None else None
+ next_external_id = _cap_to_field_length("external_id", external_id) if external_id is not None else None
+ external_id_changed = next_external_id != account.external_id
+ account.external_id = next_external_id
update_fields.append("external_id")
if not isinstance(properties, _Unset):
previous_properties = account.properties
+ previous_known_emails = previous_properties.known_emails
+ previous_email_domains = previous_properties.email_domains
validated_properties = _ModelAccountProperties.from_input(properties)
known_emails_added = set(validated_properties.known_emails) - set(previous_properties.known_emails)
email_domains_added = set(validated_properties.email_domains) - set(previous_properties.email_domains)
@@ -3827,8 +3838,15 @@ def update_account(
account.save(update_fields=update_fields)
if matching_expanded:
transaction.on_commit(lambda: _enqueue_meeting_rematch(account.team_id, str(account.id)))
- if "external_id" in update_fields or "_properties" in update_fields:
+ if external_id_changed:
schedule_email_thread_link_recalculation(account.team_id)
+ elif matching_changed:
+ schedule_email_thread_link_recalculation_for_account_properties(
+ account.team_id,
+ str(account.id),
+ previous_known_emails=previous_known_emails,
+ previous_email_domains=previous_email_domains,
+ )
return account
diff --git a/products/customer_analytics/backend/facade/email_matching.py b/products/customer_analytics/backend/facade/email_matching.py
index 5c1213119d50..7f18f7ec910b 100644
--- a/products/customer_analytics/backend/facade/email_matching.py
+++ b/products/customer_analytics/backend/facade/email_matching.py
@@ -1,9 +1,14 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from secrets import randbits
+
from django.core.cache import cache
-from django.db import transaction
+from django.db import connections, router, transaction
import structlog
from celery import current_app
+from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.team import Team
from posthog.models.user import User
@@ -13,16 +18,21 @@ from products.customer_analytics.backend.facade import contracts
from products.customer_analytics.backend.logic.account_member_search import is_account_member_search_enabled
from products.customer_analytics.backend.logic.email_account_matching import (
MatchedAccount,
+ match_accounts_for_account_properties,
match_accounts_for_emails,
match_accounts_for_gmail_emails,
normalize_emails,
)
+from products.customer_analytics.backend.models import Account
logger = structlog.get_logger(__name__)
_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_ACCOUNT_PROPERTIES_TASK = (
+ "customer_analytics.recalculate_email_thread_account_links_for_account_properties"
+)
_RECALCULATION_LOCK_SECONDS = 15 * 60
@@ -34,6 +44,31 @@ def _recalculation_dirty_cache_key(team_id: int) -> str:
return f"customer_analytics:email_thread_link_recalculation_dirty:{team_id}"
+def _matching_revision_cache_key(team_id: int) -> str:
+ return f"customer_analytics:email_matching_revision:{resolve_effective_team_id(team_id)}"
+
+
+def _get_matching_revision(team_id: int) -> int | None:
+ key = _matching_revision_cache_key(team_id)
+ cache.add(key, randbits(63), timeout=None)
+ try:
+ # Read from the Redis primary so replica lag cannot hide property edits.
+ revision = cache.incr(key, delta=0)
+ except ValueError:
+ return None
+ return revision if isinstance(revision, int) else None
+
+
+@contextmanager
+def _guard_email_thread_link_writes(team_id: int) -> Iterator[None]:
+ using = router.db_for_write(Account)
+ key = f"account-email-links:{resolve_effective_team_id(team_id)}"
+ with transaction.atomic(using=using):
+ with connections[using].cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", [key])
+ yield
+
+
def finish_email_thread_link_recalculation(team_id: int) -> None:
cache.delete(_recalculation_cache_key(team_id))
if cache.delete(_recalculation_dirty_cache_key(team_id)):
@@ -82,6 +117,30 @@ def schedule_email_thread_link_recalculation_for_threads(team_id: int, thread_id
transaction.on_commit(enqueue)
+def schedule_email_thread_link_recalculation_for_account_properties(
+ team_id: int,
+ account_id: str,
+ *,
+ previous_known_emails: list[str],
+ previous_email_domains: list[str],
+) -> None:
+ known_emails = sorted(set(previous_known_emails))
+ email_domains = sorted(set(previous_email_domains))
+
+ def enqueue() -> None:
+ try:
+ cache.set(_matching_revision_cache_key(team_id), randbits(63), timeout=None)
+ current_app.send_task(
+ _RECALCULATION_ACCOUNT_PROPERTIES_TASK,
+ args=[team_id, account_id],
+ kwargs={"previous_known_emails": known_emails, "previous_email_domains": email_domains},
+ )
+ except Exception:
+ logger.exception("email_thread_link_recalculation_enqueue_failed", team_id=team_id, account_id=account_id)
+
+ transaction.on_commit(enqueue)
+
+
def _dedupe_account_matches(matches_by_email: dict[str, MatchedAccount]) -> list[contracts.EmailAccountMatch]:
matches_by_account_id: dict[str, contracts.EmailAccountMatch] = {}
for email in sorted(matches_by_email):
@@ -113,12 +172,103 @@ def match_email_accounts(team_id: int, emails: list[str]) -> list[contracts.Emai
return _match_email_accounts(team, emails)
+def _create_link_inputs(
+ thread: EmailThreadForAccountMatching, matches_by_email: dict[str, MatchedAccount]
+) -> list[EmailThreadAccountLinkInput]:
+ matches = _dedupe_account_matches(
+ {
+ email: matches_by_email[email]
+ for email in normalize_emails(thread.participant_emails)
+ if email in matches_by_email
+ }
+ )
+ return [
+ EmailThreadAccountLinkInput(
+ account_id=match.account_id,
+ account_external_id=match.account_external_id,
+ match_source=match.match_source,
+ )
+ for match in matches
+ ]
+
+
+def _replace_thread_links(
+ team_id: int,
+ thread: EmailThreadForAccountMatching,
+ matches_by_email: dict[str, MatchedAccount],
+ *,
+ match_sources: list[str] | None = None,
+) -> None:
+ conversations.replace_email_thread_account_links(
+ team_id, thread.id, _create_link_inputs(thread, matches_by_email), match_sources=match_sources
+ )
+
+
+def _create_thread_links(
+ team_id: int, thread: EmailThreadForAccountMatching, matches_by_email: dict[str, MatchedAccount]
+) -> None:
+ conversations.create_email_thread_account_links(team_id, thread.id, _create_link_inputs(thread, matches_by_email))
+
+
+def recalculate_email_thread_links_for_account_properties(
+ team_id: int,
+ account_id: str,
+ *,
+ previous_known_emails: list[str],
+ previous_email_domains: list[str],
+ batch_size: int = 100,
+) -> int:
+ account = Account.objects.for_team(team_id).select_related("team").filter(id=account_id).first()
+ if account is None:
+ return 0
+
+ properties = account.properties
+ participant_emails = sorted(set(previous_known_emails) ^ set(properties.known_emails))
+ participant_domains = sorted(set(previous_email_domains) ^ set(properties.email_domains))
+ if not participant_emails and not participant_domains:
+ return 0
+
+ batch_size = max(1, min(batch_size, 500))
+ processed = 0
+ after_id: str | None = None
+ while True:
+ threads = conversations.list_email_threads_for_account_matching(
+ team_id,
+ participant_emails=participant_emails,
+ participant_domains=participant_domains,
+ after_id=after_id,
+ limit=batch_size,
+ )
+ if not threads:
+ return processed
+
+ with _guard_email_thread_link_writes(team_id):
+ locked_account = (
+ Account.objects.for_team(team_id).select_for_update().only("id").filter(id=account_id).first()
+ )
+ if locked_account is None:
+ return processed
+
+ matches_by_email = match_accounts_for_account_properties(
+ account.team, [email for thread in threads for email in thread.participant_emails]
+ )
+ for thread in threads:
+ _replace_thread_links(team_id, thread, matches_by_email, match_sources=["known_email", "email_domain"])
+ processed += 1
+
+ if len(threads) < batch_size:
+ return processed
+ after_id = threads[-1].id
+
+
def recalculate_email_thread_links(
team_id: int,
*,
thread_ids: list[str] | None = None,
+ append_only: bool = False,
batch_size: int = 100,
) -> int:
+ write_thread_links = _create_thread_links if append_only else _replace_thread_links
try:
team = Team.objects.get(id=team_id)
except Team.DoesNotExist:
@@ -146,33 +296,27 @@ def recalculate_email_thread_links(
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)
+ matching_revision = _get_matching_revision(team_id)
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: group_matches[email]
- for email in normalize_emails(thread.participant_emails)
- if email in group_matches
- }
- matches = _dedupe_account_matches(thread_matches)
- conversations.replace_email_thread_account_links(
- team_id,
- thread.id,
- [
- EmailThreadAccountLinkInput(
- account_id=match.account_id,
- account_external_id=match.account_external_id,
- match_source=match.match_source,
+ with _guard_email_thread_link_writes(team_id):
+ if matching_revision is None or _get_matching_revision(team_id) != matching_revision:
+ matches_by_member_search = {
+ member_search_enabled: match_accounts_for_account_properties(
+ team,
+ [email for thread in matching_threads for email in thread.participant_emails],
+ existing_matches=matches_by_member_search[member_search_enabled],
)
- for match in matches
- ],
- )
- processed += 1
+ 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]
+ write_thread_links(team_id, thread, group_matches)
+ processed += 1
if len(threads) < batch_size:
return processed
diff --git a/products/customer_analytics/backend/logic/email_account_matching.py b/products/customer_analytics/backend/logic/email_account_matching.py
index 4d5c0a417542..1ee508906b41 100644
--- a/products/customer_analytics/backend/logic/email_account_matching.py
+++ b/products/customer_analytics/backend/logic/email_account_matching.py
@@ -145,6 +145,8 @@ def _match_accounts_for_emails(
emails: list[str],
*,
use_organization_membership: bool,
+ account_properties_only: bool = False,
+ existing_matches: dict[str, MatchedAccount] | None = None,
) -> dict[str, MatchedAccount]:
normalized_emails = sorted(
email for email in normalize_emails(emails) if not email.endswith(POSTHOG_INTERNAL_EMAIL_SUFFIX)
@@ -168,6 +170,12 @@ def _match_accounts_for_emails(
)
matched.update(domain_matches)
ambiguous.update(domain_ambiguous)
+ if account_properties_only:
+ for email in _unresolved_emails(normalized_emails, matched, ambiguous):
+ existing_match = (existing_matches or {}).get(email)
+ if existing_match is not None and existing_match.source in {PERSON_GROUP_MATCH, ORGANIZATION_MEMBER_MATCH}:
+ matched[email] = existing_match
+ return matched
person_group_matches, person_group_ambiguous = _match_accounts_by_person_group(
team,
@@ -187,6 +195,21 @@ def _match_accounts_for_emails(
return matched
+def match_accounts_for_account_properties(
+ team: Team,
+ emails: list[str],
+ *,
+ existing_matches: dict[str, MatchedAccount] | None = None,
+) -> dict[str, MatchedAccount]:
+ return _match_accounts_for_emails(
+ team,
+ emails,
+ use_organization_membership=False,
+ account_properties_only=True,
+ existing_matches=existing_matches,
+ )
+
+
def match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, MatchedAccount]:
return _match_accounts_for_emails(team, emails, use_organization_membership=False)
diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.py
index 9eaac822cce0..59274550abdc 100644
--- a/products/customer_analytics/backend/tasks/tasks.py
+++ b/products/customer_analytics/backend/tasks/tasks.py
@@ -11,6 +11,7 @@ from posthog.models.scoping import with_team_scope
from products.customer_analytics.backend.facade.email_matching import (
finish_email_thread_link_recalculation,
recalculate_email_thread_links,
+ recalculate_email_thread_links_for_account_properties,
)
from products.customer_analytics.backend.logic.announcements import send_pending_deliveries
from products.customer_analytics.backend.logic.custom_property_sync import sync_custom_property_values
@@ -163,6 +164,30 @@ def recalculate_email_thread_account_links(team_id: int) -> None:
finish_email_thread_link_recalculation(team_id)
+@shared_task(
+ name="customer_analytics.recalculate_email_thread_account_links_for_account_properties",
+ ignore_result=True,
+ autoretry_for=(Exception,),
+ max_retries=3,
+ retry_backoff=True,
+ retry_jitter=True,
+)
+@with_team_scope()
+def recalculate_email_thread_account_links_for_account_properties(
+ team_id: int,
+ account_id: str,
+ *,
+ previous_known_emails: list[str],
+ previous_email_domains: list[str],
+) -> None:
+ recalculate_email_thread_links_for_account_properties(
+ team_id,
+ account_id,
+ previous_known_emails=previous_known_emails,
+ previous_email_domains=previous_email_domains,
+ )
+
+
@shared_task(
name="customer_analytics.recalculate_email_thread_account_links_for_threads",
ignore_result=True,
@@ -173,7 +198,7 @@ def recalculate_email_thread_account_links(team_id: int) -> None:
)
@with_team_scope()
def recalculate_email_thread_account_links_for_threads(team_id: int, thread_ids: list[str]) -> None:
- recalculate_email_thread_links(team_id, thread_ids=thread_ids)
+ recalculate_email_thread_links(team_id, thread_ids=thread_ids, append_only=True)
# autoretry_for is load-bearing: bare max_retries kwargs without it are silently inert.
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 cbf2c8bd91d0..0ddd1ac1e91e 100644
--- a/products/customer_analytics/backend/test/test_email_account_matching.py
+++ b/products/customer_analytics/backend/test/test_email_account_matching.py
@@ -1,5 +1,9 @@
+from itertools import count
+
from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
+
+from django.core.cache import cache
from parameterized import parameterized
@@ -12,11 +16,13 @@ from products.customer_analytics.backend.facade.email_matching import (
finish_email_thread_link_recalculation,
match_email_accounts,
recalculate_email_thread_links,
+ recalculate_email_thread_links_for_account_properties,
schedule_email_thread_link_recalculation,
schedule_email_thread_link_recalculation_for_threads,
)
from products.customer_analytics.backend.logic.email_account_matching import (
MatchedAccount,
+ match_accounts_for_account_properties,
match_accounts_for_gmail_emails,
)
from products.customer_analytics.backend.models import Account
@@ -142,6 +148,7 @@ class TestEmailAccountMatching(BaseTest):
matches = match_email_accounts(self.team.id, [member.email])
assert matches == []
+ assert match_accounts_for_account_properties(self.team, [member.email]) == {}
def test_gmail_membership_skips_only_posthog_domain(self) -> None:
posthog_member = self._create_account_member(email="[email protected]")
@@ -262,6 +269,89 @@ class TestEmailAccountMatching(BaseTest):
(str(second.id), "known_email")
]
+ @parameterized.expand(
+ [
+ ("domain_removed", False),
+ ("domain_added", False),
+ ("known_email_ambiguous", False),
+ ("domain_removed", True),
+ ]
+ )
+ @patch("products.customer_analytics.backend.facade.email_matching.current_app.send_task")
+ @patch("products.customer_analytics.backend.facade.email_matching.randbits", side_effect=count(1))
+ @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.email_account_matching.resolve_group_keys_by_email")
+ def test_full_recalculation_refreshes_properties_after_a_targeted_rematch(
+ self,
+ change: str,
+ evict_revision: bool,
+ mock_group_keys: MagicMock,
+ mock_list_threads: MagicMock,
+ mock_replace: MagicMock,
+ _mock_randbits: MagicMock,
+ _mock_send_task: MagicMock,
+ ) -> None:
+ self.team.customer_analytics_config.account_group_type_index = 0
+ self.team.customer_analytics_config.save(update_fields=["account_group_type_index"])
+ previous_domains = ["old.example.com"] if change == "domain_removed" else []
+ property_account = self._create_account(
+ name="Property match", external_id="property-account", email_domains=previous_domains
+ )
+ identity_account = self._create_account(name="Identity match", external_id="identity-account")
+ competing_account = (
+ self._create_account(name="Competing match", external_id="competing-account")
+ if change == "known_email_ambiguous"
+ else None
+ )
+ mock_list_threads.return_value = [
+ EmailThreadForAccountMatching(
+ id="affected-thread",
+ participant_emails=["[email protected]", "[email protected]"],
+ gmail_owner_id=None,
+ )
+ ]
+
+ def resolve_groups_during_property_edit(_team_id: int, _emails: list[str], _index: int) -> dict[str, str]:
+ with self.captureOnCommitCallbacks(execute=True):
+ if change == "known_email_ambiguous":
+ assert competing_account is not None
+ api.update_account(
+ competing_account,
+ properties={"known_emails": ["[email protected]"]},
+ allow_matching_updates=True,
+ )
+ properties = {"known_emails": ["[email protected]"]}
+ else:
+ properties = {"email_domains": ["identity.example.com"] if change == "domain_added" else []}
+ api.update_account(property_account, properties=properties, allow_matching_updates=True)
+
+ recalculate_email_thread_links_for_account_properties(
+ self.team.id,
+ str(property_account.id),
+ previous_known_emails=[],
+ previous_email_domains=previous_domains,
+ )
+ if evict_revision:
+ cache.clear()
+ return {"[email protected]": "identity-account"}
+
+ mock_group_keys.side_effect = resolve_groups_during_property_edit
+
+ processed = recalculate_email_thread_links(self.team.id)
+
+ assert processed == 1
+ mock_group_keys.assert_called_once()
+ final_links = {(link.account_id, link.match_source) for link in mock_replace.call_args.args[2]}
+ if change == "domain_removed":
+ assert final_links == {(str(identity_account.id), "person_group")}
+ elif change == "domain_added":
+ assert final_links == {(str(property_account.id), "email_domain")}
+ else:
+ assert final_links == set()
+
@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"
@@ -331,26 +421,151 @@ class TestEmailAccountMatching(BaseTest):
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:
+ @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.email_account_matching.resolve_group_keys_by_email")
+ def test_property_recalculation_skips_identity_matching_and_limits_threads(
+ self,
+ mock_group_keys: MagicMock,
+ mock_list_threads: MagicMock,
+ mock_replace: 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 = self._create_account(
+ name="Customer",
+ external_id="customer",
+ known_emails=["[email protected]"],
+ email_domains=["new.example.com"],
+ )
+ self._create_account(name="Identity only", external_id="identity-account")
+ mock_group_keys.return_value = {"[email protected]": "identity-account"}
+ mock_list_threads.side_effect = [
+ [
+ EmailThreadForAccountMatching(
+ id="thread-1",
+ participant_emails=["[email protected]", "[email protected]"],
+ gmail_owner_id=self.user.id,
+ ),
+ EmailThreadForAccountMatching(
+ id="thread-2",
+ participant_emails=["[email protected]"],
+ gmail_owner_id=None,
+ ),
+ ],
+ [
+ EmailThreadForAccountMatching(
+ id="thread-3",
+ participant_emails=["[email protected]"],
+ gmail_owner_id=None,
+ ),
+ EmailThreadForAccountMatching(
+ id="thread-4",
+ participant_emails=["[email protected]", "[email protected]"],
+ gmail_owner_id=self.user.id,
+ ),
+ ],
+ [],
+ ]
+
+ processed = recalculate_email_thread_links_for_account_properties(
+ self.team.id,
+ str(account.id),
+ previous_known_emails=["[email protected]", "[email protected]"],
+ previous_email_domains=["old.example.com"],
+ batch_size=2,
+ )
+
+ assert processed == 4
+ mock_group_keys.assert_not_called()
+ assert [
+ (item.args[1], [(link.account_id, link.match_source) for link in item.args[2]])
+ for item in mock_replace.call_args_list
+ ] == [
+ ("thread-1", [(str(account.id), "known_email")]),
+ ("thread-2", [(str(account.id), "email_domain")]),
+ ("thread-3", []),
+ ("thread-4", []),
+ ]
+ assert all(
+ item.kwargs == {"match_sources": ["known_email", "email_domain"]} for item in mock_replace.call_args_list
+ )
+ assert mock_list_threads.call_args_list == [
+ call(
+ self.team.id,
+ participant_emails=["[email protected]"],
+ participant_domains=["new.example.com", "old.example.com"],
+ after_id=after_id,
+ limit=2,
+ )
+ for after_id in (None, "thread-2", "thread-4")
+ ]
+
+ @parameterized.expand(
+ [
+ (
+ "known_email_changed",
+ {"known_emails": ["[email protected]"], "email_domains": ["old.example.com"]},
+ True,
+ ),
+ (
+ "email_domain_changed",
+ {"known_emails": ["[email protected]"], "email_domains": ["new.example.com"]},
+ True,
+ ),
+ ("matching_removed", {"known_emails": [], "email_domains": []}, True),
+ (
+ "unrelated_property_changed",
+ {
+ "known_emails": ["[email protected]"],
+ "email_domains": ["old.example.com"],
+ "sfdc_id": "example-salesforce-account",
+ },
+ False,
+ ),
+ (
+ "matching_unchanged_after_normalization",
+ {"known_emails": [" [email protected] "], "email_domains": ["@OLD.EXAMPLE.COM"]},
+ False,
+ ),
+ ]
+ )
+ @patch("products.customer_analytics.backend.facade.email_matching.current_app.send_task")
+ def test_account_matching_changes_schedule_recalculation(
+ self, _name: str, properties: dict[str, list[str] | str], expected_rematch: bool, mock_send_task: MagicMock
+ ) -> None:
with self.captureOnCommitCallbacks(execute=True):
account = api.create_account(
team=self.team,
name="Account",
external_id="account",
- properties={"known_emails": ["[email protected]"]},
+ properties={"known_emails": ["[email protected]"], "email_domains": ["old.example.com"]},
)
-
- mock_schedule.assert_not_called()
+ mock_send_task.reset_mock()
with self.captureOnCommitCallbacks(execute=True):
api.update_account(
- account,
- properties={"email_domains": ["example.com"]},
- allow_matching_updates=True,
+ account, external_id=account.external_id, properties=properties, allow_matching_updates=True
)
+ assert not any("recalculate_email_thread" in item.args[0] for item in mock_send_task.call_args_list)
- mock_schedule.assert_called_once_with(self.team.id)
+ email_rematches = [item for item in mock_send_task.call_args_list if "recalculate_email_thread" in item.args[0]]
+ assert email_rematches == (
+ [
+ call(
+ "customer_analytics.recalculate_email_thread_account_links_for_account_properties",
+ args=[self.team.id, str(account.id)],
+ kwargs={
+ "previous_known_emails": ["[email protected]"],
+ "previous_email_domains": ["old.example.com"],
+ },
+ )
+ ]
+ if expected_rematch
+ else []
+ )
@parameterized.expand(
[