: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(subscriptions): auto-disable on terminal slack api errors (#56772)
Vasco de Krijger2339a20fae02
diff --git a/ee/tasks/subscriptions/__init__.py b/ee/tasks/subscriptions/__init__.pyindex 1764eee52eb0..83f2d5937f62 100644--- a/ee/tasks/subscriptions/__init__.py+++ b/ee/tasks/subscriptions/__init__.py@@ -7,9 +7,10 @@ from posthog.models.subscription import Subscriptionlogger = structlog.get_logger(__name__)-# Slack errors that are user configuration issues, not system failures+# Slack errors that won't self-heal without user action — skip Temporal retries+# and auto-disable the subscription so it stops re-firing every cycle.SLACK_USER_CONFIG_ERRORS = frozenset(- ["not_in_channel", "account_inactive", "is_archived", "channel_not_found", "invalid_auth"]+ {"not_in_channel", "account_inactive", "is_archived", "channel_not_found", "invalid_auth", "token_revoked"})diff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.pyindex 07c9e2e08c97..237a9cb0ae20 100644--- a/ee/tasks/subscriptions/auto_disable.py+++ b/ee/tasks/subscriptions/auto_disable.py@@ -29,6 +29,11 @@ UNSUPPORTED_TARGET_DISABLE_REASON = DisableReason(description="Unsupported delivery channel",user_message="Cannot re-enable {target_type} subscription: this delivery channel is not currently supported.",)+SLACK_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(+ key="slack_permission_revoked",+ description="PostHog can no longer post to this Slack channel",+ user_message="Cannot re-enable {target_type} subscription: PostHog can't post to this Slack channel. Reconnect Slack or re-add the bot to the channel, then try again.",+)logger = structlog.get_logger(__name__)diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.pyindex 5e46e5d33acd..d2dc5bd4fe03 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/posthog/temporal/subscriptions/activities.py@@ -38,6 +38,7 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_eventfrom ee.tasks.subscriptions.auto_disable import (SLACK_DISCONNECTED_DISABLE_REASON,+ SLACK_PERMISSION_REVOKED_DISABLE_REASON,UNSUPPORTED_TARGET_DISABLE_REASON,DisableReason,disable_invalid_subscription,@@ -551,7 +552,8 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsexcept ApplicationError:raiseexcept Exception as e:- is_user_config_error = isinstance(e, SlackApiError) and e.response.get("error") in SLACK_USER_CONFIG_ERRORS+ slack_error_code = e.response.get("error") if isinstance(e, SlackApiError) else None+ is_user_config_error = slack_error_code in SLACK_USER_CONFIG_ERRORS_capture_delivery_failed_event(subscription, e)LOGGER.error("deliver_subscription.slack_failed",@@ -561,15 +563,13 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsexc_info=True,)capture_exception(e)- recipient_results.append(- RecipientResult(- recipient=subscription.target_value,- status="failed",- error={"message": str(e), "type": type(e).__name__},+ if is_user_config_error:+ # Won't self-heal without user action — auto-disable so the subscription+ # stops re-firing every cycle.+ return await _auto_disable_and_return(+ subscription, SLACK_PERMISSION_REVOKED_DISABLE_REASON, recipient_results)- )- if not is_user_config_error:- raise # Transient Slack errors — let Temporal retry+ raise # Transient Slack errors — let Temporal retryawait LOGGER.ainfo("deliver_subscription.completed",diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 40302f4f8675..5fa860f8eb8b 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -15,6 +15,7 @@ from django.conf import settingsimport pytest_asynciofrom asgiref.sync import sync_to_async+from slack_sdk.errors import SlackApiErrorfrom temporalio.client import Clientfrom temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -711,6 +712,134 @@ async def test_validate_subscription_for_delivery(assert subscription.enabled is expected_final_enabled+async def test_deliver_subscription_short_circuits_when_already_disabled(team, user):+ """Activity retries that fire after the subscription is disabled must return+ cleanly — re-entering the missing-integration branch would re-fire the+ auto-disable side effects (event capture, email notification).+ """+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="dis02", name="Already Disabled")+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ insight=insight,+ export_format="image/png",+ content_location="s3://bucket/already-disabled.png",+ )+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="slack",+ target_value="C12345|#test-channel",+ enabled=False,+ )++ env = ActivityEnvironment()++ with patch("posthog.temporal.subscriptions.activities.disable_invalid_subscription") as disable_mock:+ result = await env.run(+ deliver_subscription,+ DeliverSubscriptionInputs(+ subscription_id=subscription.id,+ exported_asset_ids=[asset.id],+ total_insight_count=1,+ ),+ )++ assert result.recipient_results == []+ disable_mock.assert_not_called()+++async def _setup_slack_delivery_test_case(+ team, user, slack_error_code: str+) -> tuple[Subscription, DeliverSubscriptionInputs, MagicMock, SlackApiError]:+ insight = await sync_to_async(Insight.objects.create)(+ team=team, short_id=f"slk-{slack_error_code[:5]}", name=slack_error_code+ )+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ insight=insight,+ export_format="image/png",+ content_location=f"s3://bucket/{slack_error_code}.png",+ )+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="slack",+ target_value="C12345|#test-channel",+ enabled=True,+ )+ mock_integration = MagicMock()+ mock_integration.kind = "slack"+ slack_error = SlackApiError("Slack API error", response={"error": slack_error_code, "ok": False})+ inputs = DeliverSubscriptionInputs(+ subscription_id=subscription.id,+ exported_asset_ids=[asset.id],+ total_insight_count=1,+ )+ return subscription, inputs, mock_integration, slack_error+++ "slack_error_code, expect_auto_disable",+ [+ # User-config errors won't self-heal without user action — auto-disable.+ ("invalid_auth", True),+ ("account_inactive", True),+ ("token_revoked", True),+ ("is_archived", True),+ ("channel_not_found", True),+ ("not_in_channel", True),+ # Transient errors propagate so Temporal retries.+ ("internal_error", False),+ ("rate_limited", False),+ ],+)+async def test_deliver_subscription_handles_slack_api_errors(team, user, slack_error_code, expect_auto_disable):+ subscription, inputs, mock_integration, slack_error = await _setup_slack_delivery_test_case(+ team, user, slack_error_code+ )++ with (+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,+ patch(+ "posthog.temporal.subscriptions.activities.get_slack_integration_for_team",+ return_value=mock_integration,+ ),+ patch(+ "posthog.temporal.subscriptions.activities.send_slack_message_with_integration_async",+ new_callable=AsyncMock,+ side_effect=slack_error,+ ),+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ if expect_auto_disable:+ result = await ActivityEnvironment().run(deliver_subscription, inputs)+ else:+ with pytest.raises(SlackApiError):+ await ActivityEnvironment().run(deliver_subscription, inputs)+ result = None++ await sync_to_async(subscription.refresh_from_db)()+ if expect_auto_disable:+ # Two captures: the real SlackApiError, and the synthetic Exception from the auto-disable helper.+ assert capture_mock.call_count == 2+ assert subscription.enabled is False+ send_mock.assert_called_once()+ assert result is not None+ assert result.recipient_results[0].status == "failed"+ assert result.recipient_results[0].error == {+ "message": "PostHog can no longer post to this Slack channel",+ "type": "slack_permission_revoked",+ }+ else:+ capture_mock.assert_called_once()+ assert subscription.enabled is True+ send_mock.assert_not_called()++@patch("posthog.slo.events.posthoganalytics")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncio