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.

feat(billing): sync Conversations Slack signals to Salesforce accounts (#66974)

Abhischek5216c90b9b66
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index d639e6cafa21..c594459b8e70 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -2,6 +2,7 @@ REDIS_TTL_SECONDS: int = 12 * 60 * 60 # 12h
SALESFORCE_ACCOUNTS_CACHE_KEY: str = "salesforce-enrichment:global:all_accounts"
SALESFORCE_ORG_MAPPINGS_CACHE_KEY: str = "salesforce-enrichment:global:org_mappings"
SALESFORCE_STRIPE_ENRICHMENT_WATERMARK_KEY: str = "salesforce-enrichment:stripe:last_watermark"
+ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE: str = "OrgMappingsCacheMissing"
HARMONIC_BASE_URL: str = "https://api.harmonic.ai"
YC_INVESTOR_NAME: str = "y combinator"
HARMONIC_DEFAULT_MAX_CONCURRENT_REQUESTS: int = 5 # rate limit: 10/s
@@ -146,6 +147,17 @@ STRIPE_ENRICHMENT_FIELD_MAPPINGS: dict[str, str] = {
"address_country": "BillingCountry",
}
+CONVERSATIONS_SLACK_ENRICHMENT_BATCH_SIZE: int = 100
+
+
+CONVERSATIONS_SLACK_FIELD_MAPPINGS: dict[str, str] = {
+ "slack_channel_url": "Slack_Channel__c",
+ "slack_issue_count": "slack_issue_count__c",
+ "slack_user_count": "slack_user_count__c",
+ "last_slack_activity": "last_slack_activity__c",
+ "most_recent_support_ticket_url": "Most_Recent_Support_Ticket__c",
+}
+
PERSONAL_EMAIL_DOMAINS = {
"gmail.com",
"yahoo.com",
diff --git a/ee/billing/salesforce_enrichment/conversations_signals.py b/ee/billing/salesforce_enrichment/conversations_signals.py
new file mode 100644
index 000000000000..9ee584095ae8
--- /dev/null
+++ b/ee/billing/salesforce_enrichment/conversations_signals.py
@@ -0,0 +1,279 @@
+"""Conversations Slack signals aggregation for Salesforce enrichment."""
+
+import datetime as dt
+from dataclasses import dataclass
+
+from django.conf import settings
+from django.db.models import Case, Count, DateTimeField, Exists, Max, Min, OuterRef, Q, QuerySet, UUIDField, When
+from django.db.models.functions import Cast, Coalesce
+
+from slack_sdk import WebClient
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.organization import OrganizationMembership
+from posthog.temporal.common.logger import get_logger
+
+from products.conversations.backend.models import TeamConversationsSlackConfig, Ticket
+from products.conversations.backend.models.constants import Channel
+
+LOGGER = get_logger(__name__)
+MAX_SLACK_MEMBER_PAGES = 100
+_UUID_REGEX = r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
+
+
+@dataclass
+class ConversationsSlackSignals:
+ """Slack support signals for a single PostHog organization."""
+
+ posthog_organization_id: str
+ slack_channel_url: str | None
+ slack_issue_count: int
+ slack_user_count: int | None
+ last_slack_activity: dt.datetime | None
+ most_recent_support_ticket_url: str | None
+
+
+def build_slack_channel_url(slack_channel_id: str, slack_team_id: str | None = None) -> str:
+ """Build a stable Slack channel URL from Slack IDs."""
+ if slack_team_id:
+ return f"https://app.slack.com/client/{slack_team_id}/{slack_channel_id}"
+ return f"https://app.slack.com/archives/{slack_channel_id}"
+
+
+def build_support_ticket_url(team_id: int, ticket_number: int) -> str:
+ return f"{settings.SITE_URL.rstrip('/')}/project/{team_id}/support/tickets/{ticket_number}"
+
+
+def _get_slack_bot_token(slack_team_id: str | None, team_id: int | None) -> str | None:
+ """Resolve the Slack bot token that can read a channel.
+
+ The bot lives in the channel's Slack workspace, so match the config by
+ ``slack_team_id`` (unique per workspace) first and fall back to the
+ representative PostHog team only when the workspace id is unknown.
+ """
+ configs = TeamConversationsSlackConfig.objects.filter(slack_bot_token__isnull=False).only("slack_bot_token")
+
+ config = configs.filter(slack_team_id=slack_team_id).first() if slack_team_id else None
+ if config is None and team_id is not None:
+ config = configs.filter(team_id=team_id).first()
+
+ if not config or not config.slack_bot_token:
+ return None
+ return str(config.slack_bot_token)
+
+
+def fetch_slack_channel_user_count(team_id: int, slack_channel_id: str, slack_team_id: str | None = None) -> int | None:
+ """Fetch the current Slack channel member count using the channel's support bot token."""
+ bot_token = _get_slack_bot_token(slack_team_id, team_id)
+ if not bot_token:
+ return None
+
+ client = WebClient(token=bot_token)
+ cursor: str | None = None
+ user_count = 0
+
+ for _ in range(MAX_SLACK_MEMBER_PAGES):
+ try:
+ response = client.conversations_members(
+ channel=slack_channel_id,
+ cursor=cursor,
+ limit=1000,
+ )
+ except SlackApiError as e:
+ LOGGER.warning(
+ "slack_channel_user_count_fetch_failed",
+ team_id=team_id,
+ slack_channel_id=slack_channel_id,
+ error=e.response.get("error"),
+ )
+ return None
+ except Exception as e:
+ LOGGER.warning(
+ "slack_channel_user_count_fetch_error",
+ team_id=team_id,
+ slack_channel_id=slack_channel_id,
+ error=str(e),
+ )
+ return None
+
+ members = response.get("members") or []
+ user_count += len(members)
+
+ response_metadata = response.get("response_metadata") or {}
+ cursor = response_metadata.get("next_cursor") or None
+ if not cursor:
+ return user_count
+
+ LOGGER.warning(
+ "slack_channel_user_count_too_many_pages",
+ team_id=team_id,
+ slack_channel_id=slack_channel_id,
+ max_pages=MAX_SLACK_MEMBER_PAGES,
+ )
+ return None
+
+
+def _activity_at() -> Coalesce:
+ """Most recent activity timestamp for a ticket, preferring the newest available signal."""
+ return Coalesce("last_message_at", "updated_at", "created_at", output_field=DateTimeField())
+
+
+def _tickets_with_verified_org() -> QuerySet[Ticket]:
+ """Tickets whose organization attribution is confirmed through a trusted path.
+
+ ``Ticket.organization_id`` can be stamped from an authoritative
+ ``OrganizationMembership`` lookup, but also from analytics ``$groups``,
+ which are customer-supplied and spoofable. Before an org is used as a
+ Salesforce Account key, re-verify it here: the ticket's customer identity
+ (the widget's real distinct_id, or the provider-supplied email that the
+ Slack/Teams/email channels store in ``distinct_id``/``email_from``) must
+ belong to a member of that organization, and that identity must carry a
+ positive attestation (``identity_verified=True``).
+ """
+ membership_for_ticket_org = OrganizationMembership.objects.filter(
+ organization_id=OuterRef("organization_uuid")
+ ).filter(
+ Q(user__distinct_id=OuterRef("distinct_id"))
+ | Q(user__email__iexact=OuterRef("distinct_id"))
+ | Q(user__email__iexact=OuterRef("email_from"))
+ )
+ return (
+ # organization_id is free text (analytics-derived values are arbitrary), so
+ # guard the uuid cast with CASE — an unguarded cast would abort the whole
+ # query on the first malformed row. Comparing as uuid also lets the
+ # membership organization_id index anchor the EXISTS.
+ Ticket.objects.annotate(
+ organization_uuid=Case(
+ When(organization_id__regex=_UUID_REGEX, then=Cast("organization_id", output_field=UUIDField())),
+ output_field=UUIDField(),
+ )
+ ).filter(Exists(membership_for_ticket_org), identity_verified=True)
+ )
+
+
+def _fetch_slack_channel_aggregate_rows(org_ids: list[str]) -> list[dict[str, object]]:
+ if not org_ids:
+ return []
+
+ return list(
+ _tickets_with_verified_org()
+ .filter(
+ channel_source=Channel.SLACK,
+ organization_id__in=org_ids,
+ slack_channel_id__isnull=False,
+ )
+ .exclude(slack_channel_id="")
+ .annotate(activity_at=_activity_at())
+ # Slack channel IDs are only unique within a workspace, so group by
+ # (org, workspace, channel) to avoid merging unrelated channels.
+ .values("organization_id", "slack_team_id", "slack_channel_id")
+ .annotate(
+ representative_team_id=Min("team_id"),
+ slack_issue_count=Count("id"),
+ last_slack_activity=Max("activity_at"),
+ )
+ .order_by(
+ "organization_id",
+ "-last_slack_activity",
+ "-slack_issue_count",
+ "slack_channel_id",
+ "slack_team_id",
+ )
+ )
+
+
+def _fetch_latest_support_ticket_rows(org_ids: list[str]) -> list[dict[str, object]]:
+ if not org_ids:
+ return []
+
+ return list(
+ _tickets_with_verified_org()
+ .filter(organization_id__in=org_ids)
+ .annotate(activity_at=_activity_at())
+ .values("organization_id", "team_id", "ticket_number", "activity_at")
+ .order_by("organization_id", "-activity_at", "-ticket_number")
+ .distinct("organization_id")
+ )
+
+
+def aggregate_conversations_slack_signals_for_orgs(
+ org_ids: list[str],
+ *,
+ include_slack_user_count: bool = True,
+) -> dict[str, ConversationsSlackSignals]:
+ """Aggregate Conversations Slack signals for organizations.
+
+ Only tickets with verified org attribution count (see
+ ``_tickets_with_verified_org``). If an organization has multiple Slack
+ channels, choose the most recently active workspace-scoped channel, then
+ tie-break by ticket count and channel ID. Salesforce exposes a single
+ Slack channel field, so the issue/user/activity stats are for that
+ representative channel.
+ """
+ if not org_ids:
+ return {}
+
+ LOGGER.info("fetching_conversations_slack_signals", org_count=len(org_ids))
+ rows = _fetch_slack_channel_aggregate_rows(org_ids)
+ latest_ticket_rows = _fetch_latest_support_ticket_rows(org_ids)
+
+ selected_rows: dict[str, dict[str, object]] = {}
+ for row in rows:
+ org_id = str(row["organization_id"])
+ if org_id not in selected_rows:
+ selected_rows[org_id] = row
+
+ selected_latest_ticket_rows: dict[str, dict[str, object]] = {}
+ for row in latest_ticket_rows:
+ org_id = str(row["organization_id"])
+ if org_id not in selected_latest_ticket_rows:
+ selected_latest_ticket_rows[org_id] = row
+
+ result: dict[str, ConversationsSlackSignals] = {}
+ for org_id in sorted(set(selected_rows) | set(selected_latest_ticket_rows)):
+ row = selected_rows.get(org_id, {})
+ slack_channel_id_value = row.get("slack_channel_id")
+ slack_channel_id = (
+ slack_channel_id_value if isinstance(slack_channel_id_value, str) and slack_channel_id_value else None
+ )
+
+ slack_team_id_value = row.get("slack_team_id")
+ slack_team_id = slack_team_id_value if isinstance(slack_team_id_value, str) and slack_team_id_value else None
+
+ team_id_value = row.get("representative_team_id")
+ team_id = int(team_id_value) if isinstance(team_id_value, int) else None
+
+ slack_user_count = (
+ fetch_slack_channel_user_count(team_id, slack_channel_id, slack_team_id)
+ if include_slack_user_count and team_id is not None and slack_channel_id is not None
+ else None
+ )
+
+ last_slack_activity_value = row.get("last_slack_activity")
+ last_slack_activity = last_slack_activity_value if isinstance(last_slack_activity_value, dt.datetime) else None
+
+ latest_ticket_row = selected_latest_ticket_rows.get(org_id, {})
+ ticket_team_id_value = latest_ticket_row.get("team_id")
+ ticket_number_value = latest_ticket_row.get("ticket_number")
+ most_recent_support_ticket_url = (
+ build_support_ticket_url(int(ticket_team_id_value), int(ticket_number_value))
+ if isinstance(ticket_team_id_value, int) and isinstance(ticket_number_value, int)
+ else None
+ )
+
+ slack_issue_count_value = row.get("slack_issue_count")
+ slack_issue_count = slack_issue_count_value if isinstance(slack_issue_count_value, int) else 0
+
+ result[org_id] = ConversationsSlackSignals(
+ posthog_organization_id=org_id,
+ slack_channel_url=(
+ build_slack_channel_url(slack_channel_id, slack_team_id) if slack_channel_id is not None else None
+ ),
+ slack_issue_count=slack_issue_count,
+ slack_user_count=slack_user_count,
+ last_slack_activity=last_slack_activity,
+ most_recent_support_ticket_url=most_recent_support_ticket_url,
+ )
+
+ LOGGER.info("fetched_conversations_slack_signals", org_count=len(org_ids), signals_found=len(result))
+ return result
diff --git a/ee/billing/salesforce_enrichment/redis_cache.py b/ee/billing/salesforce_enrichment/redis_cache.py
index 56b13a5508e3..25ebd507b3a0 100644
--- a/ee/billing/salesforce_enrichment/redis_cache.py
+++ b/ee/billing/salesforce_enrichment/redis_cache.py
@@ -135,20 +135,37 @@ async def _lrange_json_or_none(key: str, start: int, end: int) -> list[dict[str,
return None
-async def get_org_mappings_page_from_redis(
- offset: int = 0,
- limit: int = 10000,
-) -> list[dict[str, Any]] | None:
- """Retrieve a page of org mappings via LRANGE — no decompression needed.
+class OrgMappingsCacheMissingError(Exception):
+ """The org mappings cache key is absent or holds unreadable entries.
- Args:
- offset: Starting index for pagination
- limit: Number of mappings to retrieve
+ Callers should rebuild the cache. Transient Redis errors deliberately do not
+ map to this error — they propagate as-is so activity retry policies can
+ absorb them instead of triggering a needless rebuild.
+ """
- Returns:
- List of mapping dictionaries, empty list if past end, or None if key missing
+
+async def get_org_mappings_page(offset: int = 0, limit: int = 10000) -> list[dict[str, Any]]:
+ """Retrieve a page of org mappings via LRANGE — no decompression needed.
+
+ Returns an empty list when ``offset`` is at or past the end of the cached
+ list, meaning pagination is complete. Raises ``OrgMappingsCacheMissingError``
+ when the key is missing or an entry cannot be parsed, so callers never
+ mistake an expired cache for a completed run.
"""
- return await _lrange_json_or_none(SALESFORCE_ORG_MAPPINGS_CACHE_KEY, offset, offset + limit - 1)
+ redis_client = get_async_client()
+ raw_items = await redis_client.lrange(SALESFORCE_ORG_MAPPINGS_CACHE_KEY, offset, offset + limit - 1)
+ if raw_items:
+ try:
+ return [json.loads(item) for item in raw_items]
+ except (TypeError, ValueError) as e:
+ raise OrgMappingsCacheMissingError("org mappings cache entries are unreadable") from e
+
+ # LRANGE returns nothing both when the key is missing and when the offset is
+ # past the end of the list; LLEN tells those cases apart.
+ total = await redis_client.llen(SALESFORCE_ORG_MAPPINGS_CACHE_KEY)
+ if total and offset >= total:
+ return []
+ raise OrgMappingsCacheMissingError("org mappings cache key is missing")
async def get_org_mappings_from_redis() -> list[dict[str, Any]] | None:
diff --git a/ee/billing/test/test_conversations_signals.py b/ee/billing/test/test_conversations_signals.py
new file mode 100644
index 000000000000..4be0a6f3523b
--- /dev/null
+++ b/ee/billing/test/test_conversations_signals.py
@@ -0,0 +1,332 @@
+import uuid
+import datetime as dt
+from collections.abc import Callable
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models import Organization, User
+
+from products.conversations.backend.models import TeamConversationsSlackConfig, Ticket
+from products.conversations.backend.models.constants import Channel
+
+from ee.billing.salesforce_enrichment.conversations_signals import (
+ _get_slack_bot_token,
+ aggregate_conversations_slack_signals_for_orgs,
+ build_slack_channel_url,
+ build_support_ticket_url,
+ fetch_slack_channel_user_count,
+)
+
+
+class TestConversationsSlackSignals(SimpleTestCase):
+ def test_builds_channel_url(self):
+ assert build_slack_channel_url("C123", "T123") == "https://app.slack.com/client/T123/C123"
+ assert build_slack_channel_url("C123") == "https://app.slack.com/archives/C123"
+
+ def test_builds_support_ticket_url(self):
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ assert build_support_ticket_url(2, 1234) == "https://us.posthog.com/project/2/support/tickets/1234"
+
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
+ def test_aggregates_latest_channel_for_org(self, mock_fetch_rows, mock_fetch_latest_tickets):
+ org_id = "org-1"
+ mock_fetch_rows.return_value = [
+ {
+ "organization_id": org_id,
+ "slack_channel_id": "C_NEW",
+ "slack_team_id": "T123",
+ "representative_team_id": 1,
+ "slack_issue_count": 2,
+ "last_slack_activity": dt.datetime(2026, 6, 29, 9, 0, tzinfo=dt.UTC),
+ },
+ {
+ "organization_id": org_id,
+ "slack_channel_id": "C_OLD",
+ "slack_team_id": "T123",
+ "representative_team_id": 1,
+ "slack_issue_count": 1,
+ "last_slack_activity": dt.datetime(2026, 6, 1, 12, 0, tzinfo=dt.UTC),
+ },
+ ]
+ mock_fetch_latest_tickets.return_value = [
+ {
+ "organization_id": org_id,
+ "team_id": 2,
+ "ticket_number": 1234,
+ "activity_at": dt.datetime(2026, 6, 30, 8, 0, tzinfo=dt.UTC),
+ }
+ ]
+
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ result = aggregate_conversations_slack_signals_for_orgs([org_id], include_slack_user_count=False)
+
+ assert set(result.keys()) == {org_id}
+ signals = result[org_id]
+ assert signals.posthog_organization_id == org_id
+ assert signals.slack_channel_url == "https://app.slack.com/client/T123/C_NEW"
+ assert signals.slack_issue_count == 2
+ assert signals.slack_user_count is None
+ assert signals.last_slack_activity == dt.datetime(2026, 6, 29, 9, 0, tzinfo=dt.UTC)
+ assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/1234"
+
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
+ def test_returns_latest_support_ticket_without_slack_rows(self, mock_fetch_rows, mock_fetch_latest_tickets):
+ org_id = "org-1"
+ mock_fetch_rows.return_value = []
+ mock_fetch_latest_tickets.return_value = [
+ {
+ "organization_id": org_id,
+ "team_id": 2,
+ "ticket_number": 5678,
+ "activity_at": dt.datetime(2026, 6, 30, 8, 0, tzinfo=dt.UTC),
+ }
+ ]
+
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ result = aggregate_conversations_slack_signals_for_orgs([org_id], include_slack_user_count=False)
+
+ assert set(result.keys()) == {org_id}
+ signals = result[org_id]
+ assert signals.slack_channel_url is None
+ assert signals.slack_issue_count == 0
+ assert signals.slack_user_count is None
+ assert signals.last_slack_activity is None
+ assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/5678"
+
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
+ def test_returns_empty_when_no_rows(self, mock_fetch_rows, mock_fetch_latest_tickets):
+ mock_fetch_rows.return_value = []
+ mock_fetch_latest_tickets.return_value = []
+
+ result = aggregate_conversations_slack_signals_for_orgs(["org-1"], include_slack_user_count=False)
+
+ assert result == {}
+
+ @patch("ee.billing.salesforce_enrichment.conversations_signals.WebClient")
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._get_slack_bot_token")
+ def test_fetch_slack_channel_user_count_paginates(self, mock_get_token, mock_web_client):
+ mock_get_token.return_value = "xoxb-test"
+ mock_client = MagicMock()
+ mock_client.conversations_members.side_effect = [
+ {"members": ["U1", "U2"], "response_metadata": {"next_cursor": "next-page"}},
+ {"members": ["U3"], "response_metadata": {}},
+ ]
+ mock_web_client.return_value = mock_client
+
+ result = fetch_slack_channel_user_count(1, "C123")
+
+ assert result == 3
+ assert mock_client.conversations_members.call_args_list[0].kwargs["cursor"] is None
+ assert mock_client.conversations_members.call_args_list[1].kwargs["cursor"] == "next-page"
+
+
+class TestConversationsSlackSignalsDatabase(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.org_id = str(self.organization.id)
+
+ def _create_slack_ticket(
+ self,
+ *,
+ channel_id: str,
+ activity_at: dt.datetime,
+ org_id: str | None = None,
+ slack_team_id: str | None = "T123",
+ distinct_id: str | None = None,
+ identity_verified: bool | None = True,
+ ) -> Ticket:
+ return Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=f"session-{uuid.uuid4()}",
+ distinct_id=self.user.distinct_id if distinct_id is None else distinct_id,
+ channel_source=Channel.SLACK,
+ slack_channel_id=channel_id,
+ slack_team_id=slack_team_id,
+ organization_id=org_id or self.org_id,
+ last_message_at=activity_at,
+ identity_verified=identity_verified,
+ )
+
+ def _create_member_of_other_org(self, email: str) -> tuple[Organization, User]:
+ organization = Organization.objects.create(name=f"other-{uuid.uuid4()}")
+ user = User.objects.create_and_join(organization, email, None)
+ return organization, user
+
+ def test_aggregate_query_applies_recency_and_tie_break_ordering(self):
+ selected_activity = dt.datetime(2026, 6, 30, 11, 0, tzinfo=dt.UTC)
+ most_recent_ticket = self._create_slack_ticket(channel_id="C_NEW", activity_at=selected_activity)
+ for index in range(3):
+ self._create_slack_ticket(
+ channel_id="C_OLD_BUSY",
+ activity_at=dt.datetime(2026, 6, 29, 12, index, tzinfo=dt.UTC),
+ )
+
+ tie_org, tie_user = self._create_member_of_other_org(f"tie-{uuid.uuid4()}@posthog.com")
+ tie_org_id = str(tie_org.id)
+ tie_activity = dt.datetime(2026, 6, 30, 9, 0, tzinfo=dt.UTC)
+ for channel_id in ("C_TIE_B", "C_TIE_A"):
+ for _ in range(2):
+ self._create_slack_ticket(
+ org_id=tie_org_id,
+ channel_id=channel_id,
+ activity_at=tie_activity,
+ distinct_id=tie_user.distinct_id,
+ )
+ self._create_slack_ticket(
+ org_id=tie_org_id, channel_id="C_TIE_C", activity_at=tie_activity, distinct_id=tie_user.distinct_id
+ )
+
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ result = aggregate_conversations_slack_signals_for_orgs(
+ [self.org_id, tie_org_id],
+ include_slack_user_count=False,
+ )
+
+ signals = result[self.org_id]
+ assert signals.slack_channel_url == "https://app.slack.com/client/T123/C_NEW"
+ assert signals.slack_issue_count == 1
+ assert signals.last_slack_activity == selected_activity
+ assert (
+ signals.most_recent_support_ticket_url
+ == f"https://us.posthog.com/project/{self.team.id}/support/tickets/{most_recent_ticket.ticket_number}"
+ )
+
+ tie_signals = result[tie_org_id]
+ assert tie_signals.slack_channel_url == "https://app.slack.com/client/T123/C_TIE_A"
+ assert tie_signals.slack_issue_count == 2
+ assert tie_signals.last_slack_activity == tie_activity
+
+ @parameterized.expand(
+ [
+ ("member_distinct_id", lambda self: {"distinct_id": self.user.distinct_id}, True),
+ ("member_email_as_distinct_id", lambda self: {"distinct_id": self.user.email.upper()}, True),
+ ("unknown_identity", lambda self: {"distinct_id": f"stranger-{uuid.uuid4()}"}, False),
+ (
+ "identity_verification_failed",
+ lambda self: {"distinct_id": self.user.distinct_id, "identity_verified": False},
+ False,
+ ),
+ (
+ "identity_never_verified",
+ lambda self: {"distinct_id": self.user.distinct_id, "identity_verified": None},
+ False,
+ ),
+ ]
+ )
+ def test_only_tickets_with_verified_org_attribution_count(
+ self,
+ _name: str,
+ ticket_kwargs: Callable[["TestConversationsSlackSignalsDatabase"], dict[str, Any]],
+ expected_included: bool,
+ ) -> None:
+ self._create_slack_ticket(
+ channel_id="C123",
+ activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC),
+ **ticket_kwargs(self),
+ )
+
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ assert (self.org_id in result) == expected_included
+
+ def test_malformed_org_id_is_excluded_without_breaking_aggregation(self):
+ malformed_org_id = "not-a-uuid"
+ self._create_slack_ticket(
+ org_id=malformed_org_id,
+ channel_id="C123",
+ activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC),
+ )
+
+ result = aggregate_conversations_slack_signals_for_orgs(
+ [malformed_org_id, self.org_id], include_slack_user_count=False
+ )
+
+ assert result == {}
+
+ def test_spoofed_org_attribution_does_not_poison_another_orgs_signals(self):
+ legit_ticket = self._create_slack_ticket(
+ channel_id="C_LEGIT", activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC)
+ )
+ # The attacker is a genuine member of their own org, but stamps the victim's
+ # org id on a ticket (as spoofed analytics $groups attribution would).
+ _, attacker = self._create_member_of_other_org(f"attacker-{uuid.uuid4()}@posthog.com")
+ self._create_slack_ticket(
+ org_id=self.org_id,
+ channel_id="C_EVIL",
+ activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),
+ distinct_id=attacker.distinct_id,
+ )
+
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ signals = result[self.org_id]
+ assert signals.slack_channel_url == "https://app.slack.com/client/T123/C_LEGIT"
+ assert signals.slack_issue_count == 1
+ assert (
+ signals.most_recent_support_ticket_url
+ == f"https://us.posthog.com/project/{self.team.id}/support/tickets/{legit_ticket.ticket_number}"
+ )
+
+ def test_email_channel_ticket_verified_by_email_from(self):
+ ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=f"session-{uuid.uuid4()}",
+ distinct_id="",
+ channel_source=Channel.EMAIL,
+ email_from=self.user.email.upper(),
+ organization_id=self.org_id,
+ last_message_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC),
+ identity_verified=True,
+ )
+
+ with self.settings(SITE_URL="https://us.posthog.com"):
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ signals = result[self.org_id]
+ assert signals.slack_channel_url is None
+ assert signals.slack_issue_count == 0
+ assert (
+ signals.most_recent_support_ticket_url
+ == f"https://us.posthog.com/project/{self.team.id}/support/tickets/{ticket.ticket_number}"
+ )
+
+ def test_channels_with_same_id_in_different_workspaces_are_not_merged(self):
+ self._create_slack_ticket(
+ channel_id="C_SHARED",
+ activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC),
+ slack_team_id="T_ONE",
+ )
+ self._create_slack_ticket(
+ channel_id="C_SHARED",
+ activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),
+ slack_team_id="T_TWO",
+ )
+
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ signals = result[self.org_id]
+ assert signals.slack_channel_url == "https://app.slack.com/client/T_TWO/C_SHARED"
+ assert signals.slack_issue_count == 1
+
+ def test_get_slack_bot_token_resolves_by_workspace_then_team(self):
+ TeamConversationsSlackConfig.objects.update_or_create(
+ team=self.team, defaults={"slack_team_id": "TWORK", "slack_bot_token": "xoxb-test"}
+ )
+
+ # Matches by Slack workspace id, independent of the representative team.
+ assert _get_slack_bot_token("TWORK", None) == "xoxb-test"
+ # Falls back to the representative team when the workspace id is absent or unmatched.
+ assert _get_slack_bot_token(None, self.team.id) == "xoxb-test"
+ assert _get_slack_bot_token("TUNMATCHED", self.team.id) == "xoxb-test"
+ # No token when neither path resolves.
+ assert _get_slack_bot_token("TUNMATCHED", None) is None
diff --git a/ee/billing/test/test_redis_cache.py b/ee/billing/test/test_redis_cache.py
index 9e6d03830565..764234311cb5 100644
--- a/ee/billing/test/test_redis_cache.py
+++ b/ee/billing/test/test_redis_cache.py
@@ -5,10 +5,11 @@ import pytest
from unittest.mock import AsyncMock, patch
from ee.billing.salesforce_enrichment.redis_cache import (
+ OrgMappingsCacheMissingError,
_compress_redis_data,
get_cached_org_mappings_count,
get_org_mappings_from_redis,
- get_org_mappings_page_from_redis,
+ get_org_mappings_page,
get_stripe_enrichment_watermark,
set_stripe_enrichment_watermark,
store_org_mappings_in_redis,
@@ -91,7 +92,11 @@ class TestStoreOrgMappingsInRedis:
mock_pipe.execute.assert_called_once()
-class TestGetOrgMappingsPageFromRedis:
+class TestGetOrgMappingsPage:
+ """A missing key must never look like a completed run, and transient Redis
+ errors must propagate (so activity retries absorb them) instead of
+ triggering a needless cache rebuild."""
+
@pytest.mark.asyncio
async def test_get_page_success(self):
raw_items = [
@@ -105,40 +110,66 @@ class TestGetOrgMappingsPageFromRedis:
"ee.billing.salesforce_enrichment.redis_cache.get_async_client",
return_value=mock_redis,
):
- result = await get_org_mappings_page_from_redis(0, 10000)
+ result = await get_org_mappings_page(0, 10000)
assert result == [
{"salesforce_account_id": "001ABC", "posthog_org_id": "uuid-1"},
{"salesforce_account_id": "001DEF", "posthog_org_id": "uuid-2"},
]
+ # offset == total is the terminal page of any run whose mapping count is an
+ # exact multiple of the page size, so the equality boundary matters.
@pytest.mark.asyncio
- async def test_get_page_cache_miss(self):
+ @pytest.mark.parametrize("offset", [42, 50])
+ async def test_get_page_past_end_returns_empty(self, offset):
mock_redis = AsyncMock()
mock_redis.lrange.return_value = []
+ mock_redis.llen.return_value = 42
with patch(
"ee.billing.salesforce_enrichment.redis_cache.get_async_client",
return_value=mock_redis,
):
- result = await get_org_mappings_page_from_redis(0, 10000)
+ result = await get_org_mappings_page(offset, 10000)
- assert result is None
+ assert result == []
@pytest.mark.asyncio
- async def test_get_page_redis_error(self):
+ async def test_get_page_missing_key_raises(self):
mock_redis = AsyncMock()
- mock_redis.lrange.side_effect = Exception("Redis connection error")
+ mock_redis.lrange.return_value = []
+ mock_redis.llen.return_value = 0
with patch(
"ee.billing.salesforce_enrichment.redis_cache.get_async_client",
return_value=mock_redis,
):
- with patch("ee.billing.salesforce_enrichment.redis_cache.capture_exception") as mock_capture:
- result = await get_org_mappings_page_from_redis(0, 10000)
+ with pytest.raises(OrgMappingsCacheMissingError):
+ await get_org_mappings_page(0, 10000)
- assert result is None
- mock_capture.assert_called_once()
+ @pytest.mark.asyncio
+ async def test_get_page_corrupt_entry_raises_cache_missing(self):
+ mock_redis = AsyncMock()
+ mock_redis.lrange.return_value = [b"not-json"]
+
+ with patch(
+ "ee.billing.salesforce_enrichment.redis_cache.get_async_client",
+ return_value=mock_redis,
+ ):
+ with pytest.raises(OrgMappingsCacheMissingError):
+ await get_org_mappings_page(0, 10000)
+
+ @pytest.mark.asyncio
+ async def test_get_page_redis_error_propagates(self):
+ mock_redis = AsyncMock()
+ mock_redis.lrange.side_effect = ConnectionError("redis unreachable")
+
+ with patch(
+ "ee.billing.salesforce_enrichment.redis_cache.get_async_client",
+ return_value=mock_redis,
+ ):
+ with pytest.raises(ConnectionError, match="redis unreachable"):
+ await get_org_mappings_page(0, 10000)
class TestGetOrgMappingsFromRedis:
diff --git a/posthog/temporal/salesforce_enrichment/__init__.py b/posthog/temporal/salesforce_enrichment/__init__.py
index e0a6049a4aa0..3a3d5f285d82 100644
--- a/posthog/temporal/salesforce_enrichment/__init__.py
+++ b/posthog/temporal/salesforce_enrichment/__init__.py
@@ -1,3 +1,8 @@
+from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import (
+ SalesforceConversationsSlackEnrichmentWorkflow,
+ aggregate_conversations_slack_signals_activity,
+ enrich_conversations_slack_page_activity,
+)
from posthog.temporal.salesforce_enrichment.stripe_workflow import (
SalesforceStripeEnrichmentWorkflow,
commit_stripe_watermark_activity,
@@ -20,6 +25,7 @@ WORKFLOWS = [
SalesforceEnrichmentAsyncWorkflow,
SalesforceUsageEnrichmentWorkflow,
SalesforceStripeEnrichmentWorkflow,
+ SalesforceConversationsSlackEnrichmentWorkflow,
]
ACTIVITIES = [
@@ -31,4 +37,6 @@ ACTIVITIES = [
get_stripe_watermark_activity,
commit_stripe_watermark_activity,
enrich_stripe_page_activity,
+ aggregate_conversations_slack_signals_activity,
+ enrich_conversations_slack_page_activity,
]
diff --git a/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py b/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py
new file mode 100644
index 000000000000..e1abfd7ec5f0
--- /dev/null
+++ b/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py
@@ -0,0 +1,337 @@
+"""Salesforce Conversations Slack enrichment workflow."""
+
+import json
+import time
+import asyncio
+import datetime as dt
+import dataclasses
+from itertools import batched
+from typing import Any
+
+from django.db import close_old_connections
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError, ApplicationError
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.common.logger import get_logger
+from posthog.temporal.salesforce_enrichment.usage_workflow import cache_org_mappings_activity
+
+from ee.billing.salesforce_enrichment.constants import (
+ CONVERSATIONS_SLACK_ENRICHMENT_BATCH_SIZE,
+ CONVERSATIONS_SLACK_FIELD_MAPPINGS,
+ ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ POSTHOG_FETCH_MAPPINGS_PAGE_SIZE,
+)
+from ee.billing.salesforce_enrichment.conversations_signals import (
+ ConversationsSlackSignals,
+ aggregate_conversations_slack_signals_for_orgs,
+)
+from ee.billing.salesforce_enrichment.enrichment import bulk_update_salesforce_accounts
+from ee.billing.salesforce_enrichment.redis_cache import OrgMappingsCacheMissingError, get_org_mappings_page
+from ee.billing.salesforce_enrichment.salesforce_client import get_salesforce_client
+
+LOGGER = get_logger(__name__)
+
+
+class ConversationsSlackEnrichmentState:
+ """Continue-As-New state carried across workflow executions."""
+
+ page_offset: int = 0
+ total_processed: int = 0
+ total_updated: int = 0
+ error_count: int = 0
+ errors: list[str] = dataclasses.field(default_factory=list)
+
+
+class ConversationsSlackEnrichmentInputs:
+ """Inputs for the Conversations Slack enrichment workflow."""
+
+ batch_size: int = CONVERSATIONS_SLACK_ENRICHMENT_BATCH_SIZE
+ max_orgs: int | None = None
+ specific_org_id: str | None = None
+ state: ConversationsSlackEnrichmentState | None = None
+
+
+class ConversationsSlackEnrichmentResult:
+ """Result of the Conversations Slack enrichment workflow."""
+
+ total_orgs_processed: int
+ total_orgs_updated: int
+ error_count: int
+ errors: list[str]
+
+
+class EnrichConversationsSlackPageResult:
+ """Result of enriching one page of org mappings."""
+
+ page_size: int
+ processed: int
+ updated: int
+ errors: list[str]
+
+
+def prepare_conversations_slack_update_record(
+ salesforce_account_id: str, signals: ConversationsSlackSignals
+) -> dict[str, Any]:
+ """Prepare a Salesforce Account update record from Conversations Slack signals."""
+ record: dict[str, Any] = {"Id": salesforce_account_id}
+
+ for attr, sf_field in CONVERSATIONS_SLACK_FIELD_MAPPINGS.items():
+ value = getattr(signals, attr, None)
+ if value is None:
+ continue
+
+ if attr == "last_slack_activity" and isinstance(value, dt.datetime):
+ record[sf_field] = value.date().isoformat()
+ continue
+
+ record[sf_field] = value
+
+ return record
+
+
+def _serialize_signals(signals: ConversationsSlackSignals) -> dict[str, Any]:
+ serialized = dataclasses.asdict(signals)
+ if signals.last_slack_activity is not None:
+ serialized["last_slack_activity"] = signals.last_slack_activity.isoformat()
+ return serialized
+
+
+async def aggregate_conversations_slack_signals_activity(
+ org_ids: list[str],
+) -> dict[str, dict[str, Any]]:
+ """Aggregate Conversations Slack signals for given org IDs."""
+ async with Heartbeater():
+ close_old_connections()
+ logger = LOGGER.bind()
+ logger.info("aggregating_conversations_slack_signals", org_count=len(org_ids))
+
+ signals = await asyncio.to_thread(aggregate_conversations_slack_signals_for_orgs, org_ids)
+ logger.info("conversations_slack_signals_aggregated", org_count=len(org_ids), signals_count=len(signals))
+ return {org_id: _serialize_signals(org_signals) for org_id, org_signals in signals.items()}
+
+
+async def enrich_conversations_slack_page_activity(
+ offset: int,
+ limit: int,
+ batch_size: int,
+) -> EnrichConversationsSlackPageResult:
+ """Read a page of org mappings, aggregate Conversations Slack signals, and update Salesforce."""
+ async with Heartbeater() as heartbeater:
+ close_old_connections()
+ logger = LOGGER.bind()
+
+ redis_start = time.monotonic()
+ try:
+ cached_mappings = await get_org_mappings_page(offset, limit)
+ except OrgMappingsCacheMissingError as e:
+ logger.warning(
+ "org_mappings_cache_miss",
+ reason=str(e),
+ offset=offset,
+ redis_duration_ms=round((time.monotonic() - redis_start) * 1000, 1),
+ )
+ raise ApplicationError(
+ "Org mappings cache is missing or unreadable",
+ type=ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ non_retryable=True,
+ ) from e
+ redis_duration_ms = (time.monotonic() - redis_start) * 1000
+
+ if not cached_mappings:
+ # An empty page past the end of the list means pagination is complete.
+ return EnrichConversationsSlackPageResult(page_size=0, processed=0, updated=0, errors=[])
+
+ org_to_sf = {m["posthog_org_id"]: m["salesforce_account_id"] for m in cached_mappings}
+ all_org_ids = list(org_to_sf.keys())
+ total_orgs = len(all_org_ids)
+
+ logger.info(
+ "conversations_slack_enrich_page_started",
+ offset=offset,
+ page_size=total_orgs,
+ redis_duration_ms=round(redis_duration_ms, 1),
+ )
+
+ sf = await asyncio.to_thread(get_salesforce_client)
+ total_processed = 0
+ total_updated = 0
+ errors: list[str] = []
+
+ for batch_tuple in batched(all_org_ids, batch_size, strict=False):
+ batch_org_ids = list(batch_tuple)
+ signals = await asyncio.to_thread(aggregate_conversations_slack_signals_for_orgs, batch_org_ids)
+ update_records = [
+ prepare_conversations_slack_update_record(org_to_sf[org_id], org_signals)
+ for org_id, org_signals in signals.items()
+ if org_id in org_to_sf
+ ]
+
+ if update_records:
+ success, failed = await asyncio.to_thread(
+ bulk_update_salesforce_accounts,
+ sf,
+ update_records,
+ raise_on_batch_error=True,
+ )
+ total_updated += success
+ if failed:
+ errors.append(f"sfdc_bulk_update_failed_count={failed}")
+
+ total_processed += len(batch_org_ids)
+ heartbeater.details = (total_processed, total_orgs, total_updated)
+
+ logger.info(
+ "conversations_slack_enrich_page_completed",
+ offset=offset,
+ page_size=total_orgs,
+ processed=total_processed,
+ updated=total_updated,
+ error_count=len(errors),
+ )
+
+ return EnrichConversationsSlackPageResult(
+ page_size=len(cached_mappings),
+ processed=total_processed,
+ updated=total_updated,
+ errors=errors,
+ )
+
+
[email protected](name="salesforce-conversations-slack-enrichment")
+class SalesforceConversationsSlackEnrichmentWorkflow(PostHogWorkflow):
+ """Enrich Salesforce accounts with Conversations Slack support signals."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ConversationsSlackEnrichmentInputs:
+ loaded = json.loads(inputs[0])
+ state_data = loaded.pop("state", None)
+ state = ConversationsSlackEnrichmentState(**state_data) if state_data else None
+ return ConversationsSlackEnrichmentInputs(**loaded, state=state)
+
+ @workflow.run
+ async def run(self, inputs: ConversationsSlackEnrichmentInputs) -> dict[str, Any]:
+ logger = LOGGER.bind()
+ logger.info(
+ "salesforce_conversations_slack_enrichment_started",
+ batch_size=inputs.batch_size,
+ max_orgs=inputs.max_orgs,
+ specific_org_id=inputs.specific_org_id,
+ )
+
+ if inputs.specific_org_id:
+ return await self._run_debug_mode(inputs.specific_org_id)
+
+ return await self._run_production_mode(inputs)
+
+ async def _run_debug_mode(self, org_id: str) -> dict[str, Any]:
+ logger = LOGGER.bind()
+ logger.info("conversations_slack_debug_mode_started", org_id=org_id)
+
+ signals = await workflow.execute_activity(
+ aggregate_conversations_slack_signals_activity,
+ [org_id],
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ if org_id not in signals:
+ return {"mode": "debug", "org_id": org_id, "error": "No Conversations Slack signals found"}
+
+ return {"mode": "debug", "org_id": org_id, "signals": signals[org_id]}
+
+ async def _run_production_mode(self, inputs: ConversationsSlackEnrichmentInputs) -> dict[str, Any]:
+ logger = LOGGER.bind()
+ state = inputs.state or ConversationsSlackEnrichmentState()
+ page_size = POSTHOG_FETCH_MAPPINGS_PAGE_SIZE
+
+ if inputs.max_orgs is not None:
+ remaining = inputs.max_orgs - state.total_processed
+ if remaining <= 0:
+ return self._build_result(state)
+ page_size = min(page_size, remaining)
+
+ if state.page_offset == 0:
+ cache_result = await self._warm_org_mappings_cache()
+ if not cache_result.get("total_mappings"):
+ logger.info("no_salesforce_accounts_found")
+ return self._build_result(state)
+
+ try:
+ page_result = await self._run_enrich_page(state.page_offset, page_size, inputs.batch_size)
+ except ActivityError as e:
+ if not (isinstance(e.cause, ApplicationError) and e.cause.type == ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE):
+ raise
+ # The org mappings cache can expire or turn unreadable mid-run; force a
+ # rebuild once and retry the page instead of silently truncating the sync.
+ # A second miss propagates.
+ logger.warning("org_mappings_cache_missing_rebuilding", page_offset=state.page_offset)
+ cache_result = await self._warm_org_mappings_cache(force_rebuild=True)
+ if not cache_result.get("total_mappings"):
+ logger.info("no_salesforce_accounts_found")
+ return self._build_result(state)
+ page_result = await self._run_enrich_page(state.page_offset, page_size, inputs.batch_size)
+
+ state.total_processed += page_result.processed
+ state.total_updated += page_result.updated
+ state.error_count += len(page_result.errors)
+ if len(state.errors) < 10:
+ state.errors.extend(page_result.errors[: 10 - len(state.errors)])
+
+ if page_result.page_size < POSTHOG_FETCH_MAPPINGS_PAGE_SIZE:
+ return self._build_result(state)
+
+ state.page_offset += page_result.page_size
+ logger.info(
+ "conversations_slack_enrichment_continuing_as_new",
+ page_offset=state.page_offset,
+ total_processed=state.total_processed,
+ total_updated=state.total_updated,
+ )
+ workflow.continue_as_new(
+ ConversationsSlackEnrichmentInputs(
+ batch_size=inputs.batch_size,
+ max_orgs=inputs.max_orgs,
+ state=state,
+ )
+ )
+ return self._build_result(state) # type: ignore[unreachable]
+
+ @staticmethod
+ async def _warm_org_mappings_cache(force_rebuild: bool = False) -> dict[str, Any]:
+ return await workflow.execute_activity(
+ cache_org_mappings_activity,
+ args=[force_rebuild],
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ @staticmethod
+ async def _run_enrich_page(offset: int, page_size: int, batch_size: int) -> EnrichConversationsSlackPageResult:
+ return await workflow.execute_activity(
+ enrich_conversations_slack_page_activity,
+ args=[offset, page_size, batch_size],
+ start_to_close_timeout=dt.timedelta(minutes=30),
+ retry_policy=RetryPolicy(initial_interval=dt.timedelta(seconds=10), maximum_attempts=3),
+ heartbeat_timeout=dt.timedelta(minutes=5),
+ )
+
+ @staticmethod
+ def _build_result(state: ConversationsSlackEnrichmentState) -> dict[str, Any]:
+ return dataclasses.asdict(
+ ConversationsSlackEnrichmentResult(
+ total_orgs_processed=state.total_processed,
+ total_orgs_updated=state.total_updated,
+ error_count=state.error_count,
+ errors=state.errors[:10],
+ )
+ )
diff --git a/posthog/temporal/salesforce_enrichment/usage_workflow.py b/posthog/temporal/salesforce_enrichment/usage_workflow.py
index fa418b23b455..10b6fdb02d9a 100644
--- a/posthog/temporal/salesforce_enrichment/usage_workflow.py
+++ b/posthog/temporal/salesforce_enrichment/usage_workflow.py
@@ -12,12 +12,14 @@ from django.db import close_old_connections
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError, ApplicationError
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from ee.billing.salesforce_enrichment.constants import (
+ ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
POSTHOG_FETCH_MAPPINGS_PAGE_SIZE,
POSTHOG_ORG_ID_FIELD,
POSTHOG_USAGE_ENRICHMENT_BATCH_SIZE,
@@ -25,8 +27,9 @@ from ee.billing.salesforce_enrichment.constants import (
SALESFORCE_UPDATE_BATCH_SIZE,
)
from ee.billing.salesforce_enrichment.redis_cache import (
+ OrgMappingsCacheMissingError,
get_cached_org_mappings_count,
- get_org_mappings_page_from_redis,
+ get_org_mappings_page,
store_org_mappings_in_redis,
)
from ee.billing.salesforce_enrichment.salesforce_client import get_salesforce_client
@@ -89,21 +92,30 @@ def prepare_salesforce_update_record(salesforce_account_id: str, signals: UsageS
@activity.defn
-async def cache_org_mappings_activity() -> dict[str, Any]:
- """Cache all Salesforce org mappings in Redis (reuses existing cache if available)."""
+async def cache_org_mappings_activity(force_rebuild: bool = False) -> dict[str, Any]:
+ """Cache all Salesforce org mappings in Redis (reuses existing cache if available).
+
+ ``force_rebuild`` skips cache reuse and replaces the list unconditionally.
+ Recovery from unreadable cache entries needs this: the key still exists, so
+ the count check alone would reuse the same bad data.
+ """
close_old_connections()
logger = LOGGER.bind()
- cached_count = await get_cached_org_mappings_count()
- if cached_count is not None:
- logger.info("cache_hit_skipping_salesforce_query", cached_total=cached_count)
- return {"success": True, "total_mappings": cached_count, "cache_reused": True}
-
- logger.info("cache_miss_querying_salesforce", action="org_mappings")
+ if force_rebuild:
+ logger.info("cache_force_rebuild_querying_salesforce", action="org_mappings")
+ else:
+ cached_count = await get_cached_org_mappings_count()
+ if cached_count is not None:
+ logger.info("cache_hit_skipping_salesforce_query", cached_total=cached_count)
+ return {"success": True, "total_mappings": cached_count, "cache_reused": True}
+ logger.info("cache_miss_querying_salesforce", action="org_mappings")
sf = get_salesforce_client()
- # POSTHOG_ORG_ID_FIELD is a trusted constant defined in constants.py, not user input
- query = f"SELECT Id, {POSTHOG_ORG_ID_FIELD} FROM Account WHERE {POSTHOG_ORG_ID_FIELD} != null"
+ # POSTHOG_ORG_ID_FIELD is a trusted constant defined in constants.py, not user input.
+ # ORDER BY keeps list order deterministic across rebuilds, so a workflow resuming
+ # at a saved page offset after a mid-run cache rebuild doesn't skip or repeat orgs.
+ query = f"SELECT Id, {POSTHOG_ORG_ID_FIELD} FROM Account WHERE {POSTHOG_ORG_ID_FIELD} != null ORDER BY Id"
result = await asyncio.to_thread(sf.query_all, query)
mappings = [
@@ -141,18 +153,24 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
# Read mappings directly from Redis
redis_start = time.monotonic()
- cached_mappings = await get_org_mappings_page_from_redis(offset, limit)
- redis_duration_ms = (time.monotonic() - redis_start) * 1000
-
- if cached_mappings is None:
+ try:
+ cached_mappings = await get_org_mappings_page(offset, limit)
+ except OrgMappingsCacheMissingError as e:
logger.warning(
"org_mappings_cache_miss",
- reason="cache_expired_or_missing",
- redis_duration_ms=round(redis_duration_ms, 1),
+ reason=str(e),
+ offset=offset,
+ redis_duration_ms=round((time.monotonic() - redis_start) * 1000, 1),
)
- return EnrichPageResult(page_size=0, processed=0, updated=0, errors=[])
+ raise ApplicationError(
+ "Org mappings cache is missing or unreadable",
+ type=ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ non_retryable=True,
+ ) from e
+ redis_duration_ms = (time.monotonic() - redis_start) * 1000
if not cached_mappings:
+ # An empty page past the end of the list means pagination is complete.
return EnrichPageResult(page_size=0, processed=0, updated=0, errors=[])
org_to_sf = {m["posthog_org_id"]: m["salesforce_account_id"] for m in cached_mappings}
@@ -289,7 +307,7 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
page_size = POSTHOG_FETCH_MAPPINGS_PAGE_SIZE
# Apply max_orgs limit
- if inputs.max_orgs:
+ if inputs.max_orgs is not None:
remaining = inputs.max_orgs - state.total_processed
if remaining <= 0:
return self._build_result(state)
@@ -297,20 +315,26 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
# Cache org mappings in Redis on the first execution only
if state.page_offset == 0:
- await workflow.execute_activity(
- cache_org_mappings_activity,
- start_to_close_timeout=dt.timedelta(minutes=10),
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
+ cache_result = await self._warm_org_mappings_cache()
+ if not cache_result.get("total_mappings"):
+ logger.info("no_salesforce_accounts_found")
+ return self._build_result(state)
# Enrich one page: reads from Redis, aggregates signals, updates Salesforce
- page_result = await workflow.execute_activity(
- enrich_org_page_activity,
- args=[state.page_offset, page_size, inputs.batch_size],
- start_to_close_timeout=dt.timedelta(minutes=30),
- retry_policy=RetryPolicy(initial_interval=dt.timedelta(seconds=10), maximum_attempts=3),
- heartbeat_timeout=dt.timedelta(minutes=5),
- )
+ try:
+ page_result = await self._run_enrich_page(state.page_offset, page_size, inputs.batch_size)
+ except ActivityError as e:
+ if not (isinstance(e.cause, ApplicationError) and e.cause.type == ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE):
+ raise
+ # The org mappings cache can expire or turn unreadable mid-run; force a
+ # rebuild once and retry the page instead of failing the enrichment.
+ # A second miss propagates.
+ logger.warning("org_mappings_cache_missing_rebuilding", page_offset=state.page_offset)
+ cache_result = await self._warm_org_mappings_cache(force_rebuild=True)
+ if not cache_result.get("total_mappings"):
+ logger.info("no_salesforce_accounts_found")
+ return self._build_result(state)
+ page_result = await self._run_enrich_page(state.page_offset, page_size, inputs.batch_size)
state.total_processed += page_result.processed
state.total_updated += page_result.updated
@@ -319,10 +343,7 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
if len(state.errors) < 10:
state.errors.extend(page_result.errors[: 10 - len(state.errors)])
- # No data or last page — return final result
- if page_result.page_size == 0 or page_result.page_size < page_size:
- if state.page_offset == 0 and page_result.page_size == 0:
- logger.info("no_salesforce_accounts_found")
+ if page_result.page_size < POSTHOG_FETCH_MAPPINGS_PAGE_SIZE:
return self._build_result(state)
# More pages to process — continue as new execution
@@ -341,6 +362,25 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
)
)
+ @staticmethod
+ async def _warm_org_mappings_cache(force_rebuild: bool = False) -> dict[str, Any]:
+ return await workflow.execute_activity(
+ cache_org_mappings_activity,
+ args=[force_rebuild],
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ @staticmethod
+ async def _run_enrich_page(offset: int, page_size: int, batch_size: int) -> EnrichPageResult:
+ return await workflow.execute_activity(
+ enrich_org_page_activity,
+ args=[offset, page_size, batch_size],
+ start_to_close_timeout=dt.timedelta(minutes=30),
+ retry_policy=RetryPolicy(initial_interval=dt.timedelta(seconds=10), maximum_attempts=3),
+ heartbeat_timeout=dt.timedelta(minutes=5),
+ )
+
@staticmethod
def _build_result(state: UsageEnrichmentState) -> dict[str, Any]:
return dataclasses.asdict(
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 79f9f64b7e8f..c639649f1d7d 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -55,6 +55,7 @@ from posthog.temporal.mcp_analytics.intent_clustering.schedule import create_int
from posthog.temporal.messaging.schedule import create_all_realtime_cohort_calculation_schedules
from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputs
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputs
+from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import ConversationsSlackEnrichmentInputs
from posthog.temporal.salesforce_enrichment.stripe_workflow import StripeEnrichmentInputs
from posthog.temporal.salesforce_enrichment.usage_workflow import UsageEnrichmentInputs
from posthog.temporal.salesforce_enrichment.workflow import SalesforceEnrichmentInputs
@@ -283,6 +284,46 @@ async def create_salesforce_stripe_enrichment_schedule(client: Client):
)
+async def create_salesforce_conversations_slack_enrichment_schedule(client: Client):
+ """Create or update the schedule for the Salesforce Conversations Slack enrichment workflow.
+
+ Runs daily at 5 AM UTC to push Conversations Slack support signals to
+ Salesforce Accounts. ``SKIP`` prevents overlapping runs if Slack API calls
+ or Salesforce updates take longer than expected.
+ """
+ salesforce_conversations_slack_enrichment_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "salesforce-conversations-slack-enrichment",
+ asdict(ConversationsSlackEnrichmentInputs()),
+ id="salesforce-conversations-slack-enrichment-schedule",
+ task_queue=settings.BILLING_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Daily at 5 AM UTC",
+ hour=[ScheduleRange(start=5, end=5)],
+ )
+ ]
+ ),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, "salesforce-conversations-slack-enrichment-schedule"):
+ await a_update_schedule(
+ client,
+ "salesforce-conversations-slack-enrichment-schedule",
+ salesforce_conversations_slack_enrichment_schedule,
+ )
+ else:
+ await a_create_schedule(
+ client,
+ "salesforce-conversations-slack-enrichment-schedule",
+ salesforce_conversations_slack_enrichment_schedule,
+ trigger_immediately=False,
+ )
+
+
async def create_enforce_max_replay_retention_schedule(client: Client):
"""Create or update the schedule for the enforce max replay retention workflow.
@@ -796,6 +837,11 @@ if settings.CLOUD_DEPLOYMENT:
if settings.EE_AVAILABLE:
schedules.append(create_schedule_all_subscriptions_schedule)
+ # Conversations tickets are region-local, so unlike the other (US-only) Salesforce
+ # writers this one runs per region — each region's tickets enrich that region's
+ # orgs, which map to disjoint Salesforce Accounts.
+ if settings.CLOUD_DEPLOYMENT in ("US", "EU"):
+ schedules.append(create_salesforce_conversations_slack_enrichment_schedule)
if settings.CLOUD_DEPLOYMENT == "US":
schedules.append(create_salesforce_enrichment_schedule)
schedules.append(create_salesforce_usage_enrichment_schedule)
diff --git a/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py b/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
new file mode 100644
index 000000000000..394b7db315b7
--- /dev/null
+++ b/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
@@ -0,0 +1,390 @@
+import json
+import datetime as dt
+from typing import Any
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from temporalio.exceptions import ActivityError, ApplicationError
+
+from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import (
+ ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ ConversationsSlackEnrichmentInputs,
+ ConversationsSlackEnrichmentState,
+ EnrichConversationsSlackPageResult,
+ SalesforceConversationsSlackEnrichmentWorkflow,
+ enrich_conversations_slack_page_activity,
+ prepare_conversations_slack_update_record,
+)
+
+from ee.billing.salesforce_enrichment.conversations_signals import ConversationsSlackSignals
+from ee.billing.salesforce_enrichment.redis_cache import OrgMappingsCacheMissingError
+
+WORKFLOW_MODULE = "posthog.temporal.salesforce_enrichment.conversations_slack_workflow"
+
+
+async def mock_to_thread(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+
+def _cache_missing_activity_error() -> ActivityError:
+ error = ActivityError(
+ "enrich page failed",
+ scheduled_event_id=1,
+ started_event_id=1,
+ identity="",
+ activity_type="enrich_conversations_slack_page_activity",
+ activity_id="1",
+ retry_state=None,
+ )
+ error.__cause__ = ApplicationError(
+ "Org mappings cache is missing or unreadable",
+ type=ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ non_retryable=True,
+ )
+ return error
+
+
+def _cache_activity_result(total_mappings: int) -> dict[str, Any]:
+ return {"success": True, "total_mappings": total_mappings}
+
+
+def _signals(
+ org_id: str = "org-1",
+ last_slack_activity: dt.datetime | None = None,
+) -> ConversationsSlackSignals:
+ return ConversationsSlackSignals(
+ posthog_organization_id=org_id,
+ slack_channel_url="https://app.slack.com/client/T123/C123",
+ slack_issue_count=3,
+ slack_user_count=12,
+ last_slack_activity=last_slack_activity or dt.datetime(2026, 6, 29, 15, 30, tzinfo=dt.UTC),
+ most_recent_support_ticket_url=f"https://us.posthog.com/project/2/support/tickets/{1000 if org_id == 'org-1' else 1001}",
+ )
+
+
+class TestPrepareConversationsSlackUpdateRecord(SimpleTestCase):
+ def test_formats_last_slack_activity_as_salesforce_date(self):
+ record = prepare_conversations_slack_update_record("001ABC", _signals())
+
+ assert record == {
+ "Id": "001ABC",
+ "Slack_Channel__c": "https://app.slack.com/client/T123/C123",
+ "slack_issue_count__c": 3,
+ "slack_user_count__c": 12,
+ "last_slack_activity__c": "2026-06-29",
+ "Most_Recent_Support_Ticket__c": "https://us.posthog.com/project/2/support/tickets/1000",
+ }
+
+ def test_omits_none_fields(self):
+ signals = ConversationsSlackSignals(
+ posthog_organization_id="org-1",
+ slack_channel_url=None,
+ slack_issue_count=0,
+ slack_user_count=None,
+ last_slack_activity=None,
+ most_recent_support_ticket_url=None,
+ )
+
+ record = prepare_conversations_slack_update_record("001ABC", signals)
+
+ assert record == {"Id": "001ABC", "slack_issue_count__c": 0}
+
+
+class TestWorkflowParseInputs(SimpleTestCase):
+ def test_defaults(self):
+ inputs = SalesforceConversationsSlackEnrichmentWorkflow.parse_inputs(["{}"])
+
+ assert inputs.batch_size == 100
+ assert inputs.max_orgs is None
+ assert inputs.specific_org_id is None
+ assert inputs.state is None
+
+ def test_state_roundtrip(self):
+ payload = json.dumps(
+ {
+ "max_orgs": 500,
+ "state": {
+ "page_offset": 100,
+ "total_processed": 100,
+ "total_updated": 90,
+ "error_count": 1,
+ "errors": ["one failed"],
+ },
+ }
+ )
+
+ inputs = SalesforceConversationsSlackEnrichmentWorkflow.parse_inputs([payload])
+
+ assert inputs.max_orgs == 500
+ assert inputs.state is not None
+ assert inputs.state.page_offset == 100
+ assert inputs.state.total_updated == 90
+
+ def test_invalid_json_raises(self):
+ with pytest.raises(json.JSONDecodeError):
+ SalesforceConversationsSlackEnrichmentWorkflow.parse_inputs(["invalid"])
+
+
+class TestEnrichConversationsSlackPageActivity(SimpleTestCase):
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.bulk_update_salesforce_accounts", return_value=(2, 0))
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.aggregate_conversations_slack_signals_for_orgs")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_enriches_page_successfully(
+ self,
+ _mock_close,
+ mock_get_page,
+ mock_aggregate,
+ mock_sf_client,
+ mock_bulk,
+ _mock_heartbeat,
+ ):
+ mock_get_page.return_value = [
+ {"salesforce_account_id": "001ABC", "posthog_org_id": "org-1"},
+ {"salesforce_account_id": "001DEF", "posthog_org_id": "org-2"},
+ ]
+ mock_aggregate.return_value = {
+ "org-1": _signals("org-1"),
+ "org-2": _signals("org-2", dt.datetime(2026, 6, 28, 10, 0, tzinfo=dt.UTC)),
+ }
+ mock_sf = MagicMock()
+ mock_sf_client.return_value = mock_sf
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await enrich_conversations_slack_page_activity(0, 10000, 100)
+
+ assert result.page_size == 2
+ assert result.processed == 2
+ assert result.updated == 2
+ assert result.errors == []
+ mock_get_page.assert_called_once_with(0, 10000)
+ mock_bulk.assert_called_once()
+
+ sent_records = mock_bulk.call_args[0][1]
+ assert sent_records[0]["Id"] == "001ABC"
+ assert sent_records[0]["last_slack_activity__c"] == "2026-06-29"
+ assert sent_records[1]["Id"] == "001DEF"
+ assert sent_records[1]["last_slack_activity__c"] == "2026-06-28"
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.bulk_update_salesforce_accounts", side_effect=Exception("sfdc down"))
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.aggregate_conversations_slack_signals_for_orgs")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_sfdc_transport_exception_propagates_for_retry(
+ self,
+ _mock_close,
+ mock_get_page,
+ mock_aggregate,
+ mock_sf_client,
+ mock_bulk,
+ _mock_heartbeat,
+ ):
+ mock_get_page.return_value = [{"salesforce_account_id": "001ABC", "posthog_org_id": "org-1"}]
+ mock_aggregate.return_value = {"org-1": _signals("org-1")}
+ mock_sf_client.return_value = MagicMock()
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ with pytest.raises(Exception, match="sfdc down"):
+ await enrich_conversations_slack_page_activity(0, 10000, 100)
+
+ _, kwargs = mock_bulk.call_args
+ assert kwargs.get("raise_on_batch_error") is True
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.bulk_update_salesforce_accounts", return_value=(1, 1))
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.aggregate_conversations_slack_signals_for_orgs")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_partial_bulk_update_failure_records_error(
+ self,
+ _mock_close,
+ mock_get_page,
+ mock_aggregate,
+ mock_sf_client,
+ mock_bulk,
+ _mock_heartbeat,
+ ):
+ mock_get_page.return_value = [
+ {"salesforce_account_id": "001ABC", "posthog_org_id": "org-1"},
+ {"salesforce_account_id": "001DEF", "posthog_org_id": "org-2"},
+ ]
+ mock_aggregate.return_value = {
+ "org-1": _signals("org-1"),
+ "org-2": _signals("org-2"),
+ }
+ mock_sf_client.return_value = MagicMock()
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await enrich_conversations_slack_page_activity(0, 10000, 100)
+
+ assert result.updated == 1
+ assert result.errors == ["sfdc_bulk_update_failed_count=1"]
+ _, kwargs = mock_bulk.call_args
+ assert kwargs.get("raise_on_batch_error") is True
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_raises_when_cache_is_missing(self, _mock_close, mock_get_page, _mock_heartbeat):
+ mock_get_page.side_effect = OrgMappingsCacheMissingError("org mappings cache key is missing")
+
+ with pytest.raises(ApplicationError) as exc_info:
+ await enrich_conversations_slack_page_activity(0, 10000, 100)
+
+ assert exc_info.value.type == ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_returns_empty_page_past_end_of_list(self, _mock_close, mock_get_page, _mock_heartbeat):
+ mock_get_page.return_value = []
+
+ result = await enrich_conversations_slack_page_activity(50, 10000, 100)
+
+ assert result == EnrichConversationsSlackPageResult(page_size=0, processed=0, updated=0, errors=[])
+
+
+class TestProductionModeContinueAsNew(SimpleTestCase):
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_continues_as_new_when_page_is_full(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_activity_result(20000),
+ EnrichConversationsSlackPageResult(page_size=10000, processed=10000, updated=500, errors=[]),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100))
+
+ mock_workflow.continue_as_new.assert_called_once()
+ next_inputs = mock_workflow.continue_as_new.call_args[0][0]
+ assert next_inputs.state.page_offset == 10000
+ assert next_inputs.state.total_processed == 10000
+ assert next_inputs.state.total_updated == 500
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_returns_result_on_last_page(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ return_value=EnrichConversationsSlackPageResult(page_size=5000, processed=5000, updated=250, errors=[]),
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ state = ConversationsSlackEnrichmentState(page_offset=10000, total_processed=10000, total_updated=500)
+ result = await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100, state=state))
+
+ mock_workflow.continue_as_new.assert_not_called()
+ assert result["total_orgs_processed"] == 15000
+ assert result["total_orgs_updated"] == 750
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_max_orgs_capped_page_finishes_without_continuing(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_activity_result(20000),
+ EnrichConversationsSlackPageResult(page_size=500, processed=500, updated=100, errors=[]),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ result = await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100, max_orgs=500))
+
+ enrich_call = mock_workflow.execute_activity.call_args_list[1]
+ assert enrich_call.kwargs["args"] == [0, 500, 100]
+ mock_workflow.continue_as_new.assert_not_called()
+ assert result["total_orgs_processed"] == 500
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_skips_paging_when_no_org_mappings(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(return_value=_cache_activity_result(0))
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ result = await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100))
+
+ assert mock_workflow.execute_activity.call_count == 1
+ assert result["total_orgs_processed"] == 0
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_recaches_and_retries_page_when_cache_expires_mid_run(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ _cache_activity_result(15000),
+ EnrichConversationsSlackPageResult(page_size=5000, processed=5000, updated=250, errors=[]),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ state = ConversationsSlackEnrichmentState(page_offset=10000, total_processed=10000, total_updated=500)
+ result = await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100, state=state))
+
+ assert mock_workflow.execute_activity.call_count == 3
+ # The rewarm must force a rebuild — reusing an existing (possibly unreadable)
+ # list would make the retry read the same bad data.
+ rewarm_call = mock_workflow.execute_activity.call_args_list[1]
+ assert rewarm_call.kwargs["args"] == [True]
+ # The retried page must target the same offset and page size as the failed one.
+ retried_call = mock_workflow.execute_activity.call_args_list[2]
+ assert retried_call.kwargs["args"] == [10000, 10000, 100]
+ assert result["total_orgs_processed"] == 15000
+ assert result["total_orgs_updated"] == 750
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_returns_gracefully_when_recache_finds_no_mappings(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ _cache_activity_result(0),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ state = ConversationsSlackEnrichmentState(page_offset=10000, total_processed=10000, total_updated=500)
+ result = await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100, state=state))
+
+ assert mock_workflow.execute_activity.call_count == 2
+ assert result["total_orgs_processed"] == 10000
+ assert result["total_orgs_updated"] == 500
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_second_cache_miss_after_recache_propagates(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ _cache_activity_result(15000),
+ _cache_missing_activity_error(),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ workflow = SalesforceConversationsSlackEnrichmentWorkflow()
+ state = ConversationsSlackEnrichmentState(page_offset=10000)
+
+ with pytest.raises(ActivityError):
+ await workflow._run_production_mode(ConversationsSlackEnrichmentInputs(batch_size=100, state=state))
diff --git a/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py b/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
index ff707fb2a21d..08fb591ef47f 100644
--- a/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
+++ b/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
@@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.test import TestCase
+from temporalio.exceptions import ActivityError, ApplicationError
+
from posthog.temporal.salesforce_enrichment.usage_workflow import (
EnrichPageResult,
SalesforceUsageEnrichmentWorkflow,
@@ -15,6 +17,8 @@ from posthog.temporal.salesforce_enrichment.usage_workflow import (
prepare_salesforce_update_record,
)
+from ee.billing.salesforce_enrichment.constants import ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE
+from ee.billing.salesforce_enrichment.redis_cache import OrgMappingsCacheMissingError
from ee.billing.salesforce_enrichment.usage_signals import UsageSignals
@@ -137,6 +141,24 @@ class TestWorkflowParseInputs(TestCase):
WORKFLOW_MODULE = "posthog.temporal.salesforce_enrichment.usage_workflow"
+def _cache_missing_activity_error() -> ActivityError:
+ error = ActivityError(
+ "enrich page failed",
+ scheduled_event_id=1,
+ started_event_id=1,
+ identity="",
+ activity_type="enrich_org_page_activity",
+ activity_id="1",
+ retry_state=None,
+ )
+ error.__cause__ = ApplicationError(
+ "Org mappings cache is missing or unreadable",
+ type=ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
+ non_retryable=True,
+ )
+ return error
+
+
class TestCacheOrgMappingsActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
@@ -177,12 +199,32 @@ class TestCacheOrgMappingsActivity(TestCase):
assert stored_mappings[0]["posthog_org_id"] == "org-uuid-1"
assert stored_mappings[1]["posthog_org_id"] == "org-uuid-2"
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.store_org_mappings_in_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.get_cached_org_mappings_count", new_callable=AsyncMock, return_value=100)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_force_rebuild_replaces_existing_cache(
+ self, _mock_close, _mock_cache_count, mock_sf_client, mock_store
+ ):
+ mock_sf = MagicMock()
+ mock_sf.query_all.return_value = {"records": [{"Id": "001ABC", "Posthog_Org_ID__c": "org-uuid-1"}]}
+ mock_sf_client.return_value = mock_sf
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await cache_org_mappings_activity(force_rebuild=True)
+
+ # A positive cached count must not short-circuit a forced rebuild.
+ assert result["total_mappings"] == 1
+ assert "cache_reused" not in result
+ mock_store.assert_called_once()
+
class TestEnrichOrgPageActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
@patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
async def test_enriches_page_successfully(self, _mock_close, mock_get_page, mock_sf_client, _mock_heartbeat):
mock_get_page.return_value = [
@@ -208,20 +250,19 @@ class TestEnrichOrgPageActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
- async def test_returns_empty_on_cache_miss(self, _mock_close, mock_get_page, _mock_heartbeat):
- mock_get_page.return_value = None
+ async def test_raises_when_cache_is_missing(self, _mock_close, mock_get_page, _mock_heartbeat):
+ mock_get_page.side_effect = OrgMappingsCacheMissingError("org mappings cache key is missing")
- result = await enrich_org_page_activity(0, 10000, 100)
+ with pytest.raises(ApplicationError) as exc_info:
+ await enrich_org_page_activity(0, 10000, 100)
- assert result.page_size == 0
- assert result.processed == 0
- assert result.updated == 0
+ assert exc_info.value.type == ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
async def test_returns_empty_on_empty_page(self, _mock_close, mock_get_page, _mock_heartbeat):
mock_get_page.return_value = []
@@ -234,7 +275,7 @@ class TestEnrichOrgPageActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
@patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
async def test_handles_salesforce_partial_failure(
self, _mock_close, mock_get_page, mock_sf_client, _mock_heartbeat
@@ -263,7 +304,7 @@ class TestEnrichOrgPageActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
@patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
async def test_handles_batch_exception(self, _mock_close, mock_get_page, mock_sf_client, _mock_heartbeat):
mock_get_page.return_value = [
@@ -287,7 +328,7 @@ class TestEnrichOrgPageActivity(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
- @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page_from_redis", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@patch(f"{WORKFLOW_MODULE}.close_old_connections")
async def test_passes_offset_to_redis(self, _mock_close, mock_get_page, _mock_heartbeat):
mock_get_page.return_value = []
@@ -306,7 +347,7 @@ class TestProductionModeContinueAsNew(TestCase):
async def test_continues_as_new_when_page_is_full(self, mock_workflow):
mock_workflow.execute_activity = AsyncMock(
side_effect=[
- None, # cache_org_mappings_activity
+ {"success": True, "total_mappings": 20000}, # cache_org_mappings_activity
EnrichPageResult(page_size=10000, processed=10000, updated=9500, errors=[]),
]
)
@@ -358,21 +399,81 @@ class TestProductionModeContinueAsNew(TestCase):
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.workflow")
- async def test_empty_page_returns_result(self, mock_workflow):
- mock_workflow.execute_activity = AsyncMock(
- side_effect=[
- None, # cache_org_mappings_activity
- EnrichPageResult(page_size=0, processed=0, updated=0, errors=[]),
- ]
- )
+ async def test_skips_paging_when_no_org_mappings(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(return_value={"success": True, "total_mappings": 0})
wf = SalesforceUsageEnrichmentWorkflow()
inputs = UsageEnrichmentInputs(batch_size=100)
result = await wf._run_production_mode(inputs)
+ assert mock_workflow.execute_activity.call_count == 1
assert result["total_orgs_processed"] == 0
assert result["total_orgs_updated"] == 0
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_recaches_and_retries_page_when_cache_expires_mid_run(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ {"success": True, "total_mappings": 15000},
+ EnrichPageResult(page_size=5000, processed=5000, updated=4800, errors=[]),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ wf = SalesforceUsageEnrichmentWorkflow()
+ state = UsageEnrichmentState(page_offset=10000, total_processed=10000, total_updated=9500)
+ result = await wf._run_production_mode(UsageEnrichmentInputs(batch_size=100, state=state))
+
+ assert mock_workflow.execute_activity.call_count == 3
+ # The rewarm must force a rebuild — reusing an existing (possibly unreadable)
+ # list would make the retry read the same bad data.
+ rewarm_call = mock_workflow.execute_activity.call_args_list[1]
+ assert rewarm_call.kwargs["args"] == [True]
+ # The retried page must target the same offset and page size as the failed one.
+ retried_call = mock_workflow.execute_activity.call_args_list[2]
+ assert retried_call.kwargs["args"] == [10000, 10000, 100]
+ assert result["total_orgs_processed"] == 15000
+ assert result["total_orgs_updated"] == 14300
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_returns_gracefully_when_recache_finds_no_mappings(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ {"success": True, "total_mappings": 0},
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ wf = SalesforceUsageEnrichmentWorkflow()
+ state = UsageEnrichmentState(page_offset=10000, total_processed=10000, total_updated=9500)
+ result = await wf._run_production_mode(UsageEnrichmentInputs(batch_size=100, state=state))
+
+ assert mock_workflow.execute_activity.call_count == 2
+ assert result["total_orgs_processed"] == 10000
+ assert result["total_orgs_updated"] == 9500
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.workflow")
+ async def test_second_cache_miss_after_recache_propagates(self, mock_workflow):
+ mock_workflow.execute_activity = AsyncMock(
+ side_effect=[
+ _cache_missing_activity_error(),
+ {"success": True, "total_mappings": 15000},
+ _cache_missing_activity_error(),
+ ]
+ )
+ mock_workflow.continue_as_new = MagicMock()
+
+ wf = SalesforceUsageEnrichmentWorkflow()
+ state = UsageEnrichmentState(page_offset=10000)
+
+ with pytest.raises(ActivityError):
+ await wf._run_production_mode(UsageEnrichmentInputs(batch_size=100, state=state))
+
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.workflow")
async def test_errors_capped_at_10_across_continuations(self, mock_workflow):
diff --git a/products/conversations/backend/migrations/0046_ticket_org_id_indexes.py b/products/conversations/backend/migrations/0046_ticket_org_id_indexes.py
new file mode 100644
index 000000000000..8141349e1071
--- /dev/null
+++ b/products/conversations/backend/migrations/0046_ticket_org_id_indexes.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [("conversations", "0045_zendesk_ticket_uniq")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(fields=["organization_id"], name="posthog_org_id_idx"),
+ ),
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ fields=["organization_id", "slack_channel_id"],
+ name="posthog_org_slack_ch_idx",
+ condition=models.Q(channel_source="slack"),
+ ),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 34c0a68a10e9..5350e58d7649 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0045_zendesk_ticket_uniq
+0046_ticket_org_id_indexes
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index bea1c8d7a682..929746777ba3 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -148,6 +148,12 @@ class Ticket(UUIDTModel):
name="posthog_con_snooze_wake_idx",
condition=models.Q(snoozed_until__isnull=False),
),
+ models.Index(fields=["organization_id"], name="posthog_org_id_idx"),
+ models.Index(
+ fields=["organization_id", "slack_channel_id"],
+ name="posthog_org_slack_ch_idx",
+ condition=models.Q(channel_source="slack"),
+ ),
]
constraints = [
models.UniqueConstraint(fields=["team", "ticket_number"], name="unique_ticket_number_per_team"),
diff --git a/tach.toml b/tach.toml
index 9aa923c8074d..952230fe2fd9 100644
--- a/tach.toml
+++ b/tach.toml
@@ -39,6 +39,7 @@ depends_on = [
"products.actions",
"products.alerts",
"products.cdp",
+ "products.conversations",
"products.customer_analytics",
"products.dashboards",
"products.data_modeling",