:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(slack-app): attribute answer ratings by cached slack email (#128022)
Vojta Bartoše6e95c144945
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 17635f2749e5..65ec740a59b9 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -37,13 +37,7 @@ from products.slack_app.backend.feature_flags import is_slack_app_byos_enabled,from products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_usedfrom products.slack_app.backend.logic.interview_recruitment import INVITE_MESSAGE, book_button, invite_section-from products.slack_app.backend.models import (- ChannelWelcomeMode,- SlackSettings,- SlackUserProfileCache,- ThreadJoinMode,- UntaggedFollowupMode,-)+from products.slack_app.backend.models import ChannelWelcomeMode, SlackSettings, ThreadJoinMode, UntaggedFollowupModefrom products.slack_app.backend.services.integration_resolver import load_integrations, resolve_from_candidatesfrom products.slack_app.backend.services.model_catalogue import (COST_BASELINE_MODEL,@@ -85,7 +79,10 @@ from products.slack_app.backend.services.slack_settings import (set_untagged_followup_mode,set_untagged_question_mode,)-from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin+from products.slack_app.backend.services.slack_user_info import (+ find_member_by_cached_slack_email,+ is_slack_workspace_admin,+)from products.slack_app.backend.services.slack_user_oauth import build_invite_url, find_linked_posthog_userfrom products.slack_app.backend.services.workspace_integrations import (WorkspaceIntegration,@@ -2640,19 +2637,9 @@ def _resolve_home_user(integration: WorkspaceIntegration, slack_user_id: str) ->if linked_user is not None:return linked_user- profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id).first()- if profile is None or not profile.email:- return None- membership = (- OrganizationMembership.objects.filter(- organization_id__in=candidate_org_ids,- user__email__iexact=profile.email,- user__is_active=True,- )- .select_related("user")- .first()+ return find_member_by_cached_slack_email(+ slack_team_id=slack_team_id, slack_user_id=slack_user_id, candidate_org_ids=candidate_org_ids)- return membership.user if membership else Nonedef _analytics_home_user(integration: WorkspaceIntegration, slack_user_id: str) -> User | None:diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.pyindex debf36ab335c..a6a1d55656c5 100644--- a/products/slack_app/backend/services/slack_user_info.py+++ b/products/slack_app/backend/services/slack_user_info.py@@ -18,8 +18,10 @@ keeps `api.py` focused on routes."""import re+from collections.abc import Iterablefrom datetime import timedeltafrom typing import Any+from uuid import UUIDfrom django.core.cache import cachefrom django.db.utils import DatabaseError@@ -30,6 +32,8 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.integrations import IntegrationRecordfrom posthog.models.integration import SLACK_INTEGRATION_KINDS, SlackIntegration+from posthog.models.organization import OrganizationMembership+from posthog.models.user import Userfrom products.slack_app.backend.models import SlackUserProfileCachefrom products.slack_app.backend.services.slack_auth import (@@ -39,6 +43,7 @@ from products.slack_app.backend.services.slack_auth import (write_auth_state_broken,write_auth_state_ok,)+from products.slack_app.backend.services.workspace_integrations import workspace_integrationslogger = structlog.get_logger(__name__)@@ -214,6 +219,42 @@ def _purge_stale_email_rows(integration: IntegrationRecord, normalized_email: stlogger.warning("slack_app_slack_user_cache_db_unavailable", integration_id=integration.id)+def find_member_by_cached_slack_email(+ *, slack_team_id: str, slack_user_id: str, candidate_org_ids: Iterable[UUID]+) -> User | None:+ """The active member of ``candidate_org_ids`` whose email matches the cached Slack profile.++ The fallback for a Slack identity without an OAuth link. It reads only the profile cache,+ so it costs no ``users.info`` call. Any install of the workspace may have cached the+ profile, so the lookup is scoped to the Slack team and not to one integration row.+ """+ org_ids = set(candidate_org_ids)+ if not slack_team_id or not slack_user_id or not org_ids:+ return None+ profile = (+ SlackUserProfileCache.objects.filter(+ integration_id__in=[row.id for row in workspace_integrations(slack_team_id)],+ slack_user_id=slack_user_id,+ )+ .exclude(email__isnull=True)+ .exclude(email="")+ .order_by("-updated_at")+ .first()+ )+ if profile is None:+ return None+ membership = (+ OrganizationMembership.objects.filter(+ organization_id__in=org_ids,+ user__email__iexact=profile.email,+ user__is_active=True,+ )+ .select_related("user")+ .first()+ )+ return membership.user if membership else None++def clear_workspace_profile_cache(slack_team_id: str) -> int:"""Delete every cached Slack profile for the workspace, returning the row count.diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.pyindex 5fe03c71bb2b..0ca1f13c5342 100644--- a/products/slack_app/backend/services/turn_feedback.py+++ b/products/slack_app/backend/services/turn_feedback.py@@ -36,7 +36,10 @@ from products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_usedfrom products.slack_app.backend.logic.interview_recruitment import MODAL_INVITE_MESSAGE, book_button, invite_sectionfrom products.slack_app.backend.services.slack_messages import SLACK_WEBHOOK_TIMEOUT_SECONDS, TURN_FEEDBACK_ACTION_ID-from products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id+from products.slack_app.backend.services.slack_user_info import (+ find_member_by_cached_slack_email,+ get_cached_bot_user_id,+)from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, get_workspace_integrationlogger = structlog.get_logger(__name__)@@ -229,17 +232,26 @@ def _distinct_id(target: _FeedbackTarget) -> str:"""Who the feedback is attributed to.The PostHog user behind the Slack identity when there is one, so a rating joins that- person's feedback from the web and desktop clients. An unlinked reader is attributed to- the project instead of minting a person keyed on a Slack id; ``slack_user_id`` rides on- the event either way, so the click is still traceable to someone we can follow up with.+ person's feedback from the web and desktop clients. The OAuth link wins, else the cached+ Slack profile email is matched against the project's organization, the same cascade that+ resolves who started the task. Most readers never link, so without the email match their+ ratings carry no person. A reader neither way finds is attributed to the project instead+ of minting a person keyed on a Slack id; ``slack_user_id`` rides on the event either way,+ so the click is still traceable to someone we can follow up with."""from products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user # noqa: PLC0415+ slack_team_id = target.integration.integration_id or ""+ candidate_org_ids = {target.integration.team.organization_id}try:user = find_linked_posthog_user(slack_user_id=target.slack_user_id,- slack_team_id=target.integration.integration_id or "",- candidate_org_ids={target.integration.team.organization_id},+ slack_team_id=slack_team_id,+ candidate_org_ids=candidate_org_ids,+ ) or find_member_by_cached_slack_email(+ slack_team_id=slack_team_id,+ slack_user_id=target.slack_user_id,+ candidate_org_ids=candidate_org_ids,)if user is not None and user.distinct_id:return user.distinct_iddiff --git a/products/slack_app/backend/tests/test_turn_feedback.py b/products/slack_app/backend/tests/test_turn_feedback.pyindex c42cfc905d40..1142e862dd6a 100644--- a/products/slack_app/backend/tests/test_turn_feedback.py+++ b/products/slack_app/backend/tests/test_turn_feedback.py@@ -9,12 +9,13 @@ from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models.integration import Integration-from posthog.models.organization import Organization+from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.slack_app.backend.logic import interview_recruitmentfrom products.slack_app.backend.logic.interview_recruitment import BOOKING_URL+from products.slack_app.backend.models import SlackUserProfileCachefrom products.slack_app.backend.services.slack_messages import TURN_FEEDBACK_ACTION_ID, turn_feedback_blockfrom products.slack_app.backend.services.slack_user_info import cache_workspace_bot_user_idfrom products.slack_app.backend.services.turn_feedback import (@@ -136,6 +137,24 @@ class TestTurnFeedback(TestCase):assert properties["$ai_trace_id"] is Noneassert self.mock_slack.return_value.client.views_open.called is asks_for_a_reason+ @parameterized.expand(+ [+ ("cached_email_of_a_member", "[email protected]", True, True),+ ("deactivated_member", "[email protected]", False, False),+ ("email_of_no_member", "[email protected]", True, False),+ ]+ )+ def test_an_unlinked_rater_is_attributed_by_cached_slack_email(self, _name, email, is_active, attributed):+ OrganizationMembership.objects.create(organization=self.org, user=self.user)+ self.user.is_active = is_active+ self.user.save(update_fields=["is_active"])+ SlackUserProfileCache.objects.create(integration=self.integration, slack_user_id="U_ALICE", email=email)++ self._pick(self._thumb_value("positive"))++ expected = self.user.distinct_id if attributed else str(self.team.uuid)+ assert self.mock_analytics.capture.call_args.kwargs["distinct_id"] == expected+def test_a_rating_names_the_turn_the_reply_answered(self):trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"