: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): clear cached slack profiles on app uninstall (#76558)
Vojta Bartošae2f5bad910e
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 3ce5f2883bda..9fa56b647729 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -97,6 +97,7 @@ from products.slack_app.backend.services.slack_app_home import (handle_app_home_view_submission as _handle_app_home_view_submission,)from products.slack_app.backend.services.slack_user_info import (+ clear_workspace_profile_cache,get_cached_bot_user_id,get_slack_user_info,normalize_slack_response,@@ -119,6 +120,7 @@ HANDLED_EVENT_TYPES = ["assistant_thread_started","assistant_thread_context_changed","app_home_opened",+ "app_uninstalled",]# The notifications Slack app (`slack`) install carries every scope the coding-agent flow@@ -1768,6 +1770,20 @@ def _route_assistant_event()+def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:+ """Drop the workspace's cached Slack profiles so a reinstall resolves users from+ fresh ``users.info`` data instead of emails cached under the previous install.++ Fanned out once to the other region (loop-guarded) since a dual-owned workspace+ caches profiles on both sides.+ """+ deleted = clear_workspace_profile_cache(slack_team_id)+ logger.info("slack_app_uninstalled_profile_cache_cleared", slack_team_id=slack_team_id, rows_deleted=deleted)+ if not was_proxied(request) and cross_region_routing_enabled():+ _proxy_event_to_region(request, other_region_domain(request.get_host()))+ return ROUTE_HANDLED_LOCALLY++def route_posthog_code_event_to_relevant_region(request: HttpRequest,event: dict,@@ -1800,6 +1816,9 @@ def route_posthog_code_event_to_relevant_region(eu_domain=_eu_region_domain(),)+ if event_type == "app_uninstalled":+ return _handle_app_uninstalled(request, slack_team_id)+# App Home tab: published per-user when they open the Home tab. Always# handled locally — `views.publish` just renders a snapshot of the user's# AI preferences against the integration row, no cross-region state.diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.pyindex 612d8f83b98b..bcd722f8838f 100644--- a/products/slack_app/backend/services/slack_user_info.py+++ b/products/slack_app/backend/services/slack_user_info.py@@ -26,7 +26,7 @@ from django.utils import timezoneimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegrationfrom products.slack_app.backend.models import SlackUserProfileCachefrom products.slack_app.backend.services.slack_auth import (@@ -210,6 +210,27 @@ def _purge_stale_email_rows(integration: Integration, normalized_email: str, keelogger.warning("slack_app_slack_user_cache_db_unavailable", integration_id=integration.id)+def clear_workspace_profile_cache(slack_team_id: str) -> int:+ """Delete every cached Slack profile for the workspace, returning the row count.++ Called when the app is uninstalled, so a reinstall resolves users from fresh+ ``users.info`` data instead of emails cached under the previous install.++ A transient database failure is logged and swallowed (returning 0): raising would+ 500 the webhook, and since Slack retries are acked without reprocessing, the event+ would be lost — along with the cross-region fan-out that follows the clear. Rows+ that survive a failed clear age out via the cache TTL.+ """+ try:+ deleted, _ = SlackUserProfileCache.objects.filter(+ integration__kind__in=SLACK_INTEGRATION_KINDS, integration__integration_id=slack_team_id+ ).delete()+ except DatabaseError:+ logger.warning("slack_app_uninstall_profile_cache_clear_failed", slack_team_id=slack_team_id, exc_info=True)+ return 0+ return deleted++def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:"""Return the bot's Slack user id for ``integration``, populating theshared auth-state cache as a side effect.diff --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 547f7d39a190..d4f897b0ac8c 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@@ -78,6 +78,7 @@ class TestPostHogCodeEventHandler(SimpleTestCase):("app_mention_no_integration", "app_mention", "no_integration", 202, True),("member_joined_channel_routes", "member_joined_channel", "handled_locally", 202, True),("message_dm_routes", "message", "handled_locally", 202, True),+ ("app_uninstalled_routes", "app_uninstalled", "handled_locally", 202, True),("non_handled_event_type_skips_routing", "reaction_added", "handled_locally", 202, False),])@@ -201,6 +202,63 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_sync_connect.return_value.start_workflow.assert_called_once()mock_asyncio_run.assert_called_once()+ @parameterized.expand(+ [+ ("fans_out_to_other_region", False, 1),+ ("proxied_does_not_fan_out_again", True, 0),+ ]+ )+ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_app_uninstalled_clears_workspace_profile_cache(+ self, _name, proxied: bool, expected_proxy_calls: int, mock_proxy+ ):+ # An uninstall must clear the workspace's cached Slack profiles (stale emails+ # otherwise break user resolution after a reinstall) while leaving other+ # workspaces' cache rows and the Integration row itself untouched.+ other_integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T99999",+ sensitive_config={"access_token": "xoxb-other"},+ )+ SlackUserProfileCache.objects.create(+ integration=other_integration,+ slack_user_id="U999",+ email="[email protected]",+ )++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ headers = {"x-posthog-region-proxied": "1"} if proxied else {}+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com", headers=headers)+ result = route_posthog_code_event_to_relevant_region(request, {"type": "app_uninstalled"}, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ assert not SlackUserProfileCache.objects.filter(integration=self.posthog_code_integration).exists()+ assert SlackUserProfileCache.objects.filter(integration=other_integration).exists()+ assert Integration.objects.filter(id=self.posthog_code_integration.id).exists()+ assert mock_proxy.call_count == expected_proxy_calls++ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.services.slack_user_info.SlackUserProfileCache.objects.filter")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_app_uninstalled_db_failure_still_acks_and_fans_out(self, mock_filter, mock_proxy):+ # A transient DB error during the cache clear must not raise: Slack acks+ # retries without reprocessing, so a 500 would lose the event — and the+ # cross-region fan-out that follows the clear would be skipped too.+ from django.db.utils import DatabaseError++ mock_filter.side_effect = DatabaseError("connection lost")++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ result = route_posthog_code_event_to_relevant_region(request, {"type": "app_uninstalled"}, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_proxy.assert_called_once()+@parameterized.expand([(