: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
feat(customer-analytics): link email threads to accounts (#80786)
Arthur Moreira de Deus52b641d5d57b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 325b498a1f84..f7e4f15315d5 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -140,6 +140,7 @@ rules:|EmailMessageMapping|EmailChannelSetup|EmailThread+ |EmailThreadAccountLink|EmailThreadMessage|EmailThreadParticipant|EmailReputationSnapshot@@ -504,6 +505,7 @@ rules:|EmailMessageMapping|EmailChannelSetup|EmailThread+ |EmailThreadAccountLink|EmailThreadMessage|EmailThreadParticipant|EmailReputationSnapshotdiff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.pyindex 68af496e1fb5..39a7b8a4f972 100644--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py@@ -5,7 +5,7 @@ from uuid import uuid4from freezegun import freeze_timefrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import Client, RequestFactory, SimpleTestCasefrom django.utils import timezone@@ -32,6 +32,7 @@ from products.conversations.backend.models import (EmailChannelSetupProvider,EmailOutboxMessage,EmailThread,+ EmailThreadAccountLink,EmailThreadMessage,Ticket,)@@ -379,6 +380,29 @@ class TestCustomerEmailIngestion(BaseTest):[] if header_kind == "in_reply_to" else ["<[email protected]>", root_message_id])+ @patch(+ "products.conversations.backend.services.email_thread_ingestion.schedule_email_thread_link_recalculation_for_threads"+ )+ def test_forwarded_message_schedules_account_matching(self, mock_schedule: MagicMock) -> None:+ response = self._post_email(message_id="<[email protected]>")++ assert response.status_code == 200+ thread = EmailThread.objects.for_team(self.team.id).get()+ mock_schedule.assert_called_once_with(self.team.id, [str(thread.id)])++ @patch(+ "products.customer_analytics.backend.facade.email_matching.current_app.send_task",+ side_effect=Exception("account matching backend unavailable"),+ )+ def test_account_link_recalculation_failure_does_not_fail_ingestion(self, _mock_send_task: MagicMock) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._post_email(message_id="<[email protected]>")++ assert response.status_code == 200+ thread = EmailThread.objects.for_team(self.team.id).get()+ assert EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).count() == 1+ assert not EmailThreadAccountLink.objects.for_team(self.team.id).exists()+def test_duplicate_delivery_creates_one_message_across_customer_channels(self) -> None:message_id = "<[email protected]>"first_response = self._post_email(message_id=message_id)diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 804700e6898f..68c539985a39 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -8,10 +8,11 @@ team's Slack credentials directly.import asynciofrom datetime import datetime-from typing import Any+from typing import Any, Protocol, castfrom django.conf import settings-from django.db.models import F+from django.db import transaction+from django.db.models import F, Prefetchimport structlogfrom slack_sdk.errors import SlackApiError@@ -25,10 +26,25 @@ from posthog.temporal.common.client import sync_connectfrom products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.types import (+ AccountEmailThreadDetail as AccountEmailThreadDetail,+ AccountEmailThreadMessage as AccountEmailThreadMessage,+ AccountEmailThreadSummary as AccountEmailThreadSummary,+ EmailThreadAccountLinkInput as EmailThreadAccountLinkInput,+ EmailThreadAddress as EmailThreadAddress,+ EmailThreadForAccountMatching as EmailThreadForAccountMatching,+ EmailThreadParticipantSummary as EmailThreadParticipantSummary,SupportChannel as SupportChannel,TicketSummary as TicketSummary,)-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import (+ EmailThread,+ EmailThreadAccountLink,+ EmailThreadAccountMatchSource,+ EmailThreadMessage,+ EmailThreadParticipant,+ EmailThreadParticipantKind,+ Ticket,+)from products.conversations.backend.slack import get_slack_clientfrom products.conversations.backend.support_slack import get_support_slack_bot_tokenfrom products.conversations.backend.support_slack_channels import (@@ -40,6 +56,10 @@ from products.conversations.backend.support_slack_channels import (logger = structlog.get_logger(__name__)+class _EmailThreadWithFacadePrefetch(Protocol):+ facade_participants: list[EmailThreadParticipant]++class SupportMessageSendError(Exception):"""Slack rejected a SupportHog bot message.@@ -235,3 +255,181 @@ def list_account_tickets(team_id: int, organization_id: str, *, limit: int = 50))for ticket in tickets]+++def resolve_group_keys_by_email(+ team_id: int,+ emails: list[str],+ group_type_index: int,+) -> dict[str, str | None]:+ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ return {}++ from products.conversations.backend.person_lookup import ( # noqa: PLC0415 — keeps HogQL and personhog off the facade import path+ get_group_keys_by_email,+ )++ return get_group_keys_by_email(team=team, emails=emails, group_type_index=group_type_index)+++def list_email_threads_for_account_matching(+ team_id: int,+ *,+ thread_ids: list[str] | None = None,+ after_id: str | None = None,+ limit: int = 100,+) -> list[EmailThreadForAccountMatching]:+ participants = EmailThreadParticipant.objects.for_team(team_id).filter(kind=EmailThreadParticipantKind.CUSTOMER)+ threads = EmailThread.objects.for_team(team_id).prefetch_related(+ Prefetch("participants", queryset=participants, to_attr="customer_participants")+ )+ if thread_ids is not None:+ threads = threads.filter(id__in=thread_ids)+ 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)+ ],+ )+ for thread in threads.order_by("id")[:limit]+ ]+++def replace_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)+ 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()++ 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}")+ EmailThreadAccountLink.objects.for_team(team_id).update_or_create(+ team_id=team_id,+ thread=thread,+ account_id=account_id,+ defaults={+ "account_external_id": link.account_external_id,+ "match_source": link.match_source,+ },+ )+++def _email_thread_participant_summary(+ participant: EmailThreadParticipant,+) -> EmailThreadParticipantSummary:+ return EmailThreadParticipantSummary(+ email=participant.email,+ display_name=participant.display_name,+ kind=participant.kind,+ )+++def _account_email_thread_summary(thread: EmailThread) -> AccountEmailThreadSummary:+ prefetched_thread = cast(_EmailThreadWithFacadePrefetch, thread)+ return AccountEmailThreadSummary(+ id=str(thread.id),+ subject=thread.subject,+ preview=thread.preview,+ first_message_at=thread.first_message_at,+ last_message_at=thread.last_message_at,+ message_count=thread.message_count,+ participants=[+ _email_thread_participant_summary(participant) for participant in prefetched_thread.facade_participants+ ],+ )+++def list_account_email_threads(+ team_id: int,+ account_id: str,+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[AccountEmailThreadSummary], int]:+ participants = EmailThreadParticipant.objects.for_team(team_id).order_by("email")+ threads = (+ EmailThread.objects.for_team(team_id)+ .filter(account_links__team_id=team_id, account_links__account_id=account_id)+ .prefetch_related(Prefetch("participants", queryset=participants, to_attr="facade_participants"))+ .order_by(F("last_message_at").desc(nulls_last=True), "-id")+ )+ count = threads.count()+ return [_account_email_thread_summary(thread) for thread in threads[offset : offset + limit]], count+++def _email_thread_addresses(value: object) -> list[EmailThreadAddress]:+ if not isinstance(value, list):+ return []+ addresses: list[EmailThreadAddress] = []+ for item in value:+ if not isinstance(item, dict):+ continue+ email = item.get("email")+ name = item.get("name", "")+ if isinstance(email, str) and isinstance(name, str):+ addresses.append(EmailThreadAddress(name=name, email=email))+ return addresses+++def get_account_email_thread(+ team_id: int,+ account_id: str,+ thread_id: str,+) -> AccountEmailThreadDetail | None:+ participants = EmailThreadParticipant.objects.for_team(team_id).order_by("email")+ thread = (+ EmailThread.objects.for_team(team_id)+ .filter(+ id=thread_id,+ account_links__team_id=team_id,+ account_links__account_id=account_id,+ )+ .prefetch_related(Prefetch("participants", queryset=participants, to_attr="facade_participants"))+ .first()+ )+ if thread is None:+ return None++ messages = (+ EmailThreadMessage.objects.for_team(team_id)+ .filter(thread=thread)+ .select_related("comment")+ .order_by("sent_at", "id")+ )+ summary = _account_email_thread_summary(thread)+ return AccountEmailThreadDetail(+ id=summary.id,+ subject=summary.subject,+ preview=summary.preview,+ first_message_at=summary.first_message_at,+ last_message_at=summary.last_message_at,+ message_count=summary.message_count,+ participants=summary.participants,+ messages=[+ AccountEmailThreadMessage(+ id=str(message.id),+ sent_at=message.sent_at,+ sender=EmailThreadAddress(name=message.sender_name, email=message.sender_email),+ to_recipients=_email_thread_addresses(message.to_recipients),+ cc_recipients=_email_thread_addresses(message.cc_recipients),+ sender_authenticated=message.sender_authenticated,+ direction=message.direction,+ content=message.comment.content or "",+ )+ for message in messages+ ],+ )diff --git a/products/conversations/backend/facade/types.py b/products/conversations/backend/facade/types.pyindex 387c9091dbe4..50eda8380e1f 100644--- a/products/conversations/backend/facade/types.py+++ b/products/conversations/backend/facade/types.py@@ -31,3 +31,57 @@ class TicketSummary:last_message_at: datetime | Nonelast_message_text: str | Nonedeep_link: str+++@dataclass(frozen=True)+class EmailThreadAccountLinkInput:+ account_id: str+ account_external_id: str | None+ match_source: str+++@dataclass(frozen=True)+class EmailThreadForAccountMatching:+ id: str+ participant_emails: list[str]+++@dataclass(frozen=True)+class EmailThreadParticipantSummary:+ email: str+ display_name: str+ kind: str+++@dataclass(frozen=True)+class AccountEmailThreadSummary:+ id: str+ subject: str+ preview: str+ first_message_at: datetime | None+ last_message_at: datetime | None+ message_count: int+ participants: list[EmailThreadParticipantSummary]+++@dataclass(frozen=True)+class EmailThreadAddress:+ name: str+ email: str+++@dataclass(frozen=True)+class AccountEmailThreadMessage:+ id: str+ sent_at: datetime+ sender: EmailThreadAddress+ to_recipients: list[EmailThreadAddress]+ cc_recipients: list[EmailThreadAddress]+ sender_authenticated: bool+ direction: str+ content: str+++@dataclass(frozen=True)+class AccountEmailThreadDetail(AccountEmailThreadSummary):+ messages: list[AccountEmailThreadMessage]diff --git a/products/conversations/backend/migrations/0062_emailthreadaccountlink.py b/products/conversations/backend/migrations/0062_emailthreadaccountlink.pynew file mode 100644index 000000000000..432c9534b053--- /dev/null+++ b/products/conversations/backend/migrations/0062_emailthreadaccountlink.py@@ -0,0 +1,79 @@+# Generated by Django 5.2.17 on 2026-08-10 17:46++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0061_emailchannelsetup_emailchannel_connection_status_and_more"),+ ("posthog", "1297_add_instagram_integration_kind"),+ ]++ operations = [+ migrations.CreateModel(+ name="EmailThreadAccountLink",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("account_id", models.CharField(max_length=64)),+ (+ "account_external_id",+ models.CharField(blank=True, max_length=400, null=True),+ ),+ (+ "match_source",+ models.CharField(+ choices=[+ ("known_email", "Known email"),+ ("person_group", "Person group"),+ ("email_domain", "Email domain"),+ ],+ max_length=32,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ (+ "thread",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="account_links",+ to="conversations.emailthread",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_email_thread_account_link",+ "indexes": [+ models.Index(+ fields=["team", "account_id", "thread"],+ name="email_link_team_account_idx",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "thread", "account_id"),+ name="unique_email_thread_account_link",+ )+ ],+ },+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex f913e76692c0..c184b66d8fcc 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0061_emailchannelsetup_emailchannel_connection_status_and_more+0062_emailthreadaccountlink\ No newline at end of filediff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex b329eae615bd..dc2ad77f8e4b 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -6,6 +6,8 @@ from .email_outbox_message import EmailOutboxMessagefrom .email_thread import (EMAIL_THREAD_COMMENT_SCOPE,EmailThread,+ EmailThreadAccountLink,+ EmailThreadAccountMatchSource,EmailThreadMessage,EmailThreadMessageDirection,EmailThreadParticipant,@@ -36,6 +38,8 @@ __all__ = ["EmailOutboxMessage","EMAIL_THREAD_COMMENT_SCOPE","EmailThread",+ "EmailThreadAccountLink",+ "EmailThreadAccountMatchSource","EmailThreadMessage","EmailThreadMessageDirection","EmailThreadParticipant",diff --git a/products/conversations/backend/models/email_thread.py b/products/conversations/backend/models/email_thread.pyindex 259144ffff8b..00c1fbbe2ca8 100644--- a/products/conversations/backend/models/email_thread.py+++ b/products/conversations/backend/models/email_thread.py@@ -6,6 +6,12 @@ from posthog.models.utils import UUIDModelEMAIL_THREAD_COMMENT_SCOPE = "EmailThread"+class EmailThreadAccountMatchSource(models.TextChoices):+ KNOWN_EMAIL = "known_email", "Known email"+ PERSON_GROUP = "person_group", "Person group"+ EMAIL_DOMAIN = "email_domain", "Email domain"++class EmailThreadMessageDirection(models.TextChoices):INBOUND = "inbound", "Inbound"OUTBOUND = "outbound", "Outbound"@@ -40,6 +46,28 @@ class EmailThread(TeamScopedRootMixin, UUIDModel):]+class EmailThreadAccountLink(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ 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)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_conversations_email_thread_account_link"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "thread", "account_id"],+ name="unique_email_thread_account_link",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "account_id", "thread"], name="email_link_team_account_idx"),+ ]++class EmailThreadMessage(TeamScopedRootMixin, UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)thread = models.ForeignKey("conversations.EmailThread", on_delete=models.CASCADE, related_name="messages")diff --git a/products/conversations/backend/person_lookup.py b/products/conversations/backend/person_lookup.pyindex 0adbc8ea0427..afb5adaa278d 100644--- a/products/conversations/backend/person_lookup.py+++ b/products/conversations/backend/person_lookup.py@@ -22,6 +22,13 @@ WHERE lower(properties.email) IN {emails}ORDER BY is_identified DESC, created_at ASC, id ASC"""+GROUP_KEY_BY_DISTINCT_ID_QUERY = """+SELECT distinct_id, argMaxIf({group_column}, timestamp, {group_column} != '') AS group_key+FROM events+WHERE distinct_id IN {{distinct_ids}} AND timestamp > now() - INTERVAL 90 DAY+GROUP BY distinct_id+"""+def _get_persons_by_email(team: Team,@@ -69,3 +76,34 @@ def _get_persons_by_email(if person is not None:result[email_lower] = personreturn result+++def get_group_keys_by_email(*, team: Team, emails: list[str], group_type_index: int) -> dict[str, str | None]:+ if group_type_index not in range(5):+ return {}+ persons_by_email = _get_persons_by_email(team, emails)+ distinct_id_to_email = {+ distinct_id: email for email, person in persons_by_email.items() for distinct_id in person.distinct_ids or []+ }+ if not distinct_id_to_email:+ return {}++ group_column = f"`$group_{group_type_index}`"+ query = GROUP_KEY_BY_DISTINCT_ID_QUERY.format(group_column=group_column)+ with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):+ response = execute_hogql_query(+ query,+ placeholders={"distinct_ids": ast.Constant(value=sorted(distinct_id_to_email))},+ team=team,+ query_type="conversations_email_group_lookup",+ )++ group_keys_by_email: dict[str, set[str]] = {}+ for distinct_id, group_key in response.results or []:+ email = distinct_id_to_email.get(distinct_id)+ if email and group_key:+ group_keys_by_email.setdefault(email, set()).add(group_key)+ return {+ email: next(iter(group_keys)) if len(group_keys) == 1 else None+ for email, group_keys in group_keys_by_email.items()+ }diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.pyindex 293baea862bb..1d1f585b2cdb 100644--- a/products/conversations/backend/services/email_thread_ingestion.py+++ b/products/conversations/backend/services/email_thread_ingestion.py@@ -19,6 +19,9 @@ from products.conversations.backend.models import (EmailThreadParticipant,EmailThreadParticipantKind,)+from products.customer_analytics.backend.facade.email_matching import (+ schedule_email_thread_link_recalculation_for_threads,+)@dataclass(frozen=True, kw_only=True)@@ -267,13 +270,16 @@ def ingest_customer_email() -> EmailThreadIngestionResult:try:with transaction.atomic():- return _ingest_customer_email_once(team_id=team_id, channel=channel, email=email)+ result = _ingest_customer_email_once(team_id=team_id, channel=channel, email=email)except IntegrityError:existing_message = _find_existing_message(team_id=team_id, email=email)if existing_message is None:raise- return EmailThreadIngestionResult(+ result = EmailThreadIngestionResult(thread_id=existing_message.thread_id,message_id=existing_message.id,created=False,)++ schedule_email_thread_link_recalculation_for_threads(team_id, [str(result.thread_id)])+ return resultdiff --git a/products/conversations/backend/tests/test_email_thread_account_links.py b/products/conversations/backend/tests/test_email_thread_account_links.pynew file mode 100644index 000000000000..252919c37ff6--- /dev/null+++ b/products/conversations/backend/tests/test_email_thread_account_links.py@@ -0,0 +1,123 @@+from posthog.test.base import BaseTest++from django.utils import timezone++from posthog.models.comment import Comment++from products.conversations.backend.facade.api import (+ get_account_email_thread,+ list_account_email_threads,+ list_email_threads_for_account_matching,+ replace_email_thread_account_links,+)+from products.conversations.backend.facade.types import EmailThreadAccountLinkInput+from products.conversations.backend.models import (+ EMAIL_THREAD_COMMENT_SCOPE,+ EmailThread,+ EmailThreadAccountLink,+ EmailThreadMessage,+ EmailThreadMessageDirection,+ EmailThreadParticipant,+ EmailThreadParticipantKind,+)+++class TestEmailThreadAccountLinks(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ sent_at = timezone.now()+ self.thread = EmailThread.objects.for_team(self.team.id).create(+ team=self.team,+ canonical_thread_key="<[email protected]>",+ subject="Account review",+ first_message_at=sent_at,+ last_message_at=sent_at,+ message_count=1,+ preview="Latest update",+ )+ comment = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(self.thread.id),+ content="Latest update",+ )+ self.message = EmailThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ comment=comment,+ message_id="<[email protected]>",+ sent_at=sent_at,+ sender_email="[email protected]",+ sender_name="Customer",+ to_recipients=[{"name": "CSM", "email": "[email protected]"}],+ cc_recipients=[],+ sender_authenticated=True,+ direction=EmailThreadMessageDirection.INBOUND,+ source_type="mailgun",+ source_id="<[email protected]>",+ )+ EmailThreadParticipant.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ email="[email protected]",+ display_name="Customer",+ kind=EmailThreadParticipantKind.CUSTOMER,+ )+ EmailThreadParticipant.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ email="[email protected]",+ display_name="CSM",+ kind=EmailThreadParticipantKind.INTERNAL,+ )++ def test_replaces_links_and_exposes_account_scoped_thread_contracts(self) -> None:+ matching_threads = list_email_threads_for_account_matching(self.team.id)+ assert len(matching_threads) == 1+ assert matching_threads[0].participant_emails == ["[email protected]"]++ replace_email_thread_account_links(+ self.team.id,+ str(self.thread.id),+ [+ EmailThreadAccountLinkInput(+ account_id="account-1",+ account_external_id="group-1",+ match_source="known_email",+ ),+ EmailThreadAccountLinkInput(+ account_id="account-2",+ account_external_id="group-2",+ match_source="email_domain",+ ),+ ],+ )++ summaries, count = list_account_email_threads(self.team.id, "account-1")+ detail = get_account_email_thread(self.team.id, "account-1", str(self.thread.id))+ assert count == 1+ assert len(summaries) == 1+ assert summaries[0].subject == "Account review"+ assert detail is not None+ assert detail.id == str(self.thread.id)+ assert detail.messages[0].content == "Latest update"+ assert detail.messages[0].sender_authenticated is True+ assert detail.messages[0].to_recipients[0].email == "[email protected]"++ replace_email_thread_account_links(+ self.team.id,+ str(self.thread.id),+ [+ EmailThreadAccountLinkInput(+ account_id="account-2",+ account_external_id="renamed-group-2",+ match_source="person_group",+ )+ ],+ )++ 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 get_account_email_thread(self.team.id, "account-1", str(self.thread.id)) is Nonediff --git a/products/conversations/backend/tests/test_email_threads.py b/products/conversations/backend/tests/test_email_threads.pyindex 6157e7334f9d..3eea243cc040 100644--- a/products/conversations/backend/tests/test_email_threads.py+++ b/products/conversations/backend/tests/test_email_threads.py@@ -15,6 +15,7 @@ from products.conversations.backend.models import (EmailChannel,EmailChannelKind,EmailThread,+ EmailThreadAccountLink,EmailThreadMessage,EmailThreadMessageDirection,EmailThreadParticipant,@@ -210,6 +211,13 @@ class TestEmailThreadPersistence(BaseTest):display_name="Example customer",kind=EmailThreadParticipantKind.CUSTOMER,)+ EmailThreadAccountLink.objects.for_team(self.team.id).create(+ team=self.team,+ thread=thread,+ account_id="account-1",+ account_external_id="group-1",+ match_source="known_email",+ )orphaned_content = Comment.objects.create(team=self.team,scope=EMAIL_THREAD_COMMENT_SCOPE,@@ -228,6 +236,7 @@ class TestEmailThreadPersistence(BaseTest):assert not EmailThread.objects.for_team(self.team.id).filter(id=thread.id).exists()assert not EmailThreadMessage.objects.for_team(self.team.id).filter(id=message.id).exists()assert not EmailThreadParticipant.objects.for_team(self.team.id).filter(thread_id=thread.id).exists()+ assert not EmailThreadAccountLink.objects.for_team(self.team.id).filter(thread_id=thread.id).exists()assert not Comment.objects.filter(id__in=[message.comment_id, orphaned_content.id]).exists()assert Comment.objects.filter(id=unrelated.id).exists()diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 1a7614fff854..252b6eafa5ad 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -84,6 +84,7 @@ from products.customer_analytics.backend.events import emit_account_tags_addedfrom products.customer_analytics.backend.facade.contracts import (InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,)+from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculationfrom products.customer_analytics.backend.logic import (announcements as _announcements_logic,channel_summaries as _channel_summaries_logic,@@ -157,8 +158,6 @@ from . import contracts# sets keyed by definition id under its ``properties`` input — the link we resolve into references.logger = structlog.get_logger(__name__)-logger = structlog.get_logger(__name__)-_ACCOUNT_PROPERTY_TEMPLATE_ID = "template-posthog-update-account-property"_ACCOUNT_PROPERTY_INPUT_KEY = "properties"@@ -2981,6 +2980,8 @@ 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:+ schedule_email_thread_link_recalculation(account.team_id)return account@@ -3029,6 +3030,7 @@ def create_account(was_impersonated=was_impersonated,trigger=trigger,)+ schedule_email_thread_link_recalculation(team.pk)return account@@ -3205,6 +3207,7 @@ def delete_account_for_view(streams = _event_streams_containing_account(account)team = account.teamaccount.delete()+ schedule_email_thread_link_recalculation(team_id)for stream in streams:sync_event_stream_destination(stream, team=team, user=user)diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex f50b29b917de..ebaa3d0618ce 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -92,6 +92,13 @@ class Account:created_at: datetime | None+@dataclass(frozen=True)+class EmailAccountMatch:+ account_id: str+ account_external_id: str | None+ match_source: str++@dataclass(frozen=True)class AccountDueForSlackSummary:"""An account whose bound Slack channel is due a periodic summary.diff --git a/products/customer_analytics/backend/facade/email_matching.py b/products/customer_analytics/backend/facade/email_matching.pynew file mode 100644index 000000000000..486610a7fef0--- /dev/null+++ b/products/customer_analytics/backend/facade/email_matching.py@@ -0,0 +1,165 @@+from django.core.cache import cache+from django.db import transaction++import structlog+from celery import current_app++from posthog.models.team import Team++from products.conversations.backend.facade import api as conversations+from products.conversations.backend.facade.types import EmailThreadAccountLinkInput+from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.logic.email_account_matching import (+ MatchedAccount,+ match_accounts_for_emails,+ normalize_emails,+)++logger = structlog.get_logger(__name__)++_MATCH_SOURCE_PRIORITY = {"known_email": 0, "person_group": 1, "email_domain": 2}+_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+++def _recalculation_cache_key(team_id: int) -> str:+ return f"customer_analytics:email_thread_link_recalculation:{team_id}"+++def _recalculation_dirty_cache_key(team_id: int) -> str:+ return f"customer_analytics:email_thread_link_recalculation_dirty:{team_id}"+++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)):+ schedule_email_thread_link_recalculation(team_id)+++def _enqueue_full_recalculation(team_id: int, cache_key: str) -> None:+ try:+ current_app.send_task(_RECALCULATION_TASK, args=[team_id])+ except Exception:+ cache.delete(cache_key)+ logger.exception("email_thread_link_recalculation_enqueue_failed", team_id=team_id)+++def schedule_email_thread_link_recalculation(team_id: int) -> None:+ def enqueue() -> None:+ cache_key = _recalculation_cache_key(team_id)+ if cache.add(cache_key, "1", timeout=_RECALCULATION_LOCK_SECONDS):+ _enqueue_full_recalculation(team_id, cache_key)+ return++ dirty_cache_key = _recalculation_dirty_cache_key(team_id)+ cache.set(dirty_cache_key, "1", timeout=_RECALCULATION_LOCK_SECONDS)+ if cache.add(cache_key, "1", timeout=_RECALCULATION_LOCK_SECONDS):+ cache.delete(dirty_cache_key)+ _enqueue_full_recalculation(team_id, cache_key)++ transaction.on_commit(enqueue)+++def schedule_email_thread_link_recalculation_for_threads(team_id: int, thread_ids: list[str]) -> None:+ unique_thread_ids = list(dict.fromkeys(thread_ids))+ if not unique_thread_ids:+ return++ def enqueue() -> None:+ try:+ current_app.send_task(_RECALCULATION_THREADS_TASK, args=[team_id, unique_thread_ids])+ except Exception:+ logger.exception(+ "email_thread_link_recalculation_enqueue_failed",+ team_id=team_id,+ thread_ids=unique_thread_ids,+ )++ 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):+ match = matches_by_email[email]+ account_id = str(match.account.id)+ candidate = contracts.EmailAccountMatch(+ account_id=account_id,+ account_external_id=match.account.external_id,+ match_source=match.source,+ )+ current = matches_by_account_id.get(account_id)+ if (+ current is None+ or _MATCH_SOURCE_PRIORITY[candidate.match_source] < _MATCH_SOURCE_PRIORITY[current.match_source]+ ):+ matches_by_account_id[account_id] = candidate+ return list(matches_by_account_id.values())+++def _match_email_accounts(team: Team, emails: list[str]) -> list[contracts.EmailAccountMatch]:+ return _dedupe_account_matches(match_accounts_for_emails(team, emails))+++def match_email_accounts(team_id: int, emails: list[str]) -> list[contracts.EmailAccountMatch]:+ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ return []+ return _match_email_accounts(team, emails)+++def recalculate_email_thread_links(+ team_id: int,+ *,+ thread_ids: list[str] | None = None,+ batch_size: int = 100,+) -> int:+ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ 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,+ thread_ids=thread_ids,+ after_id=after_id,+ limit=batch_size,+ )+ 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]+ )+ for thread in threads:+ thread_matches = {+ email: page_matches[email]+ for email in normalize_emails(thread.participant_emails)+ if email in page_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,+ )+ for match in matches+ ],+ )+ processed += 1++ if len(threads) < batch_size:+ return processed+ after_id = threads[-1].iddiff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.pyindex 5f306e1dab91..4cf28b12cc78 100644--- a/products/customer_analytics/backend/logic/calendar_sync.py+++ b/products/customer_analytics/backend/logic/calendar_sync.py@@ -11,11 +11,9 @@ import structlogfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration-from posthog.models.person.person import Person-from posthog.models.person.util import get_persons_by_uuidsfrom posthog.models.team import Team-from posthog.personhog_client.caller_tag import personhog_caller_tag+from products.customer_analytics.backend.logic.email_account_matching import match_accounts_for_emailsfrom products.customer_analytics.backend.models import Account, Meeting, MeetingParticipant, MeetingStatuslogger = structlog.get_logger(__name__)@@ -36,13 +34,6 @@ WHERE lower(properties.email) IN {emails}ORDER BY is_identified DESC, created_at ASC, id ASC"""-GROUP_KEY_BY_DISTINCT_ID_QUERY = """-SELECT distinct_id, argMaxIf({group_col}, timestamp, {group_col} != '') AS group_key-FROM events-WHERE distinct_id IN {{distinct_ids}} AND timestamp > now() - INTERVAL 90 DAY-GROUP BY distinct_id-"""-class SyncTokenExpired(Exception):pass@@ -320,48 +311,7 @@ def rematch_account_meetings(team_id: int, account_id: str) -> int:def _match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, Account]:- """Resolve attendee emails to accounts: pinned known_emails first, then person- group links, then the email_domains fallback."""- if not emails:- return {}-- matched: dict[str, Account] = {}-- for email in emails:- candidates = list(Account.objects.for_team(team.id).filter(_properties__known_emails__contains=[email])[:2])- if len(candidates) == 1:- matched[email] = candidates[0]- elif len(candidates) > 1:- logger.warning("calendar_sync_ambiguous_known_email", team_id=team.id, email=email)-- group_type_index = team.customer_analytics_config.account_group_type_index- if group_type_index is not None:- unresolved = [email for email in emails if email not in matched]- email_to_group_key = _group_keys_via_persons(team, unresolved, group_type_index) if unresolved else {}- if email_to_group_key:- accounts = {- account.external_id: account- for account in Account.objects.for_team(team.id).filter(- external_id__in=set(email_to_group_key.values())- )- }- for email, group_key in email_to_group_key.items():- if group_key in accounts:- matched[email] = accounts[group_key]-- for email in emails:- if email in matched:- continue- domain = _domain_of(email)- if not domain:- continue- candidates = list(Account.objects.for_team(team.id).filter(_properties__email_domains__contains=[domain])[:2])- if len(candidates) == 1:- matched[email] = candidates[0]- elif len(candidates) > 1:- logger.warning("calendar_sync_ambiguous_email_domain", team_id=team.id, domain=domain)-- return matched+ return {email: match.account for email, match in match_accounts_for_emails(team, emails).items()}def _person_uuids_by_email(team: Team, emails: list[str]) -> dict[str, str]:@@ -386,44 +336,6 @@ def _person_uuids_by_email(team: Team, emails: list[str]) -> dict[str, str]:return email_to_uuid-def _group_keys_via_persons(team: Team, emails: list[str], group_type_index: int) -> dict[str, str]:- # Deferred: hogql.query pulls the whole query-runner layer into module import.- from posthog.hogql import ast # noqa: PLC0415- from posthog.hogql.query import execute_hogql_query # noqa: PLC0415-- email_to_uuid = _person_uuids_by_email(team, emails)- if not email_to_uuid:- return {}-- with personhog_caller_tag("customer_analytics/calendar-person-lookup"):- persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))- persons_by_uuid: dict[str, Person] = {str(p.uuid): p for p in persons}-- distinct_id_to_email: dict[str, str] = {}- for email, person_uuid in email_to_uuid.items():- person = persons_by_uuid.get(person_uuid)- for distinct_id in (person.distinct_ids or []) if person else []:- distinct_id_to_email[distinct_id] = email- if not distinct_id_to_email:- return {}-- query = GROUP_KEY_BY_DISTINCT_ID_QUERY.format(group_col=f"`$group_{group_type_index}`")- with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY):- response = execute_hogql_query(- query,- placeholders={"distinct_ids": ast.Constant(value=sorted(distinct_id_to_email))},- team=team,- query_type="customer_analytics_calendar_group_lookup",- )-- email_to_group_key: dict[str, str] = {}- for distinct_id, group_key in response.results or []:- matched_email = distinct_id_to_email.get(distinct_id)- if matched_email and group_key and matched_email not in email_to_group_key:- email_to_group_key[matched_email] = group_key- return email_to_group_key--def _get_fresh_access_token(integration: Integration) -> str:oauth = OauthIntegration(integration)if integration.errors != ERROR_TOKEN_REFRESH_FAILED and oauth.access_token_expired():diff --git a/products/customer_analytics/backend/logic/email_account_matching.py b/products/customer_analytics/backend/logic/email_account_matching.pynew file mode 100644index 000000000000..8063d7e0d6a8--- /dev/null+++ b/products/customer_analytics/backend/logic/email_account_matching.py@@ -0,0 +1,80 @@+from dataclasses import dataclass++import structlog++from posthog.models.team import Team++from products.conversations.backend.facade.api import resolve_group_keys_by_email+from products.customer_analytics.backend.models import Account++logger = structlog.get_logger(__name__)++KNOWN_EMAIL_MATCH = "known_email"+PERSON_GROUP_MATCH = "person_group"+EMAIL_DOMAIN_MATCH = "email_domain"+++@dataclass(frozen=True, kw_only=True)+class MatchedAccount:+ account: Account+ source: str+++def _record_ambiguity(*, team_id: int, source: str, candidate_count: int | None) -> None:+ logger.warning(+ "email_account_match_ambiguous",+ team_id=team_id,+ match_source=source,+ candidate_count=candidate_count,+ )+++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 {}++ 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])+ if len(candidates) == 1:+ matched[email] = MatchedAccount(account=candidates[0], source=KNOWN_EMAIL_MATCH)+ elif len(candidates) > 1:+ ambiguous.add(email)+ _record_ambiguity(team_id=team.id, source=KNOWN_EMAIL_MATCH, candidate_count=len(candidates))++ 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:+ continue+ domain = email.rsplit("@", 1)[-1]+ candidates = list(Account.objects.for_team(team.id).filter(_properties__email_domains__contains=[domain])[:2])+ 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))++ return matcheddiff --git a/products/customer_analytics/backend/tasks/__init__.py b/products/customer_analytics/backend/tasks/__init__.pyindex f62071890f9d..115e64d9c8a0 100644--- a/products/customer_analytics/backend/tasks/__init__.py+++ b/products/customer_analytics/backend/tasks/__init__.py@@ -1,6 +1,8 @@# Re-exported so Celery autodiscovers the tasks when the tasks package is imported.from products.customer_analytics.backend.tasks.tasks import ( # noqa: F401process_custom_property_sync,+ recalculate_email_thread_account_links,+ recalculate_email_thread_account_links_for_threads,rematch_account_meetings,send_announcement,)diff --git a/products/customer_analytics/backend/tasks/tasks.py b/products/customer_analytics/backend/tasks/tasks.pyindex f979cc3d0b9a..a76a3862ef25 100644--- a/products/customer_analytics/backend/tasks/tasks.py+++ b/products/customer_analytics/backend/tasks/tasks.py@@ -2,6 +2,10 @@ from celery import shared_taskfrom 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,+)from products.customer_analytics.backend.logic.announcements import send_pending_deliveriesfrom products.customer_analytics.backend.logic.custom_property_sync import run_custom_property_sync@@ -28,6 +32,33 @@ def rematch_account_meetings(team_id: int, account_id: str) -> None:run_meeting_rematch(team_id=team_id, account_id=account_id)+@shared_task(+ name="customer_analytics.recalculate_email_thread_account_links",+ ignore_result=True,+ autoretry_for=(Exception,),+ max_retries=3,+ retry_backoff=True,+ retry_jitter=True,+)+@with_team_scope()+def recalculate_email_thread_account_links(team_id: int) -> None:+ recalculate_email_thread_links(team_id)+ finish_email_thread_link_recalculation(team_id)+++@shared_task(+ name="customer_analytics.recalculate_email_thread_account_links_for_threads",+ 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_threads(team_id: int, thread_ids: list[str]) -> None:+ recalculate_email_thread_links(team_id, thread_ids=thread_ids)++# autoretry_for is load-bearing: bare max_retries kwargs without it are silently inert.@shared_task(name="customer_analytics.send_announcement",diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.pyindex 0e15d76a8e19..037a4dc977e8 100644--- a/products/customer_analytics/backend/test/test_calendar_sync.py+++ b/products/customer_analytics/backend/test/test_calendar_sync.py@@ -152,22 +152,16 @@ class TestCalendarSync(BaseTest):self._sync([_pages_response([event])])assert Meeting.objects.for_team(self.team.id).get().account_id == account.id- def test_matches_account_via_person_group(self) -> None:+ @patch(+ "products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email",+ return_value={"[email protected]": "acme"},+ )+ def test_matches_account_via_person_group(self, _mock_group_keys: MagicMock) -> None:self.team.customer_analytics_config.account_group_type_index = 0self.team.customer_analytics_config.save()account = Account.objects.for_team(self.team.id).create(team=self.team, name="Acme", external_id="acme")- person_uuid = "0198b6f3-0000-0000-0000-000000000001"- person = MagicMock(uuid=person_uuid, distinct_ids=["person-distinct-id"])- group_query_response = MagicMock(results=[["person-distinct-id", "acme"]])- with (- patch.object(calendar_sync, "get_persons_by_uuids", return_value=[person]),- patch("posthog.hogql.query.execute_hogql_query", return_value=group_query_response),- ):- counts = self._sync(- [_pages_response([_event()])],- person_uuids={"[email protected]": person_uuid},- )+ counts = self._sync([_pages_response([_event()])])assert Meeting.objects.for_team(self.team.id).get().account_id == account.idassert counts.matched == 1diff --git a/products/customer_analytics/backend/test/test_email_account_matching.py b/products/customer_analytics/backend/test/test_email_account_matching.pynew file mode 100644index 000000000000..edebad269764--- /dev/null+++ b/products/customer_analytics/backend/test/test_email_account_matching.py@@ -0,0 +1,196 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.conversations.backend.facade.types import EmailThreadForAccountMatching+from products.customer_analytics.backend.facade import api+from products.customer_analytics.backend.facade.email_matching import (+ finish_email_thread_link_recalculation,+ match_email_accounts,+ recalculate_email_thread_links,+ 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.models import Account+++class TestEmailAccountMatching(BaseTest):+ def _create_account(+ self,+ *,+ name: str,+ external_id: str,+ known_emails: list[str] | None = None,+ email_domains: list[str] | None = None,+ ) -> Account:+ return Account.objects.for_team(self.team.id).create(+ team=self.team,+ name=name,+ external_id=external_id,+ _properties={+ "known_emails": known_emails or [],+ "email_domains": email_domains or [],+ },+ )++ @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:+ 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"],+ )+ grouped = self._create_account(name="Grouped", external_id="group-account")+ domain = self._create_account(+ name="Domain",+ external_id="domain-account",+ email_domains=["domain.example"],+ )++ matches = match_email_accounts(+ self.team.id,+ )++ assert {(match.account_id, match.match_source) for match in matches} == {+ (str(known.id), "known_email"),+ (str(grouped.id), "person_group"),+ (str(domain.id), "email_domain"),+ }++ @patch(+ "products.customer_analytics.backend.logic.email_account_matching.resolve_group_keys_by_email",+ return_value={},+ )+ def test_ambiguous_known_email_does_not_fall_through_to_domain(self, _mock_group_keys: MagicMock) -> None:+ for external_id in ("first", "second"):+ self._create_account(+ name=external_id,+ external_id=external_id,+ known_emails=["[email protected]"],+ )+ self._create_account(+ name="Domain fallback",+ external_id="domain-fallback",+ email_domains=["ambiguous.example"],+ )++ matches = match_email_accounts(self.team.id, ["[email protected]"])++ assert matches == []++ @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.facade.email_matching.match_accounts_for_emails")+ def test_recalculation_matches_once_per_page_and_maps_links_per_thread(+ self,+ mock_match: MagicMock,+ mock_list_threads: MagicMock,+ mock_replace: MagicMock,+ ) -> None:+ first = self._create_account(name="First", external_id="first-account")+ 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]"]),+ ],+ [],+ ]+ mock_match.return_value = {+ "[email protected]": MatchedAccount(account=first, source="person_group"),+ "[email protected]": MatchedAccount(account=second, source="email_domain"),+ }++ 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()+ 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")]+ assert [(link.account_id, link.match_source) for link in links_by_thread["thread-2"]] == [+ (str(second.id), "email_domain")+ ]++ @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):+ account = api.create_account(+ team=self.team,+ name="Account",+ external_id="account",+ properties={"known_emails": ["[email protected]"]},+ )++ mock_schedule.assert_called_once_with(self.team.id)+ mock_schedule.reset_mock()++ with self.captureOnCommitCallbacks(execute=True):+ api.update_account(+ account,+ properties={"email_domains": ["example.com"]},+ allow_matching_updates=True,+ )++ mock_schedule.assert_called_once_with(self.team.id)++ @parameterized.expand(+ [+ ("active_run", False, False),+ ("run_finished_during_schedule", True, True),+ ]+ )+ @patch("products.customer_analytics.backend.facade.email_matching.current_app.send_task")+ @patch("products.customer_analytics.backend.facade.email_matching.cache")+ def test_recalculation_requested_during_a_run_is_not_lost(+ self,+ _name: str,+ second_lock_acquired: bool,+ expected_enqueue: bool,+ mock_cache: MagicMock,+ mock_send_task: MagicMock,+ ) -> None:+ mock_cache.add.side_effect = [False, second_lock_acquired]++ with self.captureOnCommitCallbacks(execute=True):+ schedule_email_thread_link_recalculation(self.team.id)++ mock_cache.set.assert_called_once()+ if expected_enqueue:+ mock_send_task.assert_called_once()+ else:+ mock_send_task.assert_not_called()++ @patch("products.customer_analytics.backend.facade.email_matching.current_app.send_task")+ def test_targeted_recalculation_is_enqueued_after_commit(self, mock_send_task: MagicMock) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ schedule_email_thread_link_recalculation_for_threads(self.team.id, ["thread-1", "thread-1"])++ mock_send_task.assert_called_once_with(+ "customer_analytics.recalculate_email_thread_account_links_for_threads",+ args=[self.team.id, ["thread-1"]],+ )++ @patch("products.customer_analytics.backend.facade.email_matching.schedule_email_thread_link_recalculation")+ @patch("products.customer_analytics.backend.facade.email_matching.cache")+ def test_finished_recalculation_schedules_dirty_follow_up(+ self, mock_cache: MagicMock, mock_schedule: MagicMock+ ) -> None:+ mock_cache.delete.side_effect = [True, True]++ finish_email_thread_link_recalculation(self.team.id)++ mock_schedule.assert_called_once_with(self.team.id)diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex de42056d0a36..b2b549a11f53 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -854,7 +854,7 @@ class AccountUpdateWriteTest(TeamScopedTestMixin, BaseTest):allow_matching_updates=True,)- mock_send_task.assert_called_once_with(+ mock_send_task.assert_any_call("customer_analytics.rematch_account_meetings",kwargs={"team_id": self.team.pk, "account_id": str(account.id)},)