:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack-app): record why a slack user was not identified (#108340)
Vojta Bartoš9da9446becbb
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 913ab669ac75..85b1ef7ea37b 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -72,6 +72,7 @@ from products.slack_app.backend.services.integration_resolver import (pick_a_project_message,resolve_from_candidates,resolve_user_for_workspace,+ unresolved_user_properties,user_resolution_failure_reply,)from products.slack_app.backend.services.slack_app_home import (@@ -2403,6 +2404,7 @@ def route_posthog_code_event_to_relevant_region(reason=f"user_unresolved:{resolution.failure_reason or 'unknown'}",replied=False,integration=untagged_followup_mapping.integration,+ **unresolved_user_properties(resolution, untagged_followup_mapping.integration),)return ROUTE_HANDLED_LOCALLY# Keep the failure reply out of the channel in an unapproved@@ -2438,6 +2440,7 @@ def route_posthog_code_event_to_relevant_region(replied=replied,integration=probe,posthog_user=attributed_user,+ **unresolved_user_properties(resolution, probe),)return ROUTE_HANDLED_LOCALLYdiff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 8daf69d919d9..a24e3fdafaba 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -1,6 +1,6 @@from collections.abc import Iterablefrom dataclasses import field-from typing import Literal+from typing import Literal, TypedDictfrom django.db.models import Q@@ -13,6 +13,7 @@ from posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.user_permissions import UserPermissionsfrom products.signals.backend.facade import api as signals_facade+from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabledfrom products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMappingfrom products.slack_app.backend.services.slack_fork_context import get_pending_fork@@ -351,6 +352,34 @@ class UserAndIntegrationsResolution:return _resolved_or_oldest(self.integration, self.candidates)+def _active_account_exists(email: str | None) -> bool | None:+ if not email:+ return None+ try:+ return User.objects.filter(email__iexact=email, is_active=True).exists()+ except Exception:+ # A database error must not fail the Slack webhook, because Slack replays a failed event.+ logger.warning("slack_app_account_lookup_failed", exc_info=True)+ return None+++class UnresolvedUserProperties(TypedDict):+ slack_email_available: bool+ posthog_account_exists: bool | None+ account_linking_available: bool+++def unresolved_user_properties(+ resolution: UserAndIntegrationsResolution, probe: Integration+) -> UnresolvedUserProperties:+ """Analytics properties that tell apart the reasons a Slack user was not identified."""+ return {+ "slack_email_available": bool(resolution.slack_email),+ "posthog_account_exists": _active_account_exists(resolution.slack_email),+ "account_linking_available": is_slack_app_oauth_enabled(probe),+ }++def resolve_user_for_workspace(*,workspace_result: ResolutionResult,diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex d5078e6c73c1..2aa39464078e 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -11,10 +11,12 @@ from posthog.models.user import Userfrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping, SlackUserProfileCachefrom products.slack_app.backend.services.integration_resolver import (+ UserAndIntegrationsResolution,load_integrations,pick_a_project_message,resolve_from_candidates,resolve_user_for_workspace,+ unresolved_user_properties,)WORKSPACE = "T_WS"@@ -819,3 +821,53 @@ class TestPickAProjectMessage:assert "<!channel>" not in messageassert "<!channel>" in messageassert "<https://evil.example|Open PostHog>" not in message+++class TestUnresolvedUserProperties:+ @pytest.mark.parametrize(+ "slack_email, account, scope, expected",+ [+ pytest.param(+ None,+ None,+ "users:read,users:read.email",+ {"slack_email_available": False, "posthog_account_exists": None, "account_linking_available": True},+ id="slack_exposes_no_email",+ ),+ pytest.param(+ "[email protected]",+ None,+ "users:read,users:read.email",+ {"slack_email_available": True, "posthog_account_exists": False, "account_linking_available": True},+ id="no_posthog_account",+ ),+ pytest.param(+ "[email protected]",+ "active",+ "users:read,users:read.email",+ {"slack_email_available": True, "posthog_account_exists": True, "account_linking_available": True},+ id="account_outside_the_connected_organizations",+ ),+ pytest.param(+ "[email protected]",+ "deactivated",+ "users:read,users:read.email",+ {"slack_email_available": True, "posthog_account_exists": False, "account_linking_available": True},+ id="deactivated_account",+ ),+ pytest.param(+ "[email protected]",+ None,+ "chat:write",+ {"slack_email_available": True, "posthog_account_exists": False, "account_linking_available": False},+ id="install_cannot_link_accounts",+ ),+ ],+ )+ def test_reports_why_the_slack_user_was_not_identified(self, db, slack_email, account, scope, expected):+ if account is not None:+ User.objects.create(email=slack_email.lower(), distinct_id="u-outside", is_active=account == "active")+ probe = Integration(kind="slack", integration_id=WORKSPACE, config={"scope": scope})+ resolution = UserAndIntegrationsResolution(failure_reason="user_not_found", slack_email=slack_email)++ assert unresolved_user_properties(resolution, probe) == expecteddiff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex 3287fec7377b..5699067e19fa 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -550,6 +550,8 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):assert captured["posthog code slack mention received"]["posthog_user_identified"] is Falseassert captured[SLACK_MENTION_DROPPED_EVENT]["drop_reason"] == "user_unresolved:user_not_found"assert captured[SLACK_MENTION_DROPPED_EVENT]["replied"] is True+ assert captured[SLACK_MENTION_DROPPED_EVENT]["slack_email_available"] is True+ assert captured[SLACK_MENTION_DROPPED_EVENT]["posthog_account_exists"] is False@patch("products.slack_app.backend.api.posthoganalytics.capture")@patch("products.slack_app.backend.api._post_slack_user_ephemeral")diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.pyindex fa235af77121..5d0b1d748dbc 100644--- a/products/slack_app/backend/tests/test_thread_message_routing.py+++ b/products/slack_app/backend/tests/test_thread_message_routing.py@@ -332,11 +332,13 @@ class TestRouteThreadMessage(TestCase):with (patch("products.slack_app.backend.api._post_user_resolution_failure_reply") as mock_failure,patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,+ patch("products.slack_app.backend.api.posthoganalytics.capture") as mock_capture,):result = self._route(event)assert result == ROUTE_HANDLED_LOCALLYmock_failure.assert_not_called()mock_start.assert_not_called()+ assert mock_capture.call_args.kwargs["properties"]["slack_email_available"] is False# --- Scope + approval gates ------------------------------------------