: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 when delivery cannot succeed (#56727)
Vasco de Krijger7515cab85ea2
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 1707f3ab61f5..ae63a319ddbc 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -43,6 +43,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerTypefrom posthog.utils import str_to_bool+from ee.tasks.subscriptions.auto_disable import validate_re_enablefrom ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNTSUMMARY_QUOTA_CACHE_TTL_SECONDS = 60@@ -132,6 +133,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"created_at","created_by","deleted",+ "enabled","title","summary","next_delivery_date",@@ -171,6 +173,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):"until_date": {"help_text": "When to stop delivering (ISO 8601 datetime). Null for indefinite."},"title": {"help_text": "Human-readable name for this subscription."},"deleted": {"help_text": "Set to true to soft-delete. Subscriptions cannot be hard-deleted."},+ "enabled": {+ "help_text": "Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid."+ },}def get_insight_short_id(self, obj: Subscription) -> Optional[str]:@@ -197,7 +202,41 @@ class SubscriptionSerializer(serializers.ModelSerializer):self._validate_dashboard_export_subscription(attrs)target_type = attrs.get("target_type") or (self.instance.target_type if self.instance else None)- integration_id = attrs.get("integration_id") or (self.instance.integration_id if self.instance else None)+ # Use explicit-key check for integration_id so a deliberate `null` in the PATCH+ # body falls through to the validation below — `or` would silently coalesce+ # to the stale instance value and pass `validate_re_enable` with the wrong id.+ integration_id = (+ attrs["integration_id"]+ if "integration_id" in attrs+ else (self.instance.integration_id if self.instance else None)+ )++ # Reject re-enables of subscriptions whose delivery prerequisite is still+ # permanently broken — otherwise the next delivery would just auto-disable+ # them again.+ is_re_enabling = self.instance is not None and attrs.get("enabled") is True and self.instance.enabled is False+ if is_re_enabling:+ error_message = validate_re_enable(target_type, integration_id)+ if error_message:+ raise ValidationError({"enabled": [error_message]})++ # Reject mutations that would land `next_delivery_date=None` — `enabled=True`+ # with a null next_delivery_date is invisible to the scheduler (the+ # `__lte=now` filter in `fetch_due_subscriptions_activity` drops nulls).+ # Three reachable paths: re-enable an exhausted sub, create one with a bad+ # rrule, or PATCH an active sub's schedule into exhaustion.+ check_schedule = (+ is_re_enabling+ or self.instance is None+ or (self.instance is not None and self.instance.enabled and bool(Subscription.RRULE_FIELDS & attrs.keys()))+ )+ if check_schedule and Subscription.project_next_delivery_date(instance=self.instance, **attrs) is None:+ base = "Subscription schedule has reached its end date. Extend until_date or remove count"+ if is_re_enabling:+ raise ValidationError({"enabled": [f"{base} before re-enabling."]})+ if self.instance is None:+ raise ValidationError({"start_date": [f"{base}."]})+ raise ValidationError(f"{base}.")if target_type == Subscription.SubscriptionTarget.SLACK:if not integration_id:@@ -408,6 +447,12 @@ class SubscriptionSerializer(serializers.ModelSerializer):if dashboard_export_insight_ids:instance.dashboard_export_insights.set(dashboard_export_insight_ids)+ # Skip the workflow trigger when the new subscription is created in a disabled+ # state — mirrors the equivalent guard in `update()`. Avoids firing a delivery+ # for a subscription that won't fire on its schedule either.+ if not instance.enabled:+ return instance+with slo_operation(spec=SloSpec(distinct_id=str(request.user.distinct_id),@@ -457,6 +502,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):def update(self, instance: Subscription, validated_data: dict, *args, **kwargs) -> Subscription:request = self.context["request"]previous_value = instance.target_value+ was_disabled = instance.enabled is Falseis_delete = not instance.deleted and validated_data.get("deleted") is Trueinvite_message = validated_data.pop("invite_message", "")dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])@@ -491,6 +537,21 @@ class SubscriptionSerializer(serializers.ModelSerializer):if dashboard_export_insight_ids:instance.dashboard_export_insights.set(dashboard_export_insight_ids)+ # Re-enabling clears the stale next_delivery_date that was frozen while+ # disabled. Without this, the scheduler picks the sub up on its next tick+ # (the past date matches `next_delivery_date__lte=now`) and fires a second+ # SCHEDULED delivery right after the immediate TARGET_CHANGE confirmation.+ if was_disabled and instance.enabled:+ instance.set_next_delivery_date()+ instance.save(update_fields=["next_delivery_date"])++ # Skip the workflow trigger when the resulting state is disabled. No delivery+ # should fire for a disabled subscription regardless of whether it was just+ # disabled or already disabled. Re-enabling (`enabled: false → true`) DOES+ # trigger the workflow so the user gets immediate confirmation delivery.+ if not instance.enabled:+ return instance+temporal = sync_connect()workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"asyncio.run(@@ -686,6 +747,11 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Msubscription = self.get_object()if subscription.deleted:return Response(status=status.HTTP_404_NOT_FOUND)+ if not subscription.enabled:+ return Response(+ {"detail": "Subscription is disabled. Re-enable it before sending a test delivery."},+ status=status.HTTP_409_CONFLICT,+ )temporal = sync_connect()workflow_id = f"test-delivery-subscription-{subscription.id}"diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex c091def1dff3..e62c27ac2ead 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Optionalfrom uuid import uuid4@@ -6,6 +6,7 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.core.cache import cache+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status@@ -105,6 +106,7 @@ class TestSubscriptionTemporal(APILicensedTest):"created_at": data["created_at"],"created_by": data["created_by"],"deleted": False,+ "enabled": True,"title": "My Subscription","next_delivery_date": data["next_delivery_date"],"integration_id": None,@@ -420,6 +422,57 @@ class TestSubscriptionTemporal(APILicensedTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "require a Slack integration" in response.json()["detail"]+ def test_patch_enabled_true_rejected_when_slack_integration_missing(self):+ """Re-enabling a disabled Slack subscription whose integration is gone must be+ rejected up front — otherwise the next delivery would auto-disable it again+ and the user would receive a confusing email seconds after hitting "Enable".+ """+ integration = Integration.objects.create(team=self.team, kind="slack", config={})+ create_response = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=integration.id,+ )+ assert create_response.status_code == status.HTTP_201_CREATED+ subscription_id = create_response.json()["id"]++ # Auto-disable: clear integration and disable the subscription+ Subscription.objects.filter(pk=subscription_id).update(enabled=False, integration=None)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",+ {"enabled": True},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "enabled"+ assert "Reconnect Slack" in response.json()["detail"]++ def test_patch_enabled_true_rejected_for_webhook_subscription(self):+ """Webhook delivery is not supported, so a webhook subscription auto-disables on+ first delivery. Re-enabling without changing target_type would just trigger the+ auto-disable path again — surface the precondition failure up front.+ """+ # Webhook subs can be created (target_type is in the model enum) but are+ # auto-disabled by the activity since `webhook` isn't in SUPPORTED_TARGET_TYPES.+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="webhook",+ target_value="https://example.com/hook",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="webhook sub",+ enabled=False,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": True},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "enabled"+ assert "this delivery channel is not currently supported" in response.json()["detail"]+def test_cannot_create_subscription_with_summary_enabled_without_ai_consent(self):self.organization.is_ai_data_processing_approved = Falseself.organization.save()@@ -860,6 +913,19 @@ class TestSubscriptionTemporal(APILicensedTest):response = self.client.post(f"/api/projects/{self.team.id}/subscriptions/{sub_id}/test-delivery/")assert response.status_code == status.HTTP_404_NOT_FOUND+ def test_deliver_disabled_subscription_returns_409(self):+ mock_client = MagicMock()+ mock_client.start_workflow = AsyncMock()+ self.mock_sync.return_value = mock_client++ response = self._create_subscription(invite_message=None)+ sub_id = response.json()["id"]+ Subscription.objects.filter(id=sub_id).update(enabled=False)++ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions/{sub_id}/test-delivery/")+ assert response.status_code == status.HTTP_409_CONFLICT+ assert "Re-enable" in response.json()["detail"]+def test_deliver_temporal_error_returns_500(self):mock_client = MagicMock()mock_client.start_workflow = AsyncMock(side_effect=[None, RuntimeError("Temporal unavailable")])@@ -1170,6 +1236,213 @@ class TestSubscriptionTemporal(APILicensedTest):assert results[0]["id"] == sub_idassert results[0]["target_type"] == target_type+ def test_patch_enabled_field(self):+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="t",+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": False},+ format="json",+ )+ assert response.status_code == 200, response.content+ assert response.json()["enabled"] is False+ subscription.refresh_from_db()+ assert subscription.enabled is False++ def test_re_enable_resets_stale_next_delivery_date(self):+ # Without this reset the scheduler's `next_delivery_date__lte=now` filter+ # picks the sub up on its next tick and fires a second delivery right+ # after the immediate TARGET_CHANGE confirmation.+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="t",+ enabled=False,+ )+ stale_date = timezone.now() - timedelta(days=3)+ Subscription.objects.filter(pk=subscription.pk).update(next_delivery_date=stale_date)++ with patch("ee.api.subscription.sync_connect") as temporal_mock:+ temporal_mock.return_value.start_workflow = AsyncMock()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": True},+ format="json",+ )++ assert response.status_code == 200, response.content+ subscription.refresh_from_db()+ assert subscription.enabled is True+ assert subscription.next_delivery_date is not None+ assert subscription.next_delivery_date > timezone.now()+ # Re-enable also fires the immediate TARGET_CHANGE confirmation delivery —+ # the date reset prevents the *scheduler* from firing a second one moments later.+ temporal_mock.return_value.start_workflow.assert_called_once()++ @parameterized.expand(+ [+ # `until_date` already in the past → no future occurrence.+ ("until_date_in_past", {"until_date": -1}),+ # `count=2` deliveries already consumed at start_date and start_date+1d.+ ("count_exhausted", {"count": 2}),+ ]+ )+ def test_re_enable_rejects_when_rrule_exhausted(self, _label, schedule_kwargs):+ # Both exhaustion modes land `next_delivery_date=None` via+ # `set_next_delivery_date()`, the scheduler `__lte=now` filter excludes+ # nulls, and the sub would silently never schedule again.+ kwargs = dict(schedule_kwargs)+ if "until_date" in kwargs:+ kwargs["until_date"] = timezone.now() + timedelta(days=kwargs["until_date"])+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now() - timedelta(days=10),+ insight=self.insight,+ title="t",+ enabled=False,+ **kwargs,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": True},+ format="json",+ )++ assert response.status_code == 400, response.content+ assert "reached its end date" in str(response.json())+ subscription.refresh_from_db()+ assert subscription.enabled is False # rejected pre-write++ def test_patch_rrule_into_exhausted_state_is_rejected(self):+ # Path 2 of the silent-fail family: editing an active sub's schedule into+ # an exhausted state. `Subscription.save()` would call+ # `set_next_delivery_date()` and land `next_delivery_date=None`.+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now() - timedelta(days=10),+ insight=self.insight,+ title="t",+ enabled=True,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"until_date": (timezone.now() - timedelta(days=1)).isoformat()},+ format="json",+ )++ assert response.status_code == 400, response.content+ assert "reached its end date" in str(response.json())+ subscription.refresh_from_db()+ assert subscription.next_delivery_date is not None # unchanged++ def test_create_rejects_when_rrule_already_exhausted(self):+ # Symmetric hole at create-time: a brand-new sub with `until_date` in the+ # past would land `next_delivery_date=None` and silently never schedule.+ response = self._create_subscription(+ start_date="2020-01-01T00:00:00",+ until_date="2020-01-02T00:00:00",+ )+ assert response.status_code == 400, response.content+ assert "reached its end date" in str(response.json())++ def test_re_enable_with_extended_until_date_is_allowed(self):+ # User extending their schedule in the same PATCH that re-enables — the+ # candidate-rrule check honors the new `until_date` and lets it through.+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now() - timedelta(days=10),+ until_date=timezone.now() - timedelta(days=1),+ insight=self.insight,+ title="t",+ enabled=False,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": True, "until_date": (timezone.now() + timedelta(days=30)).isoformat()},+ format="json",+ )++ assert response.status_code == 200, response.content+ subscription.refresh_from_db()+ assert subscription.enabled is True+ # Scheduler-visible invariant: `next_delivery_date` must be a future timestamp,+ # not None — that's what the candidate-rrule validation defends.+ assert subscription.next_delivery_date is not None+ assert subscription.next_delivery_date > timezone.now()++ def test_get_returns_enabled_field(self):+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="t",+ )+ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/")+ assert response.status_code == 200, response.content+ assert response.json()["enabled"] is True++ @parameterized.expand(+ [+ # Locks the workflow-trigger matrix across all four (initial, final) enabled states.+ ("enabled_to_enabled_field_edit", True, {"title": "renamed"}, True),+ ("redundant_enable", True, {"enabled": True}, True),+ ("disable_enabled", True, {"enabled": False}, False),+ ("redundant_disable", False, {"enabled": False}, False),+ ("enable_disabled", False, {"enabled": True}, True),+ ]+ )+ def test_patch_workflow_trigger_for_enabled_field(+ self, _label, initial_enabled, patch_payload, expect_workflow_called+ ):+ subscription = Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="t",+ enabled=initial_enabled,+ )+ with patch("ee.api.subscription.sync_connect") as temporal_mock:+ temporal_mock.return_value.start_workflow = AsyncMock()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ patch_payload,+ format="json",+ )+ assert response.status_code == 200, response.content+ if expect_workflow_called:+ temporal_mock.return_value.start_workflow.assert_called_once()+ else:+ temporal_mock.return_value.start_workflow.assert_not_called()+class TestSubscriptionDeliveryAPI(APILicensedTest):subscription: Subscription = None # type: ignorediff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.pynew file mode 100644index 000000000000..07c9e2e08c97--- /dev/null+++ b/ee/tasks/subscriptions/auto_disable.py@@ -0,0 +1,130 @@+import uuid+from typing import NamedTuple++import structlog++from posthog.email import EmailMessage+from posthog.exceptions_capture import capture_exception+from posthog.models.subscription import Subscription++from ee.tasks.subscriptions import SUPPORTED_TARGET_TYPES+++class DisableReason(NamedTuple):+ # Stable identity used for analytics (`error_type`) and activity comparisons.+ key: str+ # Shown in the disabled-subscription email body and the activity's recipient_results.+ description: str+ # Re-enable rejection message surfaced by the API serializer; `{target_type}` is interpolated.+ user_message: str+++SLACK_DISCONNECTED_DISABLE_REASON = DisableReason(+ key="missing_integration",+ description="Slack integration disconnected",+ user_message="Cannot re-enable Slack subscription: no integration configured. Reconnect Slack first.",+)+UNSUPPORTED_TARGET_DISABLE_REASON = DisableReason(+ key="unsupported_target",+ description="Unsupported delivery channel",+ user_message="Cannot re-enable {target_type} subscription: this delivery channel is not currently supported.",+)++logger = structlog.get_logger(__name__)+++def get_subscription_disable_reason(target_type: str | None, integration_id: int | None) -> DisableReason | None:+ """Single source of truth for "what target configuration is permanently broken"."""+ if not target_type:+ return None+ if target_type not in SUPPORTED_TARGET_TYPES:+ return UNSUPPORTED_TARGET_DISABLE_REASON+ if target_type == Subscription.SubscriptionTarget.SLACK and not integration_id:+ return SLACK_DISCONNECTED_DISABLE_REASON+ return None+++def validate_re_enable(target_type: str | None, integration_id: int | None) -> str | None:+ """API-serializer wrapper — returns the user-facing rejection message, or None if re-enable is OK."""+ reason = get_subscription_disable_reason(target_type, integration_id)+ if reason is None:+ return None+ return reason.user_message.format(target_type=target_type)+++def disable_invalid_subscription(subscription: Subscription, reason: DisableReason) -> None:+ # Compare-and-swap so only one racing caller sends the disabled-notification+ # email (UUID4 campaign keys mean MessagingRecord can't dedup the duplicate).+ rowcount = Subscription.objects.filter(pk=subscription.pk, enabled=True).update(enabled=False)+ if rowcount == 0:+ # A concurrent caller already disabled the row — no-op, no side effects.+ # The in-memory `subscription.enabled` is intentionally NOT touched here so+ # callers can distinguish "we just disabled it" from "it was already disabled";+ # the activity site re-fetches via select_related when it needs fresh state.+ logger.info(+ "subscription.auto_disable_already_disabled",+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ reason=reason.key,+ )+ return++ logger.warning(+ "subscription.auto_disabling",+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ reason=reason.key,+ )+ # Mirror the UPDATE in memory so callers see the new state without a fresh+ # SELECT — refresh_from_db() would also drop the eagerly-loaded created_by+ # relation (loaded via select_related at the activity site).+ subscription.enabled = False++ if subscription.created_by and subscription.created_by.email:+ try:+ send_notifications_for_disabled_subscription(+ subscription, reason.description, [subscription.created_by.email]+ )+ except Exception as e:+ # Disabling is the durable side effect; email is best-effort. If the email+ # fails (SMTP outage, ImproperlyConfigured on self-hosted, Customer.io 5xx)+ # the SLO outcome must stay `success` — we successfully prevented the+ # subscription from re-firing, which is the contract this code provides.+ capture_exception(e)+ logger.warning(+ "subscription.send_disabled_notification_failed",+ subscription_id=subscription.id,+ error=str(e),+ exc_info=True,+ )+++def send_notifications_for_disabled_subscription(subscription: Subscription, reason: str, targets: list[str]) -> None:+ logger.info(+ "subscription.send_disabled_notification",+ subscription_id=subscription.id,+ recipient_count=len(targets),+ )++ display_name = subscription.title or "your subscription"+ subject = (+ f'PostHog subscription "{subscription.title}" has been automatically disabled'+ if subscription.title+ else "Your PostHog subscription has been automatically disabled"+ )+ campaign_key = f"subscription-disabled-notification-{subscription.id}-{uuid.uuid4()}"++ message = EmailMessage(+ campaign_key=campaign_key,+ subject=subject,+ template_name="subscription_disabled",+ template_context={+ "subscription_url": subscription.url,+ "subscription_title": display_name,+ "reason": reason,+ },+ )+ for target in targets:+ message.add_recipient(email=target)++ message.send()diff --git a/ee/tasks/subscriptions/test_auto_disable.py b/ee/tasks/subscriptions/test_auto_disable.pynew file mode 100644index 000000000000..fb30e59ed24f--- /dev/null+++ b/ee/tasks/subscriptions/test_auto_disable.py@@ -0,0 +1,147 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized++from posthog.models.subscription import Subscription++from ee.tasks.subscriptions.auto_disable import (+ SLACK_DISCONNECTED_DISABLE_REASON,+ disable_invalid_subscription,+ send_notifications_for_disabled_subscription,+ validate_re_enable,+)+++class TestValidateReEnable:+ """Direct unit tests for the shared re-enable validation helper.++ Mirrors the alert pattern's validate_alert_config tests — one source of truth+ for which target configurations the API rejects up-front.+ """++ @parameterized.expand(+ [+ # (label, target_type, integration_id, expected_None_or_substring)+ ("none_target_passes", None, None, None),+ ("email_no_integration_passes", "email", None, None),+ ("email_with_integration_passes", "email", 42, None),+ ("slack_with_integration_passes", "slack", 42, None),+ ("slack_no_integration_rejected", "slack", None, "no integration configured"),+ ("webhook_no_integration_rejected", "webhook", None, "this delivery channel is not currently supported"),+ ("webhook_with_integration_rejected", "webhook", 42, "this delivery channel is not currently supported"),+ ]+ )+ def test_validate_re_enable(self, _label, target_type, integration_id, expected):+ result = validate_re_enable(target_type, integration_id)+ if expected is None:+ assert result is None+ else:+ assert result is not None+ assert expected in result+++class TestDisableInvalidSubscription(APIBaseTest):+ def _make_subscription(self, **overrides) -> Subscription:+ defaults = {+ "team": self.team,+ "target_type": "slack",+ "target_value": "C12345",+ "frequency": "daily",+ "start_date": timezone.now(),+ "insight": None,+ "title": "t",+ "created_by": self.user,+ "enabled": True,+ }+ defaults.update(overrides)+ return Subscription.objects.create(**defaults)++ def test_disables_subscription(self):+ sub = self._make_subscription()++ with patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock:+ disable_invalid_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON)++ sub.refresh_from_db()+ assert sub.enabled is False+ send_mock.assert_called_once_with(sub, SLACK_DISCONNECTED_DISABLE_REASON.description, [self.user.email])++ def test_compare_and_swap_no_op_when_already_disabled(self):+ # Simulates a cross-workflow race: by the time this caller reaches the UPDATE,+ # another caller has already flipped enabled→False. We must NOT re-fire the+ # disabled-notification email (UUID4 campaign keys defeat MessagingRecord dedup).+ sub = self._make_subscription(enabled=False)++ with patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock:+ disable_invalid_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON)++ sub.refresh_from_db()+ assert sub.enabled is False+ send_mock.assert_not_called()++ @parameterized.expand(+ [+ ("no_creator", False),+ ("creator_with_empty_email", True),+ ]+ )+ def test_no_email_when_creator_unable_to_receive(self, _label, use_creator_with_empty_email):+ if use_creator_with_empty_email:+ self.user.email = ""+ self.user.save()+ sub = self._make_subscription(created_by=self.user)+ else:+ sub = self._make_subscription(created_by=None)++ with patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock:+ disable_invalid_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON)++ sub.refresh_from_db()+ assert sub.enabled is False+ send_mock.assert_not_called()++ def test_send_notifications_uses_unique_campaign_key_per_call(self):+ sub = self._make_subscription()++ with patch("ee.tasks.subscriptions.auto_disable.EmailMessage") as email_cls:+ send_notifications_for_disabled_subscription(+ sub, SLACK_DISCONNECTED_DISABLE_REASON.description, [self.user.email]+ )+ send_notifications_for_disabled_subscription(+ sub, SLACK_DISCONNECTED_DISABLE_REASON.description, [self.user.email]+ )++ first_key = email_cls.call_args_list[0].kwargs["campaign_key"]+ second_key = email_cls.call_args_list[1].kwargs["campaign_key"]+ # UUID4 suffix makes each call unique regardless of timing — no flakiness+ # if two calls land in the same millisecond.+ assert first_key != second_key+ prefix = f"subscription-disabled-notification-{sub.id}-"+ assert first_key.startswith(prefix)+ assert second_key.startswith(prefix)++ def test_disable_persists_when_email_send_fails(self):+ """Disabling is the durable side effect; email is best-effort.++ If the email send raises (SMTP outage, ImproperlyConfigured on self-hosted,+ Customer.io 5xx) the subscription must still end up disabled and the caller+ must not see an exception — the SLO outcome stays `success`.+ """+ sub = self._make_subscription()++ with (+ patch(+ "ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription",+ side_effect=RuntimeError("smtp down"),+ ) as send_mock,+ patch("ee.tasks.subscriptions.auto_disable.capture_exception") as capture_mock,+ ):+ disable_invalid_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON)++ sub.refresh_from_db()+ assert sub.enabled is False+ send_mock.assert_called_once()+ capture_mock.assert_called_once()diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 194ba1e90021..51cd89924808 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5427,9 +5427,9 @@ snapshots:scenes-app-subscriptions-subscription-summary--insight-many-destinations--light:hash: v1.k794b7964.59ff0d065a88a7f72aff6dca77c0888db8de9af22857a410e57530ce29346882.Hrri0ZKo9ewTXLYX9bnyEgGUN5Xx6tQhQFoWMO2q7mYscenes-app-subscriptions-subscriptionstable--default--dark:- hash: v1.k794b7964.8469e1367634e150f7bc8b6b95e345ad0e045efbb5ed87500477b08bc0903f30.FRKqhIQ09KIxmv0ff9FX_OqdYH1_z1LUOuX0y7qL3Aw+ hash: v1.k794b7964.3163a047c7c1198e10defcd2456a545372bc36197f6952f4e1e08c77f9521e9e.bONzOBqskEpXpIBStM-fOkBY_U1FXVLdc-Gef0Gk9cQscenes-app-subscriptions-subscriptionstable--default--light:- hash: v1.k794b7964.7d56cc77e7f8de3e9426a05cc312d88793c06ad27b4f92621bf611b62ae77311.HEW_ANuoQiXdg3T9xXmsiyi83fx9Wgk1lLVklpK7vIk+ hash: v1.k794b7964.4ddff4e3e1a7220517d18cd3093a359455f65e212cacefceee7ea7f642ba8410.A5wEai5mQdHMkicpZucYr1kfYnvuZ7O8Ds_4FgOVVzUscenes-app-subscriptions-subscriptionstable--with-pagination--dark:hash: v1.k794b7964.3ba31fd1483577c6ef3c0a0a1a2b0298558b78c6bb151212399ecd9e64ef1f67.nEl4q1IQmch73ABvZK7q1OSGzmB5ku2C0DGq96R5NQIscenes-app-subscriptions-subscriptionstable--with-pagination--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 5c0ba1b78e2b..1a8d3fc8a9d5 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -2617,6 +2617,8 @@ export interface SubscriptionApi {readonly created_by: UserBasicApi/** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */deleted?: boolean+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean/*** Human-readable name for this subscription.* @maxLength 100@@ -2723,6 +2725,8 @@ export interface PatchedSubscriptionApi {readonly created_by?: UserBasicApi/** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */deleted?: boolean+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean/*** Human-readable name for this subscription.* @maxLength 100diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex b4f0cceff929..42715821dece 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -2614,6 +2614,12 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.nullish().describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'+ ),title: zod.string().max(subscriptionsCreateBodyTitleMax)@@ -2714,6 +2720,12 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.nullish().describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'+ ),title: zod.string().max(subscriptionsUpdateBodyTitleMax)@@ -2817,6 +2829,12 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.nullish().describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'+ ),title: zod.string().max(subscriptionsPartialUpdateBodyTitleMax)diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.tsindex ef09a041d9e9..cfadb8acf6e1 100644--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts@@ -35,6 +35,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {bysetpos: 1,dashboard_export_insights: [],integration_id: null,+ enabled: true,summary_enabled: false,summary_prompt_guide: '',}@@ -102,7 +103,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([forms(({ props, actions }) => ({subscription: {- defaults: {} as unknown as SubscriptionType,+ defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,errors: ({frequency,interval,diff --git a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.tsindex 7b0c597999c6..abba8a849eee 100644--- a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts+++ b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts@@ -9,6 +9,7 @@ import { SubscriptionType } from '~/types'import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'import type { subscriptionsLogicType } from './subscriptionsLogicType'+import { toggleSubscriptionEnabled } from './toggleSubscriptionEnabled'import { SubscriptionBaseProps } from './utils'export const subscriptionsLogic = kea<subscriptionsLogicType>([@@ -22,6 +23,9 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([deliverSubscription: (id: number) => ({ id }),deliverSubscriptionSuccess: true,deliverSubscriptionFailure: true,+ setSubscriptionEnabled: (id: number, enabled: boolean) => ({ id, enabled }),+ setSubscriptionEnabledSuccess: true,+ setSubscriptionEnabledFailure: true,}),loaders(({ props }) => ({@@ -57,6 +61,14 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([deliverSubscriptionFailure: () => null,},],+ togglingEnabledId: [+ null as number | null,+ {+ setSubscriptionEnabled: (_, { id }) => id,+ setSubscriptionEnabledSuccess: () => null,+ setSubscriptionEnabledFailure: () => null,+ },+ ],}),listeners(({ actions }) => ({@@ -75,6 +87,15 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([actions.deliverSubscriptionFailure()}},+ setSubscriptionEnabled: async ({ id, enabled }) => {+ const ok = await toggleSubscriptionEnabled(id, enabled)+ if (ok) {+ actions.setSubscriptionEnabledSuccess()+ } else {+ actions.setSubscriptionEnabledFailure()+ }+ },+ setSubscriptionEnabledSuccess: () => actions.loadSubscriptions(),})),afterMount(({ actions }) => actions.loadSubscriptions()),diff --git a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.tsnew file mode 100644index 000000000000..f74fe5864e1e--- /dev/null+++ b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts@@ -0,0 +1,74 @@+import { lemonToast } from 'lib/lemon-ui/LemonToast'++import * as generatedApi from '~/generated/core/api'++import { toggleSubscriptionEnabled } from './toggleSubscriptionEnabled'++jest.mock('lib/utils/getAppContext', () => ({+ getCurrentTeamId: () => 1,+}))++describe('toggleSubscriptionEnabled', () => {+ let patchSpy: jest.SpyInstance+ let successSpy: jest.SpyInstance+ let errorSpy: jest.SpyInstance++ beforeEach(() => {+ patchSpy = jest.spyOn(generatedApi, 'subscriptionsPartialUpdate')+ successSpy = jest.spyOn(lemonToast, 'success').mockImplementation(jest.fn())+ errorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('returns true and surfaces an enabled toast on success', async () => {+ patchSpy.mockResolvedValueOnce({ id: 42, enabled: true } as any)++ const ok = await toggleSubscriptionEnabled(42, true)++ expect(ok).toBe(true)+ expect(patchSpy).toHaveBeenCalledWith('1', 42, { enabled: true })+ expect(successSpy).toHaveBeenCalledWith('Subscription enabled')+ expect(errorSpy).not.toHaveBeenCalled()+ })++ it('returns true and surfaces a disabled toast on success', async () => {+ patchSpy.mockResolvedValueOnce({ id: 42, enabled: false } as any)++ const ok = await toggleSubscriptionEnabled(42, false)++ expect(ok).toBe(true)+ expect(successSpy).toHaveBeenCalledWith('Subscription disabled')+ })++ it('returns false and surfaces the API detail on error', async () => {+ patchSpy.mockRejectedValueOnce({ detail: 'Slack integration disconnected' })++ const ok = await toggleSubscriptionEnabled(42, true)++ expect(ok).toBe(false)+ expect(errorSpy).toHaveBeenCalledWith('Slack integration disconnected')+ expect(successSpy).not.toHaveBeenCalled()+ })++ it('returns false and uses the fallback toast when error has no detail', async () => {+ patchSpy.mockRejectedValueOnce(new Error('network down'))++ const ok = await toggleSubscriptionEnabled(42, true)++ expect(ok).toBe(false)+ expect(errorSpy).toHaveBeenCalledWith('Could not update subscription')+ })++ it('treats non-string detail as missing and uses the fallback toast', async () => {+ // Defends against API drift where `detail` becomes an object/array/null.+ patchSpy.mockRejectedValueOnce({ detail: { enabled: ['Schedule has reached its end date.'] } })++ const ok = await toggleSubscriptionEnabled(42, true)++ expect(ok).toBe(false)+ expect(errorSpy).toHaveBeenCalledWith('Could not update subscription')+ })+})diff --git a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.tsnew file mode 100644index 000000000000..68c664c00d23--- /dev/null+++ b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts@@ -0,0 +1,16 @@+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { getCurrentTeamId } from 'lib/utils/getAppContext'++import { subscriptionsPartialUpdate } from '~/generated/core/api'++export async function toggleSubscriptionEnabled(id: number, enabled: boolean): Promise<boolean> {+ try {+ await subscriptionsPartialUpdate(String(getCurrentTeamId()), id, { enabled })+ lemonToast.success(enabled ? 'Subscription enabled' : 'Subscription disabled')+ return true+ } catch (e: any) {+ const detail = typeof e?.detail === 'string' ? e.detail : null+ lemonToast.error(detail ?? 'Could not update subscription')+ return false+ }+}diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsxindex a8163b15bd20..5700cd0f64a8 100644--- a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { IconChevronLeft } from '@posthog/icons'-import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'+import { LemonCheckbox, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { FlaggedFeature } from 'lib/components/FlaggedFeature'@@ -174,9 +174,21 @@ export function EditSubscription({</LemonBanner>)}- <LemonField name="title" label="Name">- <LemonInput placeholder="e.g. Weekly team report" />- </LemonField>+ <div className="flex gap-4 items-end">+ <LemonField className="flex-auto" name="title" label="Name">+ <LemonInput placeholder="e.g. Weekly team report" />+ </LemonField>+ <LemonField name="enabled" className="pb-2">+ {({ value, onChange }) => (+ <LemonCheckbox+ checked={value !== false}+ onChange={onChange}+ data-attr="subscription-enabled"+ label="Enabled"+ />+ )}+ </LemonField>+ </div>{dashboard?.tiles && selectionReady && (<LemonField name="dashboard_export_insights" label="Insights to include">diff --git a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsxindex 8f8e6ac1d439..de097eb8b052 100644--- a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx+++ b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'import { IconEllipsis } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { IconSlack } from 'lib/lemon-ui/icons'@@ -10,6 +11,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture'import { Spinner } from 'lib/lemon-ui/Spinner'import { capitalizeFirstLetter, pluralize } from 'lib/utils'+import { isSubscriptionEnabled } from 'scenes/subscriptions/components/SubscriptionsTable'import { SubscriptionType } from '~/types'@@ -21,7 +23,9 @@ interface SubscriptionListItemProps {onClick: () => voidonDelete?: () => voidonDeliver?: () => void+ onToggleEnabled?: (enabled: boolean) => voidisDelivering?: boolean+ isToggling?: boolean}export function SubscriptionListItem({@@ -29,9 +33,13 @@ export function SubscriptionListItem({onClick,onDelete,onDeliver,+ onToggleEnabled,isDelivering,+ isToggling,}: SubscriptionListItemProps): JSX.Element {const selectedInsightsCount = subscription.dashboard_export_insights?.length+ const enabled = isSubscriptionEnabled(subscription)+ const sideActionBusy = isDelivering || isTogglingreturn (<LemonButton@@ -40,12 +48,22 @@ export function SubscriptionListItem({data-attr="subscription-list-item"fullWidthsideAction={{- icon: isDelivering ? <Spinner /> : <IconEllipsis />,- disabled: isDelivering,+ icon: sideActionBusy ? <Spinner /> : <IconEllipsis />,+ disabled: sideActionBusy,dropdown: {overlay: (<>- {onDeliver && (+ {onToggleEnabled && (+ <LemonButton+ onClick={() => onToggleEnabled(!enabled)}+ data-attr="subscription-list-item-toggle-enabled"+ fullWidth+ disabled={isToggling}+ >+ {enabled ? 'Disable subscription' : 'Enable subscription'}+ </LemonButton>+ )}+ {onDeliver && enabled && (<LemonButtononClick={onDeliver}data-attr="subscription-list-item-manual-deliver"@@ -72,14 +90,18 @@ export function SubscriptionListItem({><div className="flex justify-between flex-auto items-center p-2"><div>- <div className="text-link font-medium">{subscription.title}</div>+ <div className={`font-medium ${enabled ? 'text-link' : 'text-muted'}`}>{subscription.title}</div><div className="text-sm text-text-3000">{capitalizeFirstLetter(subscription.summary)}{selectedInsightsCount? ` · ${pluralize(selectedInsightsCount, 'insight', 'insights', true)}`: null}</div>- {subscription.next_delivery_date ? (+ {!enabled ? (+ <LemonTag type="danger" size="small" className="mt-1">+ Disabled+ </LemonTag>+ ) : subscription.next_delivery_date ? (<div className="text-xs text-secondary">Next delivery: {dayjs(subscription.next_delivery_date).format('ddd, MMM D [at] HH:mm')}</div>@@ -113,8 +135,8 @@ export function ManageSubscriptions({dashboardId,})- const { subscriptions, subscriptionsLoading, deliveringSubscriptionId } = useValues(logic)- const { deleteSubscription, deliverSubscription } = useActions(logic)+ const { subscriptions, subscriptionsLoading, deliveringSubscriptionId, togglingEnabledId } = useValues(logic)+ const { deleteSubscription, deliverSubscription, setSubscriptionEnabled } = useActions(logic)const subscriptionResourceNoun = !insightShortId && dashboardId ? 'dashboard' : 'insight'@@ -132,8 +154,7 @@ export function ManageSubscriptions({) : subscriptions.length ? (<div className="deprecated-space-y-2"><div>- <strong>{subscriptions?.length}</strong>- {' active '}+ <strong>{subscriptions?.length}</strong>{' '}{pluralize(subscriptions.length || 0, 'subscription', 'subscriptions', false)}</div>@@ -145,7 +166,9 @@ export function ManageSubscriptions({onClick={() => onSelect(sub.id)}onDelete={() => deleteSubscription(sub.id)}onDeliver={() => deliverSubscription(sub.id)}+ onToggleEnabled={(enabled) => setSubscriptionEnabled(sub.id, enabled)}isDelivering={deliveringSubscriptionId === sub.id}+ isToggling={togglingEnabledId === sub.id}/>))}</div>diff --git a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionScene.tsxindex c3254d320310..2b63fdac5b40 100644--- a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx+++ b/frontend/src/scenes/subscriptions/SubscriptionScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'@@ -18,7 +18,7 @@ import { AvailableFeature } from '~/types'import { SubscriptionDeliveryHistory } from './components/SubscriptionDeliveryHistory'import { SubscriptionsLoadingSkeleton } from './components/SubscriptionsLoadingSkeleton'-import { subscriptionEditHref, subscriptionName } from './components/SubscriptionsTable'+import { isSubscriptionEnabled, subscriptionEditHref, subscriptionName } from './components/SubscriptionsTable'import { SubscriptionSummary } from './components/SubscriptionSummary'import { subscriptionSceneLogic } from './subscriptionSceneLogic'import { subscriptionsSceneLogic } from './subscriptionsSceneLogic'@@ -26,8 +26,11 @@ import { subscriptionsSceneLogic } from './subscriptionsSceneLogic'function SubscriptionDetailActions({ sub, tabId }: { sub: SubscriptionApi; tabId?: string }): JSX.Element {const { push } = useActions(router)const { activeTabId } = useValues(sceneLogic)+ const { setEnabled } = useActions(subscriptionSceneLogic)+ const { subscriptionLoading } = useValues(subscriptionSceneLogic)const listTabId = tabId ?? activeTabId ?? undefinedconst editHref = subscriptionEditHref(sub)+ const enabled = isSubscriptionEnabled(sub)const deleteSubscription = (): void => {const name = subscriptionName(sub)@@ -48,6 +51,17 @@ function SubscriptionDetailActions({ sub, tabId }: { sub: SubscriptionApi; tabIdreturn (<div className="flex flex-wrap items-center gap-2">+ <LemonTag type={enabled ? 'success' : 'danger'} data-attr="subscription-status-tag">+ {enabled ? 'Enabled' : 'Disabled'}+ </LemonTag>+ <LemonButton+ type="secondary"+ onClick={() => setEnabled({ enabled: !enabled })}+ loading={subscriptionLoading}+ data-attr="subscription-toggle-enabled"+ >+ {enabled ? 'Disable subscription' : 'Enable subscription'}+ </LemonButton>{editHref ? (<LemonButton type="secondary" onClick={() => push(editHref)}>Edit subscription@@ -108,7 +122,13 @@ export function SubscriptionScene({ tabId }: SceneProps): JSX.Element {) : undefined}/>- {subscription ? <SubscriptionSummary sub={subscription} /> : null}+ {subscription ? (+ // Mute the body when the subscription is paused — the LemonTag in the+ // header is the explicit signal; this is the at-a-glance reinforcement.+ <div className={isSubscriptionEnabled(subscription) ? '' : 'opacity-60'}>+ <SubscriptionSummary sub={subscription} />+ </div>+ ) : null}{deliveriesEnabled ? (<SubscriptionDeliveryHistorydeliveriesPage={deliveriesPage}diff --git a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsxindex 50ff7c2cd43c..a167de7e746d 100644--- a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx+++ b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx@@ -23,15 +23,23 @@ import { AvailableFeature } from '~/types'import { SubscriptionsFiltersBar } from './components/SubscriptionsFiltersBar'import { SubscriptionsLoadingSkeleton } from './components/SubscriptionsLoadingSkeleton'-import { SubscriptionsTable, subscriptionEditHref, subscriptionName } from './components/SubscriptionsTable'+import {+ SubscriptionsTable,+ isSubscriptionEnabled,+ subscriptionEditHref,+ subscriptionName,+} from './components/SubscriptionsTable'import { SubscriptionsTab, subscriptionsSceneLogic } from './subscriptionsSceneLogic'function SubscriptionsRowActions({ sub }: { sub: SubscriptionApi }): JSX.Element {const { push } = useActions(router)- const { deleteSubscriptionSuccess, deliverSubscription } = useActions(subscriptionsSceneLogic)- const { deliveringSubscriptionId } = useValues(subscriptionsSceneLogic)+ const { deleteSubscriptionSuccess, deliverSubscription, setSubscriptionEnabled } =+ useActions(subscriptionsSceneLogic)+ const { deliveringSubscriptionId, togglingEnabledId } = useValues(subscriptionsSceneLogic)const href = subscriptionEditHref(sub)const isDelivering = deliveringSubscriptionId === sub.id+ const isToggling = togglingEnabledId === sub.id+ const enabled = isSubscriptionEnabled(sub)return (<LemonMenu@@ -45,11 +53,21 @@ function SubscriptionsRowActions({ sub }: { sub: SubscriptionApi }): JSX.Element]: []),{- label: 'Test delivery',- 'data-attr': 'subscription-list-item-manual-deliver',- disabledReason: isDelivering ? 'Sending test delivery…' : null,- onClick: () => deliverSubscription(sub.id),+ label: enabled ? 'Disable subscription' : 'Enable subscription',+ 'data-attr': 'subscription-list-item-toggle-enabled',+ disabledReason: isToggling ? 'Updating…' : null,+ onClick: () => setSubscriptionEnabled(sub.id, !enabled),},+ ...(enabled+ ? [+ {+ label: 'Test delivery',+ 'data-attr': 'subscription-list-item-manual-deliver',+ disabledReason: isDelivering ? 'Sending test delivery…' : null,+ onClick: () => deliverSubscription(sub.id),+ },+ ]+ : []),{label: 'Delete',status: 'danger' as const,@@ -66,10 +84,10 @@ function SubscriptionsRowActions({ sub }: { sub: SubscriptionApi }): JSX.Element]}><LemonButton- icon={isDelivering ? <Spinner /> : <IconEllipsis />}+ icon={isDelivering || isToggling ? <Spinner /> : <IconEllipsis />}size="small"aria-label="Subscription actions"- disabled={isDelivering}+ disabled={isDelivering || isToggling}/></LemonMenu>)diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsxindex 3dd17b40d82a..7f1dcce14a44 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx@@ -39,6 +39,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [summary: 'sent every week',next_delivery_date: '2026-04-07T17:00:00Z',deleted: false,+ enabled: true,},{id: 2,@@ -58,6 +59,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [summary: 'sent every day',next_delivery_date: '2026-04-08T09:00:00Z',deleted: false,+ enabled: true,integration_id: 1,},{@@ -78,6 +80,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [summary: 'sent every month',next_delivery_date: null,deleted: false,+ enabled: true,},{id: 4,@@ -97,6 +100,28 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [summary: 'sent every week',next_delivery_date: '2026-04-14T12:00:00Z',deleted: false,+ enabled: true,+ },+ {+ id: 5,+ insight: 105,+ dashboard: null,+ insight_short_id: 'disabled-insight',+ resource_name: 'Activation funnel',+ title: 'Auto-paused after integration broke',+ dashboard_export_insights: [],+ target_type: TargetTypeEnumApi.Slack,+ target_value: 'C99999|#archived-channel',+ frequency: SubscriptionFrequencyEnumApi.Weekly,+ interval: 1,+ start_date: '2022-01-01T00:00:00Z',+ created_at: '2023-04-27T10:04:37.977401Z',+ created_by: MOCK_USER,+ summary: 'sent every week',+ next_delivery_date: null,+ deleted: false,+ enabled: false,+ integration_id: 1,},]@@ -135,6 +160,7 @@ function buildMockSubscriptions(total: number): SubscriptionApi[] {summary: 'sent every week',next_delivery_date: '2026-04-07T17:00:00Z',deleted: false,+ enabled: true,...(isSlack ? { integration_id: 1 } : {}),}})diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsxindex 2115ed0e21dd..625419a64b8e 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx@@ -1,4 +1,4 @@-import { LemonTable, LemonTableColumn, LemonTableColumns, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonTable, LemonTableColumn, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import type { PaginationManual, Sorting } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'@@ -20,6 +20,10 @@ export function subscriptionName(sub: SubscriptionApi): string {return sub.title?.trim() || sub.resource_name?.trim() || 'Untitled subscription'}+export function isSubscriptionEnabled(sub: { enabled?: boolean | null }): boolean {+ return sub.enabled !== false+}+export function subscriptionEditHref(sub: SubscriptionApi): string | null {if (sub.insight && sub.insight_short_id) {return urls.insightSubcription(sub.insight_short_id as InsightShortId, String(sub.id))@@ -94,7 +98,7 @@ function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element):<div className="min-w-0 w-full overflow-hidden"><Linkto={urls.subscription(sub.id)}- className="font-medium block truncate"+ className={`font-medium block truncate ${isSubscriptionEnabled(sub) ? '' : 'text-muted'}`}data-attr="subscription-name-link">{name}@@ -185,6 +189,17 @@ function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element):>),sorter: true,},+ {+ title: 'Status',+ key: 'enabled',+ dataIndex: 'enabled',+ render: (_value: unknown, sub: SubscriptionApi) =>+ isSubscriptionEnabled(sub) ? (+ <LemonTag type="success">Enabled</LemonTag>+ ) : (+ <LemonTag type="danger">Disabled</LemonTag>+ ),+ },{width: 56,align: 'right',diff --git a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.tsindex ef358be87ac9..46316aaa4f1b 100644--- a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts+++ b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts@@ -33,6 +33,7 @@ export const MOCK_SUBSCRIPTION_INSIGHT: SubscriptionApi = {summary: 'sent every week',next_delivery_date: '2026-04-07T17:00:00Z',deleted: false,+ enabled: true,}/** Insight subscription with several email recipients so Resource shows the type label, not the long name. */@@ -62,6 +63,7 @@ export const MOCK_SUBSCRIPTION_DASHBOARD: SubscriptionApi = {summary: 'sent every day',next_delivery_date: '2026-04-08T09:00:00Z',deleted: false,+ enabled: true,integration_id: 1,}diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsxindex 3fd347a9ca87..c6cd5f026175 100644--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx@@ -13,6 +13,7 @@ import { urls } from 'scenes/urls'import {subscriptionsDeliveriesList,+ subscriptionsPartialUpdate,subscriptionsRetrieve,subscriptionsTestDeliveryCreate,} from '~/generated/core/api'@@ -84,6 +85,16 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([}return await subscriptionsRetrieve(String(getCurrentTeamId()), numericId)},+ // Used by the Pause / Resume button on the detail page. PATCH+ // returns the updated subscription so the loader replaces the+ // whole value — no extra GET needed.+ setEnabled: async ({ enabled }: { enabled: boolean }) => {+ const numericId = parseInt(props.id, 10)+ if (!Number.isFinite(numericId)) {+ return values.subscription+ }+ return await subscriptionsPartialUpdate(String(getCurrentTeamId()), numericId, { enabled })+ },},],deliveriesPage: [@@ -195,6 +206,18 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([: 'Could not load delivery history.'lemonToast.error(message)},+ setEnabledSuccess: ({ subscription }) => {+ if (!subscription) {+ return+ }+ lemonToast.success(subscription.enabled ? 'Subscription enabled' : 'Subscription disabled')+ },+ setEnabledFailure: ({ errorObject }) => {+ // Surface the serializer's actionable message (e.g. re-enabling a Slack+ // sub with no integration) — backend already validates this.+ const detail = errorObject?.detail+ lemonToast.error(typeof detail === 'string' ? detail : 'Could not update subscription')+ },})),afterMount(({ actions }) => {void actions.loadSubscription()diff --git a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsxindex e59677b9fb03..96a4abf51e0a 100644--- a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx+++ b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx@@ -5,6 +5,7 @@ import { router } from 'kea-router'import { Sorting } from '@posthog/lemon-ui'import { runSubscriptionTestDelivery } from 'lib/components/Subscriptions/runSubscriptionTestDelivery'+import { toggleSubscriptionEnabled } from 'lib/components/Subscriptions/toggleSubscriptionEnabled'import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'@@ -209,6 +210,9 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([deliverSubscription: (id: number) => ({ id }),deliverSubscriptionSuccess: true,deliverSubscriptionFailure: true,+ setSubscriptionEnabled: (id: number, enabled: boolean) => ({ id, enabled }),+ setSubscriptionEnabledSuccess: true,+ setSubscriptionEnabledFailure: true,}),reducers({search: [@@ -280,6 +284,16 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([deliverSubscriptionFailure: () => null,},],+ // Tracks the subscription whose Pause/Resume PATCH is in flight so the row's+ // menu item can show a busy state and prevent double-clicks.+ togglingEnabledId: [+ null as number | null,+ {+ setSubscriptionEnabled: (_, { id }) => id,+ setSubscriptionEnabledSuccess: () => null,+ setSubscriptionEnabledFailure: () => null,+ },+ ],}),loaders(({ values }) => ({subscriptionsResponse: [@@ -372,6 +386,15 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([actions.deliverSubscriptionFailure()}},+ setSubscriptionEnabled: async ({ id, enabled }) => {+ const ok = await toggleSubscriptionEnabled(id, enabled)+ if (ok) {+ actions.setSubscriptionEnabledSuccess()+ } else {+ actions.setSubscriptionEnabledFailure()+ }+ },+ setSubscriptionEnabledSuccess: () => actions.loadSubscriptions(),})),tabAwareActionToUrl(({ values }) => {const syncUrl = (diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 4d86b360f035..ed055b9d417e 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5026,6 +5026,9 @@ export enum ValueOptionType {export type WeekdayType = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday'+// TODO: migrate to SubscriptionApi from frontend/src/generated/core/api.schemas.ts.+// This hand-written interface predates the generated type and now requires+// dual-maintenance for every backend field change.export interface SubscriptionType {id: numberinsight?: number@@ -5048,6 +5051,7 @@ export interface SubscriptionType {created_by?: UserBasicType | nullcreated_at: stringdeleted?: boolean+ enabled?: booleansummary_enabled?: booleansummary_prompt_guide?: string}diff --git a/posthog/migrations/1146_subscription_enabled.py b/posthog/migrations/1146_subscription_enabled.pynew file mode 100644index 000000000000..8f3d18093404--- /dev/null+++ b/posthog/migrations/1146_subscription_enabled.py@@ -0,0 +1,13 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1145_alter_integration_kind")]++ operations = [+ migrations.AddField(+ model_name="subscription",+ name="enabled",+ field=models.BooleanField(default=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex bd25447b4dbe..5f649ddf0d57 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1145_alter_integration_kind+1146_subscription_enableddiff --git a/posthog/models/subscription.py b/posthog/models/subscription.pyindex 277fca915322..e744f24ad20c 100644--- a/posthog/models/subscription.py+++ b/posthog/models/subscription.py@@ -1,5 +1,5 @@from dataclasses import dataclass-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Any, Literal, Optional, castfrom django.contrib.postgres.fields import ArrayField@@ -67,6 +67,13 @@ class Subscription(models.Model):RRULE_FIELDS = {"frequency", "count", "interval", "start_date", "until_date", "bysetpos", "byweekday"}+ _FREQ_MAP: dict[str, int] = {+ SubscriptionFrequency.DAILY: DAILY,+ SubscriptionFrequency.WEEKLY: WEEKLY,+ SubscriptionFrequency.MONTHLY: MONTHLY,+ SubscriptionFrequency.YEARLY: YEARLY,+ }+# Relations - i.e. WHAT are we exporting?team = models.ForeignKey("Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)@@ -111,6 +118,10 @@ class Subscription(models.Model):created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)deleted = models.BooleanField(default=False)+ # False when paused or auto-disabled because the delivery prerequisite is+ # permanently invalid (e.g. Slack integration disconnected).+ enabled = models.BooleanField(default=True)+summary_enabled = models.BooleanField(default=False)summary_prompt_guide = models.CharField(max_length=500, blank=True, default="")@@ -137,31 +148,57 @@ class Subscription(models.Model):kwargs["update_fields"].append("next_delivery_date")super().save(*args, **kwargs)- @property- def rrule(self):- freq_map: dict[str, int] = {- self.SubscriptionFrequency.DAILY: DAILY,- self.SubscriptionFrequency.WEEKLY: WEEKLY,- self.SubscriptionFrequency.MONTHLY: MONTHLY,- self.SubscriptionFrequency.YEARLY: YEARLY,- }- freq = cast(Literal[0, 1, 2, 3, 4, 5, 6], freq_map[self.frequency])+ @staticmethod+ def _build_rrule(+ *,+ frequency: str,+ start_date: Any,+ count: Any = None,+ interval: Any = None,+ until_date: Any = None,+ bysetpos: Any = None,+ byweekday: Any = None,+ ) -> rrule:+ freq = cast(Literal[0, 1, 2, 3, 4, 5, 6], Subscription._FREQ_MAP[frequency])return rrule(freq=freq,- count=self.count,- interval=self.interval,- dtstart=self.start_date,- until=self.until_date,- bysetpos=self.bysetpos if self.byweekday else None,- byweekday=to_rrule_weekdays(self.byweekday) if self.byweekday else None,+ count=count,+ interval=interval,+ dtstart=start_date,+ until=until_date,+ bysetpos=bysetpos if byweekday else None,+ byweekday=to_rrule_weekdays(byweekday) if byweekday else None,)- def set_next_delivery_date(self, from_dt=None):+ @staticmethod+ def _compute_next_delivery_date(*, from_dt: Optional[datetime] = None, **rrule_fields: Any) -> Optional[datetime]:+ # Buffer of 15 minutes since we might run a bit early — never schedule into the past.+ now = timezone.now() + timedelta(minutes=15)+ return Subscription._build_rrule(**rrule_fields).after(dt=max(from_dt or now, now), inc=False)++ @property+ def rrule(self) -> rrule:+ return self._build_rrule(**{f: getattr(self, f) for f in self.RRULE_FIELDS})++ def set_next_delivery_date(self, from_dt: Optional[datetime] = None) -> None:# Authoritative schedule — a client-side preview mirror lives in- # frontend/src/lib/components/Subscriptions/utils.tsx (getNextDeliveryDate)- # We never want next_delivery_date to be in the past- now = timezone.now() + timedelta(minutes=15) # Buffer of 15 minutes since we might run a bit early- self.next_delivery_date = self.rrule.after(dt=max(from_dt or now, now), inc=False)+ # frontend/src/lib/components/Subscriptions/utils.tsx (getNextDeliveryDate).+ self.next_delivery_date = self._compute_next_delivery_date(+ from_dt=from_dt, **{f: getattr(self, f) for f in self.RRULE_FIELDS}+ )++ @classmethod+ def project_next_delivery_date(+ cls, instance: Optional["Subscription"] = None, **overrides: Any+ ) -> Optional[datetime]:+ """What `next_delivery_date` would be for the rrule defined by `instance` fields+ (when given) layered with `overrides`, without persisting. Returns None on an+ exhausted rrule. Pass `instance` for PATCH validation, omit it for creates."""+ base = {f: getattr(instance, f) for f in cls.RRULE_FIELDS} if instance is not None else {}+ merged = {**base, **{k: v for k, v in overrides.items() if k in cls.RRULE_FIELDS}}+ if "frequency" not in merged or "start_date" not in merged:+ return None # DRF field validation should reject before we get here.+ return cls._compute_next_delivery_date(**merged)@propertydef url(self):diff --git a/posthog/templates/email/subscription_disabled.html b/posthog/templates/email/subscription_disabled.htmlnew file mode 100644index 000000000000..edfe8be98052--- /dev/null+++ b/posthog/templates/email/subscription_disabled.html@@ -0,0 +1,15 @@+{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %} {% block section %}+ <p>+ Your subscription <strong>{{ subscription_title }}</strong> has been+ <strong>automatically disabled</strong> because:+ </p>+ <p><i>{{ reason }}</i></p>+ <p>+ To resume delivery, fix the issue above and re-enable the subscription.+ </p>+ {% if subscription_url %}+ <div class="mb mt text-center">+ <a class="button" href="{% absolute_uri subscription_url %}">Manage subscription</a>+ </div>+ {% endif %}+{% endblock %}diff --git a/posthog/temporal/subscriptions/__init__.py b/posthog/temporal/subscriptions/__init__.pyindex de559dab85f9..4e6fa30bc1ec 100644--- a/posthog/temporal/subscriptions/__init__.py+++ b/posthog/temporal/subscriptions/__init__.py@@ -5,6 +5,7 @@ from posthog.temporal.subscriptions.activities import (deliver_subscription,fetch_due_subscriptions_activity,update_delivery_record,+ validate_subscription_for_delivery,)from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insightsfrom posthog.temporal.subscriptions.workflows import (@@ -17,6 +18,7 @@ WORKFLOWS = [ScheduleAllSubscriptionsWorkflow, HandleSubscriptionValueChangeWorkACTIVITIES = [fetch_due_subscriptions_activity,+ validate_subscription_for_delivery,create_export_assets,deliver_subscription,advance_next_delivery_date,diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.pyindex 5118cabe0fba..5e46e5d33acd 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/posthog/temporal/subscriptions/activities.py@@ -28,13 +28,21 @@ from posthog.temporal.subscriptions.types import (DeliverSubscriptionResult,FetchDueSubscriptionsActivityInputs,RecipientResult,+ SubscriptionAbortInfo,SubscriptionInfo,UpdateDeliveryRecordInputs,)from products.dashboards.backend.models.dashboard_tile import DashboardTile-from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, SUPPORTED_TARGET_TYPES, _capture_delivery_failed_event+from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_event+from ee.tasks.subscriptions.auto_disable import (+ SLACK_DISCONNECTED_DISABLE_REASON,+ UNSUPPORTED_TARGET_DISABLE_REASON,+ DisableReason,+ disable_invalid_subscription,+ get_subscription_disable_reason,+)from ee.tasks.subscriptions.email_subscriptions import send_email_subscription_reportfrom ee.tasks.subscriptions.slack_subscriptions import (get_slack_integration_for_team,@@ -43,6 +51,10 @@ from ee.tasks.subscriptions.slack_subscriptions import (LOGGER = get_logger(__name__)+# Used only as the recipient_results error message — `no_assets` doesn't auto-disable+# (it indicates a transient resolve failure that retries can recover from).+NO_ASSETS_REASON = "No assets to deliver — likely a transient export pipeline failure; will retry on next schedule"+async def _resolve_target_delivery_id(inputs: CreateExportAssetsInputs) -> uuid.UUID | None:"""Find the SubscriptionDelivery row that create_export_assets should write to.@@ -143,7 +155,7 @@ async def fetch_due_subscriptions_activity(inputs: FetchDueSubscriptionsActivityelse str(sub["team_id"]),next_delivery_date=sub["next_delivery_date"].isoformat() if sub["next_delivery_date"] else None,)- for sub in Subscription.objects.filter(next_delivery_date__lte=now_with_buffer, deleted=False)+ for sub in Subscription.objects.filter(next_delivery_date__lte=now_with_buffer, deleted=False, enabled=True).exclude(dashboard__deleted=True).exclude(insight__deleted=True).values("id", "team_id", "created_by__distinct_id", "next_delivery_date")@@ -155,6 +167,41 @@ async def fetch_due_subscriptions_activity(inputs: FetchDueSubscriptionsActivityreturn subscriptions+async def validate_subscription_for_delivery(subscription_id: int) -> SubscriptionAbortInfo | None:+ """Returns abort info when delivery should not proceed; None to continue."""+ subscription = await database_sync_to_async(+ Subscription.objects.select_related("created_by", "integration").get,+ thread_sensitive=False,+ )(pk=subscription_id)++ # Idempotency: a Temporal redispatch (e.g. worker crash mid-acknowledge) after a+ # prior auto-disable committed must not re-fire side effects.+ if not subscription.enabled:+ await LOGGER.ainfo("validate_subscription.already_disabled_skipping", subscription_id=subscription_id)+ return SubscriptionAbortInfo()++ reason = get_subscription_disable_reason(subscription.target_type, subscription.integration_id)+ if reason is None:+ return None++ LOGGER.warning(+ "validate_subscription.invalid_auto_disabling",+ subscription_id=subscription_id,+ target_type=subscription.target_type,+ reason=reason.key,+ )+ _capture_delivery_failed_event(subscription, Exception(reason.description))+ await database_sync_to_async(disable_invalid_subscription, thread_sensitive=False)(subscription, reason)+ return SubscriptionAbortInfo(+ failed_recipient=RecipientResult(+ recipient=subscription.target_value,+ status="failed",+ error={"message": reason.description, "type": reason.key},+ )+ )++@temporalio.activity.defnasync def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExportAssetsResult:await LOGGER.ainfo(@@ -291,6 +338,27 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExport)+async def _auto_disable_and_return(+ subscription: Subscription,+ reason: DisableReason,+ recipient_results: list[RecipientResult],+) -> DeliverSubscriptionResult:+ """Permanent-failure exit path: record per-recipient failure, capture analytics,+ and auto-disable the subscription."""+ recipient_results.append(+ RecipientResult(+ recipient=subscription.target_value,+ status="failed",+ error={"message": reason.description, "type": reason.key},+ )+ )+ # `_capture_delivery_failed_event` only reads `str(e)` and `type(e).__name__`,+ # so a plain Exception conveys the same info without implying retry semantics.+ _capture_delivery_failed_event(subscription, Exception(reason.description))+ await database_sync_to_async(disable_invalid_subscription, thread_sensitive=False)(subscription, reason)+ return DeliverSubscriptionResult(recipient_results=recipient_results)++@temporalio.activity.defnasync def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubscriptionResult:recipient_results: list[RecipientResult] = []@@ -300,6 +368,14 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsthread_sensitive=False,)(pk=inputs.subscription_id)+ # Activity-retry idempotency: if a previous attempt already auto-disabled this+ # subscription (UPDATE committed) and Temporal redispatched the activity (e.g.+ # worker crash mid-acknowledge), don't re-fire the disable side effects — UUID4+ # campaign keys mean MessagingRecord wouldn't dedup the duplicate email.+ if not subscription.enabled:+ LOGGER.info("deliver_subscription.skipped_disabled", subscription_id=inputs.subscription_id)+ return DeliverSubscriptionResult(recipient_results=[])+await LOGGER.ainfo("deliver_subscription.starting",subscription_id=inputs.subscription_id,@@ -308,13 +384,16 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsis_new=inputs.is_new_subscription_target,)- if subscription.target_type not in SUPPORTED_TARGET_TYPES:+ if (+ get_subscription_disable_reason(subscription.target_type, subscription.integration_id)+ == UNSUPPORTED_TARGET_DISABLE_REASON+ ):LOGGER.warning("deliver_subscription.unsupported_target",subscription_id=inputs.subscription_id,target_type=subscription.target_type,)- return DeliverSubscriptionResult(recipient_results=recipient_results)+ return await _auto_disable_and_return(subscription, UNSUPPORTED_TARGET_DISABLE_REASON, recipient_results)assets_by_id = await database_sync_to_async(lambda: {@@ -329,8 +408,24 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsassets = [assets_by_id[aid] for aid in inputs.exported_asset_ids if aid in assets_by_id]if not assets:+ # Empty here means non-empty exported_asset_ids didn't resolve from DB — a+ # transient condition (TTL sweep, prior export crash, S3 race). Genuine+ # deletion is filtered upstream in create_export_assets and the workflow+ # short-circuits to SKIPPED before this activity runs. Don't auto-disable;+ # the failure is observable via the `subscription_delivery_failed` analytics+ # event and the next scheduled delivery retries.LOGGER.warning("deliver_subscription.no_assets", subscription_id=inputs.subscription_id)- capture_exception(Exception("No assets are in this subscription"), {"subscription_id": inputs.subscription_id})+ recipient_results.append(+ RecipientResult(+ recipient=subscription.target_value,+ status="failed",+ error={"message": NO_ASSETS_REASON, "type": "no_assets"},+ )+ )+ # Plain Exception — `_capture_delivery_failed_event` only reads `str(e)` and+ # `type(e).__name__`, and the activity returns cleanly so retry semantics on+ # ApplicationError would be misleading (matches `_auto_disable_and_return`).+ _capture_delivery_failed_event(subscription, Exception(NO_ASSETS_REASON))return DeliverSubscriptionResult(recipient_results=recipient_results)if subscription.target_type == "email":@@ -414,32 +509,9 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubs"deliver_subscription.no_slack_integration",subscription_id=inputs.subscription_id,)- missing_integration_error = {- "message": "No Slack integration configured",- "type": "missing_integration",- }- recipient_results.append(- RecipientResult(- recipient=subscription.target_value,- status="failed",- error=missing_integration_error,- )- )- # Same shape as ProcessSubscriptionWorkflow success-path serialization so- # update_delivery_record gets per-recipient rows from ActivityError.details.- raise ApplicationError(- "No Slack integration configured for this team",- {- "recipient_results": [- {- "recipient": r.recipient,- "status": r.status,- **({"error": r.error} if r.error else {}),- }- for r in recipient_results- ]- },- non_retryable=True,+ # Slack integration disconnected — auto-disable, mirrors the alert pattern.+ return await _auto_disable_and_return(+ subscription, SLACK_DISCONNECTED_DISABLE_REASON, recipient_results)LOGGER.info("deliver_subscription.sending_slack_message", subscription_id=subscription.id)@@ -590,6 +662,11 @@ async def update_delivery_record(inputs: UpdateDeliveryRecordInputs) -> None:@temporalio.activity.defnasync def advance_next_delivery_date(subscription_id: int) -> None:subscription = await database_sync_to_async(Subscription.objects.get, thread_sensitive=False)(pk=subscription_id)+ # Disabled subs (e.g. auto-disabled this run / paused by user) don't get a+ # future delivery date — avoids showing a misleading "next delivery" in the UI.+ if not subscription.enabled:+ await LOGGER.ainfo("advance_next_delivery_date.skipped_disabled", subscription_id=subscription_id)+ returnsubscription.set_next_delivery_date(subscription.next_delivery_date)await database_sync_to_async(subscription.save, thread_sensitive=False)(update_fields=["next_delivery_date"])await LOGGER.ainfo(diff --git a/posthog/temporal/subscriptions/types.py b/posthog/temporal/subscriptions/types.pyindex c5e9d32e5dd4..dea4cfcff0a5 100644--- a/posthog/temporal/subscriptions/types.py+++ b/posthog/temporal/subscriptions/types.py@@ -143,6 +143,15 @@ class DeliverSubscriptionResult:recipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)+class SubscriptionAbortInfo:+ """Returned by `validate_subscription_for_delivery` when the workflow should abort.+ `failed_recipient` is populated only when this run auto-disabled the sub+ (workflow records FAILED). None means already-disabled — idempotency redispatch."""++ failed_recipient: typing.Optional[RecipientResult] = None++@dataclasses.dataclassclass CreateDeliveryRecordInputs:subscription_id: intdiff --git a/posthog/temporal/subscriptions/workflows.py b/posthog/temporal/subscriptions/workflows.pyindex 788e469ac79e..7fffaad299fb 100644--- a/posthog/temporal/subscriptions/workflows.py+++ b/posthog/temporal/subscriptions/workflows.py@@ -3,6 +3,7 @@ import uuidimport typingimport asyncioimport datetime as dt+import dataclassesimport temporalio.commonimport temporalio.workflow@@ -27,6 +28,7 @@ from posthog.temporal.subscriptions.activities import (deliver_subscription,fetch_due_subscriptions_activity,update_delivery_record,+ validate_subscription_for_delivery,)from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insightsfrom posthog.temporal.subscriptions.types import (@@ -275,6 +277,26 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):),)+ # Validate up-front: if the subscription is already disabled or its target+ # configuration is permanently broken, auto-disable and short-circuit before+ # the export pipeline runs.+ abort_info = await temporalio.workflow.execute_activity(+ validate_subscription_for_delivery,+ inputs.subscription_id,+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=temporalio.common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=5),+ maximum_interval=dt.timedelta(seconds=30),+ maximum_attempts=3,+ ),+ )+ if abort_info is not None:+ # Just-disabled → FAILED with reason. Already-disabled (no failed_recipient) → SKIPPED default.+ if abort_info.failed_recipient is not None:+ delivery_recipient_results = [dataclasses.asdict(abort_info.failed_recipient)]+ final_status = DeliveryStatus.FAILED+ return+# Phase 1: Prepare — create ExportedAssets and persist insight snapshots# onto SubscriptionDelivery.content_snapshot (written from within the# activity to avoid shipping multi-MB query_results across Temporal's@@ -467,7 +489,9 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):if caught_error is None:raise- # Advance schedule — always for scheduled deliveries, even on failure+ # Advance schedule — always for scheduled deliveries, even on failure.+ # The activity itself no-ops when the subscription is disabled, so a+ # just-auto-disabled sub doesn't get a misleading future delivery date.if inputs.trigger_type == SubscriptionTriggerType.SCHEDULED:await temporalio.workflow.execute_activity(advance_next_delivery_date,diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 5df457601349..40302f4f8675 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -25,7 +25,8 @@ from posthog.errors import CHQueryErrorS3Errorfrom posthog.models.exported_asset import ExportedAssetfrom posthog.models.insight import Insightfrom posthog.models.instance_setting import set_instance_setting-from posthog.models.subscription import SubscriptionDelivery+from posthog.models.integration import Integration+from posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.tasks.exports.failure_handler import ExcelColumnLimitExceededfrom posthog.temporal.common.slo_interceptor import SloInterceptor@@ -37,6 +38,7 @@ from posthog.temporal.subscriptions.activities import (deliver_subscription,fetch_due_subscriptions_activity,update_delivery_record,+ validate_subscription_for_delivery,)from posthog.temporal.subscriptions.types import (CreateDeliveryRecordInputs,@@ -44,6 +46,7 @@ from posthog.temporal.subscriptions.types import (CreateExportAssetsResult,DeliverSubscriptionInputs,DeliveryStatus,+ FetchDueSubscriptionsActivityInputs,ProcessSubscriptionWorkflowInputs,ScheduleAllSubscriptionsWorkflowInputs,SubscriptionTriggerType,@@ -69,6 +72,7 @@ SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast([fetch_due_subscriptions_activity,create_delivery_record,+ validate_subscription_for_delivery,create_export_assets,export_asset_activity,deliver_subscription,@@ -81,6 +85,7 @@ SUBSCRIPTION_PROCESS_ACTIVITIES: Sequence[Callable[..., Any]] = cast(Sequence[Callable[..., Any]],[create_delivery_record,+ validate_subscription_for_delivery,create_export_assets,export_asset_activity,deliver_subscription,@@ -347,6 +352,11 @@ async def test_deliver_subscription_report_slack()insight = await sync_to_async(Insight.objects.create)(team=team, short_id="abc999", name="Insight")+ integration = await sync_to_async(Integration.objects.create)(+ team=team,+ kind="slack",+ config={"team": {"id": "T123", "name": "Test"}},+ )subscription = await sync_to_async(create_subscription)(team=team,@@ -354,6 +364,7 @@ async def test_deliver_subscription_report_slack(created_by=user,target_type="slack",target_value="C12345|#test-channel",+ integration_id=integration.id,)def fake_export(asset_obj, **kwargs):@@ -387,6 +398,7 @@ async def test_deliver_subscription_report_slack(assert mock_send_slack_async.await_count == 1+@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)@freeze_time("2022-02-02T08:55:00.000Z")@@ -394,6 +406,7 @@ async def test_deliver_subscription_report_slack(async def test_process_subscription_records_missing_slack_integration_failure(mock_get_slack: MagicMock,mock_build_snapshot: MagicMock,+ mock_send_notification: MagicMock,temporal_client: Client,team,user,@@ -422,42 +435,280 @@ async def test_process_subscription_records_missing_slack_integration_failure(content_location="s3://bucket/slack-fail.png",)- with pytest.raises(Exception):- async with await WorkflowEnvironment.start_time_skipping() as env:- async with Worker(- env.client,+ # Missing Slack integration_id is caught by the workflow's validation step+ # which auto-disables before the export pipeline runs. The team-fallback in+ # `deliver_subscription` is no longer reachable for this scenario.+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ workflows=[ProcessSubscriptionWorkflow],+ activities=SUBSCRIPTION_PROCESS_ACTIVITIES,+ interceptors=[SloInterceptor()],+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=10),+ debug_mode=True,+ ):+ await env.client.execute_workflow(+ ProcessSubscriptionWorkflow.run,+ TrackedSubscriptionInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ ),+ id=str(uuid.uuid4()),task_queue=settings.TEMPORAL_TASK_QUEUE,- workflows=[ProcessSubscriptionWorkflow],- activities=SUBSCRIPTION_PROCESS_ACTIVITIES,- interceptors=[SloInterceptor()],- workflow_runner=UnsandboxedWorkflowRunner(),- activity_executor=ThreadPoolExecutor(max_workers=10),- debug_mode=True,- ):- await env.client.execute_workflow(- ProcessSubscriptionWorkflow.run,- TrackedSubscriptionInputs(- subscription_id=subscription.id,- team_id=subscription.team_id,- distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]- ),- id=str(uuid.uuid4()),- task_queue=settings.TEMPORAL_TASK_QUEUE,- )+ )row = await sync_to_async(SubscriptionDelivery.objects.filter(subscription_id=subscription.id).latest)("created_at")+ # Validate auto-disabled the sub: row is FAILED with the disable reason in+ # recipient_results so support/debugging can read the failure detail directly.assert row.status == SubscriptionDelivery.Status.FAILEDassert row.recipient_results == [{"recipient": "C12345|#test-channel","status": "failed","error": {- "message": "No Slack integration configured",+ "message": "Slack integration disconnected","type": "missing_integration",},}]- mock_get_slack.assert_called_once_with(subscription.team_id)+ mock_get_slack.assert_not_called()++ # Subscription is auto-disabled and owner is notified.+ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False+ mock_send_notification.assert_called_once()+++ "case_label, target_type, target_value, expected_error",+ [+ (+ "missing_slack_integration",+ "slack",+ "C12345|#test-channel",+ {"message": "Slack integration disconnected", "type": "missing_integration"},+ ),+ (+ "unsupported_target",+ "webhook",+ "https://example.com/hook",+ {"message": "Unsupported delivery channel", "type": "unsupported_target"},+ ),+ ],+)+async def test_deliver_subscription_auto_disables_invalid_subscriptions(+ team, user, case_label, target_type, target_value, expected_error+):+ """Activity-level auto-disable for permanently-broken targets. `no_assets` is+ deliberately excluded — empty-assets-at-delivery is transient (the workflow short-+ circuits to SKIPPED before `deliver_subscription` runs when assets are genuinely+ deleted). See test_no_assets_does_not_auto_disable.+ """+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id=f"dis-{case_label[:5]}", name=case_label)+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ insight=insight,+ export_format="image/png",+ content_location=f"s3://bucket/{case_label}.png",+ )+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type=target_type,+ target_value=target_value,+ enabled=True,+ )++ env = ActivityEnvironment()++ with (+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,+ # Always patched — only consulted on the slack branch, harmless otherwise.+ patch(+ "posthog.temporal.subscriptions.activities.get_slack_integration_for_team",+ return_value=None,+ ),+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ result = await env.run(+ deliver_subscription,+ DeliverSubscriptionInputs(+ subscription_id=subscription.id,+ exported_asset_ids=[asset.id],+ total_insight_count=1,+ ),+ )++ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False+ send_mock.assert_called_once()+ capture_mock.assert_called_once()+ # Must return cleanly — NOT raise+ assert result is not None+ assert result.recipient_results[0].status == "failed"+ assert result.recipient_results[0].error == expected_error+++async def test_no_assets_does_not_auto_disable(team, user):+ """Empty `assets` at delivery time is a transient export-pipeline failure+ (genuine deletion is filtered upstream). Subscription stays enabled, the next+ scheduled cycle retries. The failure is surfaced via the per-recipient result+ on the SubscriptionDelivery record and a `subscription_delivery_failed` analytics+ event — SLO outcome is owned by the workflow (asset-level errors only) so it+ isn't asserted at this activity boundary."""+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="dis-noast", name="no_assets")+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="email",+ target_value="[email protected]",+ enabled=True,+ )++ env = ActivityEnvironment()++ with (+ patch("ee.tasks.subscriptions.auto_disable.disable_invalid_subscription") as disable_mock,+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ # Bogus id ensures `assets` resolves empty.+ result = await env.run(+ deliver_subscription,+ DeliverSubscriptionInputs(+ subscription_id=subscription.id,+ exported_asset_ids=[99_999_999],+ total_insight_count=1,+ ),+ )++ await sync_to_async(subscription.refresh_from_db)()+ # Subscription stays enabled — transient failure, retries can recover.+ assert subscription.enabled is True+ disable_mock.assert_not_called()+ # `subscription_delivery_failed` analytics still fires so existing dashboards see it.+ capture_mock.assert_called_once()+ # Returns cleanly — workflow records the per-recipient failure but SLO outcome+ # stays success; the next scheduled delivery retries.+ assert result is not None+ assert result.recipient_results[0].status == "failed"+ error = result.recipient_results[0].error+ assert error is not None+ assert error["type"] == "no_assets"+++async def test_deliver_subscription_retry_idempotent_after_auto_disable(team, user):+ """Simulates a Temporal redispatch after a successful auto-disable: first call+ auto-disables, second call must observe the entry guard and return without+ re-firing the disable email or analytics. UUID4 campaign keys mean+ MessagingRecord wouldn't dedup the duplicate email otherwise."""+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="retry-skip", name="retry idempotency")+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=team, insight=insight, export_format="image/png", content_location="s3://bucket/retry.png"+ )+ # webhook is unsupported, so the first call hits the auto-disable branch.+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="webhook",+ target_value="https://example.com/hook",+ enabled=True,+ )++ env = ActivityEnvironment()+ inputs = DeliverSubscriptionInputs(+ subscription_id=subscription.id, exported_asset_ids=[asset.id], total_insight_count=1+ )++ # First call: unsupported_target triggers auto-disable + per-recipient failure.+ with (+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ first_result = await env.run(deliver_subscription, inputs)++ assert first_result.recipient_results[0].status == "failed"+ error = first_result.recipient_results[0].error+ assert error is not None+ assert error["type"] == "unsupported_target"+ send_mock.assert_called_once()+ capture_mock.assert_called_once()++ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False++ # Second call simulates the Temporal redispatch — the entry guard short-circuits+ # so the disable email and analytics event do NOT fire again.+ with (+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ second_result = await env.run(deliver_subscription, inputs)++ assert second_result.recipient_results == []+ send_mock.assert_not_called()+ capture_mock.assert_not_called()+++ "label,target_type,target_value,initial_enabled,expected_aborts,expects_failed_recipient,expected_final_enabled",+ [+ ("valid_email_no_abort", "email", "[email protected]", True, False, False, True),+ ("unsupported_webhook_auto_disables", "webhook", "https://example.com/hook", True, True, True, False),+ ("already_disabled_short_circuits", "email", "[email protected]", False, True, False, False),+ ],+)+async def test_validate_subscription_for_delivery(+ team,+ user,+ label,+ target_type,+ target_value,+ initial_enabled,+ expected_aborts,+ expects_failed_recipient,+ expected_final_enabled,+):+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id=f"vld-{label[:5]}", name=label)+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type=target_type,+ target_value=target_value,+ enabled=initial_enabled,+ )++ env = ActivityEnvironment()+ with (+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,+ patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ ):+ abort_info = await env.run(validate_subscription_for_delivery, subscription.id)++ if expected_aborts:+ assert abort_info is not None+ if expects_failed_recipient:+ assert abort_info.failed_recipient is not None+ assert abort_info.failed_recipient.recipient == target_value+ assert abort_info.failed_recipient.status == "failed"+ else:+ assert abort_info.failed_recipient is None+ else:+ assert abort_info is None+ assert send_mock.called is expects_failed_recipient+ assert capture_mock.called is expects_failed_recipient+ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is expected_final_enabled@patch("posthog.slo.events.posthoganalytics")@@ -1524,3 +1775,148 @@ async def test_workflow_survives_large_insight_snapshot(assert "insights" in contentassert len(content["insights"]) == 1assert len(content["insights"][0]["query_results"]["results"]) == 50_000+++async def test_fetch_due_subscriptions_excludes_disabled(team, user):+ dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="dashboard", created_by=user)++ now = datetime.now(tz=ZoneInfo("UTC"))++ enabled_sub = await sync_to_async(Subscription.objects.create)(+ team=team,+ dashboard=dashboard,+ title="enabled sub",+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=now,+ enabled=True,+ )+ disabled_sub = await sync_to_async(Subscription.objects.create)(+ team=team,+ dashboard=dashboard,+ title="disabled sub",+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=now,+ enabled=False,+ )++ # The model's save() advances next_delivery_date to the future via rrule.+ # Force both subs into the "due" window so the buffer alone doesn't filter them out.+ await sync_to_async(Subscription.objects.filter(id__in=[enabled_sub.id, disabled_sub.id]).update)(+ next_delivery_date=now,+ )++ env = ActivityEnvironment()+ result = await env.run(+ fetch_due_subscriptions_activity,+ FetchDueSubscriptionsActivityInputs(buffer_minutes=15),+ )+ fetched_ids = {sub.subscription_id for sub in result}++ assert enabled_sub.id in fetched_ids+ assert disabled_sub.id not in fetched_ids+++@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")+@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")+@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)+@patch("posthog.temporal.exports.activities.exporter")+@patch("posthog.slo.events.posthoganalytics")+@freeze_time("2022-02-02T08:55:00.000Z")+async def test_deliver_subscription_emits_success_slo_when_disabling(+ mock_slo_analytics: MagicMock,+ mock_exporter: MagicMock,+ mock_get_slack: MagicMock,+ mock_build_snapshot: MagicMock,+ mock_send_notification: MagicMock,+ temporal_client: Client,+ team,+ user,+):+ # The slack-missing-integration branch auto-disables and returns cleanly, so+ # the SLO interceptor records outcome=success. Locks in as a regression invariant.+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="slo-d1", name="SLO disable")+ mock_build_snapshot.return_value = {+ "id": insight.id,+ "short_id": str(insight.short_id),+ "name": insight.name or "",+ "dashboard_tile_id": None,+ "query_hash": "mock_cache_key",+ "cache_key": "mock_cache_key",+ "query_results": {"result": []},+ }+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="slack",+ target_value="C12345|#test-channel",+ )+ await sync_to_async(ExportedAsset.objects.create)(+ team=team,+ insight=insight,+ export_format="image/png",+ content_location="s3://bucket/slo-disable.png",+ )++ # Stub out the actual export — the test insight has no series, so the+ # real exporter would raise ValidationError and pollute the SLO outcome+ # with PartialExportFailure before deliver_subscription even runs.+ def fake_export(asset_obj, **kwargs):+ asset_obj.content_location = "s3://bucket/slo-disable.png"+ asset_obj.save(update_fields=["content_location"])++ mock_exporter.export_asset_direct = fake_export++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ workflows=[ProcessSubscriptionWorkflow],+ activities=SUBSCRIPTION_PROCESS_ACTIVITIES,+ interceptors=[SloInterceptor()],+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=10),+ debug_mode=True,+ ):+ await env.client.execute_workflow(+ ProcessSubscriptionWorkflow.run,+ TrackedSubscriptionInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ slo=SloConfig(+ operation=SloOperation.SUBSCRIPTION_DELIVERY,+ area=SloArea.ANALYTIC_PLATFORM,+ team_id=subscription.team_id,+ resource_id=str(subscription.id),+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ ),+ ),+ id=str(uuid.uuid4()),+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ )++ # Sanity: auto-disable wired correctly.+ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False+ mock_send_notification.assert_called_once()++ delivery_completed_calls = [+ c+ for c in mock_slo_analytics.capture.call_args_list+ if c.kwargs.get("event") == "slo_operation_completed"+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY+ ]+ # At least one subscription_delivery completion was recorded.+ assert delivery_completed_calls, "expected an slo_operation_completed event for subscription_delivery"++ for call in delivery_completed_calls:+ props = call.kwargs["properties"]+ assert props["outcome"] == SloOutcome.SUCCESS, (+ f"subscription_delivery SLO must stay success after auto-disable, got {props}"+ )diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e64b3563fff9..1c3a9fa6abb2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24965,6 +24965,8 @@ export namespace Schemas {readonly created_by: UserBasic;/** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */deleted?: boolean;+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean;/*** Human-readable name for this subscription.* @maxLength 100@@ -30345,6 +30347,8 @@ export namespace Schemas {readonly created_by?: UserBasic;/** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */deleted?: boolean;+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean;/*** Human-readable name for this subscription.* @maxLength 100diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex dd86a4a2f252..d3c563e4197c 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -389,6 +389,12 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.nullish().describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'+ ),title: zod.string().max(subscriptionsCreateBodyTitleMax)@@ -510,6 +516,12 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.nullish().describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'+ ),title: zod.string().max(subscriptionsPartialUpdateBodyTitleMax)diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex 56f5bb3aafbe..1d8a53f275c6 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -275,6 +275,9 @@ const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemif (params.deleted !== undefined) {body['deleted'] = params.deleted}+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }if (params.title !== undefined) {body['title'] = params.title}@@ -426,6 +429,9 @@ const subscriptionsPartialUpdate = (): ToolBase<typeof SubscriptionsPartialUpdatif (params.deleted !== undefined) {body['deleted'] = params.deleted}+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }if (params.title !== undefined) {body['title'] = params.title}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-create.jsonindex d4ce280b3922..1efb458ed79f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-create.json@@ -66,6 +66,10 @@"description": "Set to true to soft-delete. Subscriptions cannot be hard-deleted.","type": "boolean"},+ "enabled": {+ "description": "Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.",+ "type": "boolean"+ },"frequency": {"description": "How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly","enum": ["daily", "weekly", "monthly", "yearly"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-partial-update.jsonindex aafe56aded4a..4f9352790960 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/subscriptions-partial-update.json@@ -65,6 +65,10 @@"description": "Set to true to soft-delete. Subscriptions cannot be hard-deleted.","type": "boolean"},+ "enabled": {+ "description": "Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.",+ "type": "boolean"+ },"frequency": {"description": "How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly","enum": ["daily", "weekly", "monthly", "yearly"],