:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(subscriptions): fail deliveries without insights (#75673)
Matt Puac795f4b7005f
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 92555eb9cfd7..77c272266ab8 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -67,7 +67,7 @@ from products.product_analytics.backend.models.insight import Insightfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limitedfrom ee.tasks.subscriptions.auto_disable import validate_re_enable-from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT+from ee.tasks.subscriptions.subscription_utils import MAX_DASHBOARD_INSIGHTSSUMMARY_QUOTA_CACHE_TTL_SECONDS = 60SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS = 600@@ -671,9 +671,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):if dashboard_export_insights:selected_ids = set(dashboard_export_insights)- if len(selected_ids) > DEFAULT_MAX_ASSET_COUNT:+ if len(selected_ids) > MAX_DASHBOARD_INSIGHTS:raise ValidationError(- {"dashboard_export_insights": [f"Cannot select more than {DEFAULT_MAX_ASSET_COUNT} insights."]}+ {"dashboard_export_insights": [f"Cannot select more than {MAX_DASHBOARD_INSIGHTS} insights."]})# Ensure all selected insights belong to the team@@ -711,7 +711,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):)invite_message = validated_data.pop("invite_message", "")- # The immediate confirmation delivery (TARGET_CHANGE below) is separate from the+ # The immediate confirmation delivery (SUBSCRIPTION_CHANGE below) is separate from the# recurring schedule, which the scheduler drives off next_delivery_date. Creators# can opt out of that first send via send_test_now; the schedule is unaffected.send_test_now = validated_data.pop("send_test_now", True)@@ -765,9 +765,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):distinct_id=str(instance.created_by.distinct_id)if instance.created_byelse str(instance.team_id),+ previous_target_value="",previous_value="",invite_message=invite_message,- trigger_type=SubscriptionTriggerType.TARGET_CHANGE,+ trigger_type=SubscriptionTriggerType.SUBSCRIPTION_CHANGE,resource_type=instance.resource_type,),id=workflow_id,@@ -779,7 +780,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+ previous_target_value = instance.target_valuewas_disabled = instance.enabled is Falseis_delete = not instance.deleted and validated_data.get("deleted") is Trueinvite_message = validated_data.pop("invite_message", "")@@ -835,19 +836,19 @@ class SubscriptionSerializer(serializers.ModelSerializer):# 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.+ # SCHEDULED delivery right after the immediate SUBSCRIPTION_CHANGE confirmation.if is_re_enabling:instance.set_next_delivery_date()instance.save(update_fields=["next_delivery_date"])- delivery_target_changed = any(+ delivery_content_changed = any(getattr(instance, field) != old_value for field, old_value in old_delivery_values.items()) or (old_export_insight_ids is not None and set(dashboard_export_insight_ids) != old_export_insight_ids)# Explicit send_test_now wins. When omitted, infer: send when the edit changed what# gets delivered, or on re-enable — a schedule/meta-only edit must not push a fresh# delivery. Disabled subscriptions never fire regardless.- wants_delivery = send_test_now if send_test_now is not None else (is_re_enabling or delivery_target_changed)+ wants_delivery = send_test_now if send_test_now is not None else (is_re_enabling or delivery_content_changed)delivery_triggered = wants_delivery and instance.enabled# Explicit observability for the delivery decision on edits — the canonical@@ -892,9 +893,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):distinct_id=str(instance.created_by.distinct_id)if instance.created_byelse str(instance.team_id),- previous_value=previous_value,+ previous_target_value=previous_target_value,+ previous_value=previous_target_value,invite_message=invite_message,- trigger_type=SubscriptionTriggerType.TARGET_CHANGE,+ trigger_type=SubscriptionTriggerType.SUBSCRIPTION_CHANGE,resource_type=instance.resource_type,),id=workflow_id,@@ -941,6 +943,7 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool@extend_schema_view(list=extend_schema(+ extensions={"x-product": "subscriptions"},parameters=[OpenApiParameter(name="created_by",@@ -995,8 +998,12 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool),],),+ create=extend_schema(extensions={"x-product": "subscriptions"}),+ retrieve=extend_schema(extensions={"x-product": "subscriptions"}),+ partial_update=extend_schema(extensions={"x-product": "subscriptions"}),+ destroy=extend_schema(extensions={"x-product": "subscriptions"}),)-@extend_schema(tags=["subscriptions"])+@extend_schema(tags=["subscriptions"], extensions={"x-product": "subscriptions"})class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):scope_object = "subscription"queryset = Subscription.objects.all()@@ -1132,6 +1139,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mreturn queryset@extend_schema(+ extensions={"x-product": "subscriptions"},request=None,responses={200: OpenApiResponse(@@ -1178,6 +1186,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mreturn Response(payload)@extend_schema(+ extensions={"x-product": "subscriptions"},request=None,responses={202: OpenApiResponse(description="Test delivery workflow started")},)@@ -1212,6 +1221,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mdistinct_id=str(subscription.created_by.distinct_id)if subscription.created_byelse str(subscription.team_id),+ previous_target_value=None,previous_value=None,invite_message=None,trigger_type=SubscriptionTriggerType.MANUAL,@@ -1322,7 +1332,7 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):"subscription": {"help_text": "Parent subscription id."},"temporal_workflow_id": {"help_text": "Temporal workflow id for this delivery run."},"idempotency_key": {"help_text": "Dedupes activity retries for the same logical run."},- "trigger_type": {"help_text": "Why the run started (e.g. scheduled, manual, target_change)."},+ "trigger_type": {"help_text": "Why the run started (e.g. scheduled, manual, subscription update)."},"scheduled_at": {"help_text": "Planned send time when applicable."},"target_type": {"help_text": "Channel snapshot at send time (email or slack)."},"target_value": {"help_text": "Destination snapshot at send time (emails, channel id, URL)."},@@ -1400,6 +1410,7 @@ class SubscriptionDeliveryCursorPagination(CursorPagination):@extend_schema_view(list=extend_schema(+ extensions={"x-product": "subscriptions"},summary="List subscription deliveries",description="Paginated delivery history for a subscription. Requires premium subscriptions.",parameters=[@@ -1415,12 +1426,13 @@ class SubscriptionDeliveryCursorPagination(CursorPagination):responses={200: OpenApiResponse(response=SubscriptionDeliverySerializer(many=True))},),retrieve=extend_schema(+ extensions={"x-product": "subscriptions"},summary="Retrieve subscription delivery",description="Fetch one delivery row by id.",responses={200: SubscriptionDeliverySerializer},),)-@extend_schema(tags=["subscriptions"])+@extend_schema(tags=["subscriptions"], extensions={"x-product": "subscriptions"})class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):scope_object = "subscription"queryset = SubscriptionDelivery.objects.all()diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 032b5b6c83e5..9bc83536f843 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -299,6 +299,7 @@ class TestSubscriptionTemporal(APILicensedTest):self.mock_temporal_client.start_workflow.assert_called_once()wf_args, _ = self.mock_temporal_client.start_workflow.call_argsactivity_inputs = wf_args[1]+ assert activity_inputs.previous_target_value == "[email protected]"assert activity_inputs.previous_value == "[email protected]"assert activity_inputs.invite_message == "hi new user"@@ -1203,6 +1204,7 @@ class TestSubscriptionTemporal(APILicensedTest):activity_inputs = wf_args[1]assert isinstance(activity_inputs, ProcessSubscriptionWorkflowInputs)assert activity_inputs.subscription_id == sub_id+ assert activity_inputs.previous_target_value is Noneassert activity_inputs.previous_value is Noneassert activity_inputs.trigger_type == SubscriptionTriggerType.MANUALassert wf_kwargs["id"] == f"test-delivery-subscription-{sub_id}"@@ -1664,7 +1666,7 @@ class TestSubscriptionTemporal(APILicensedTest):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.+ # after the immediate SUBSCRIPTION_CHANGE confirmation.subscription = Subscription.objects.create(team=self.team,target_type="email",diff --git a/ee/tasks/subscriptions/__init__.py b/ee/tasks/subscriptions/__init__.pyindex 9dfa3c82fcca..dbf7965fa2d5 100644--- a/ee/tasks/subscriptions/__init__.py+++ b/ee/tasks/subscriptions/__init__.py@@ -1,3 +1,7 @@+from __future__ import annotations++from typing import TYPE_CHECKING+import structlogimport posthoganalyticsfrom temporalio import activity, workflow@@ -5,6 +9,9 @@ from temporalio.common import MetricCounter, MetricMeterfrom products.exports.backend.models.subscription import Subscription+if TYPE_CHECKING:+ from products.exports.backend.temporal.subscriptions.types import NoExportableInsightsContext+logger = structlog.get_logger(__name__)# Slack errors that won't self-heal without user action — skip Temporal retries@@ -65,7 +72,9 @@ def get_subscription_failure_metric(SUPPORTED_TARGET_TYPES = frozenset(["email", "slack"])-def _capture_delivery_failed_event(subscription: Subscription, e: Exception) -> None:+def _capture_delivery_failed_event(+ subscription: Subscription, e: Exception, properties: NoExportableInsightsContext | None = None+) -> None:distinct_id = (subscription.created_by.distinct_id if subscription.created_by else None) or subscription.team_idposthoganalytics.capture(distinct_id=str(distinct_id),@@ -76,5 +85,6 @@ def _capture_delivery_failed_event(subscription: Subscription, e: Exception) ->"target_type": subscription.target_type,"exception": str(e),"exception_type": type(e).__name__,+ **(properties or {}),},)diff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.pyindex 027db8e78753..b84c95be69c6 100644--- a/ee/tasks/subscriptions/subscription_utils.py+++ b/ee/tasks/subscriptions/subscription_utils.py@@ -18,8 +18,8 @@ from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)UTM_TAGS_BASE = "utm_source=posthog&utm_campaign=subscription_report"-# Keep in sync with MAX_INSIGHTS in frontend/src/lib/components/Subscriptions/insightSelectorLogic.ts-DEFAULT_MAX_ASSET_COUNT = 6+# Keep in sync with MAX_INSIGHTS in products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.ts.+MAX_DASHBOARD_INSIGHTS = 6ASSET_GENERATION_FAILED_MESSAGE = "Failed to generate content"# Prometheus metrics for Temporal workers (web/worker pods)SUBSCRIPTION_ASSET_GENERATION_TIMER = Histogram(@@ -36,7 +36,7 @@ def _has_asset_failed(asset: ExportedAsset) -> bool:def generate_assets(resource: Union[Subscription, SharingConfiguration],- max_asset_count: int = DEFAULT_MAX_ASSET_COUNT,+ max_asset_count: int = MAX_DASHBOARD_INSIGHTS,) -> tuple[list[Insight], list[ExportedAsset]]:with SUBSCRIPTION_ASSET_GENERATION_TIMER.labels(execution_path="celery").time():if resource.dashboard:diff --git a/ee/tasks/test/subscriptions/test_subscriptions_utils.py b/ee/tasks/test/subscriptions/test_subscriptions_utils.pyindex 6a55a4d6d131..4b57d88e4b25 100644--- a/ee/tasks/test/subscriptions/test_subscriptions_utils.py+++ b/ee/tasks/test/subscriptions/test_subscriptions_utils.py@@ -7,7 +7,7 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.models.insight import Insight-from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT, generate_assets+from ee.tasks.subscriptions.subscription_utils import MAX_DASHBOARD_INSIGHTS, generate_assetsfrom ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription@@ -44,8 +44,8 @@ class TestSubscriptionsTasksUtils(APIBaseTest):insights, assets = generate_assets(subscription)assert len(insights) == len(self.tiles)- assert len(assets) == DEFAULT_MAX_ASSET_COUNT- assert mock_export_task.si.call_count == DEFAULT_MAX_ASSET_COUNT+ assert len(assets) == MAX_DASHBOARD_INSIGHTS+ assert mock_export_task.si.call_count == MAX_DASHBOARD_INSIGHTSdef test_raises_if_missing_resource(self, _mock_export_task: MagicMock, _mock_group: MagicMock) -> None:subscription = create_subscription(team=self.team, created_by=self.user)diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 95e57ab0a771..498b2e9b89f3 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -36,6 +36,7 @@ from products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, SubscriptionDeliveryfrom products.exports.backend.tasks.failure_handler import ExcelColumnLimitExceededfrom products.exports.backend.temporal.subscriptions.activities import (+ _resolve_exportable_insights,advance_next_delivery_date,create_delivery_record,create_export_assets,@@ -57,8 +58,10 @@ from products.exports.backend.temporal.subscriptions.types import (CreateExportAssetsInputs,DeliverSubscriptionInputs,DeliveryStatus,+ ExportAssetPreparationStatus,FetchDueSubscriptionsActivityInputs,GenerateAIReportInputs,+ NoExportableInsightsReason,ProcessSubscriptionWorkflowInputs,ScheduleAllSubscriptionsWorkflowInputs,SubscriptionTriggerType,@@ -87,6 +90,17 @@ _IS_OVER_BUDGET = ()_CREDIT_LIMITED_EMAIL = "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"++async def test_subscription_workflows_accept_legacy_previous_target_payload() -> None:+ payload = '{"subscription_id": 1, "previous_value": "[email protected]"}'++ process_inputs = ProcessSubscriptionWorkflow.parse_inputs([payload])+ update_inputs = HandleSubscriptionValueChangeWorkflow.parse_inputs([payload])++ assert process_inputs.previous_target_value == "[email protected]"+ assert update_inputs.previous_target_value == "[email protected]"++SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(Sequence[Callable[..., Any]],[@@ -283,6 +297,13 @@ async def test_does_not_schedule_subscription_if_item_is_deleted(@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")+ ("previous_target_value", "expected_recipients"),+ [+ ("[email protected]", ["[email protected]"]),+ ],+)@pytest.mark.asyncioasync def test_handle_subscription_value_change_email(mock_send_email: MagicMock,@@ -293,6 +314,8 @@ async def test_handle_subscription_value_change_email(subscriptions_worker,team,user,+ previous_target_value: str,+ expected_recipients: list[str],):insight = await sync_to_async(Insight.objects.create)(team=team, short_id="xyz789", name="Insight")@@ -326,16 +349,14 @@ async def test_handle_subscription_value_change_email(subscription_id=subscription.id,team_id=subscription.team_id,distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]- previous_value="[email protected]",+ previous_target_value=previous_target_value,invite_message="My invite message",),id=str(uuid.uuid4()),task_queue=settings.TEMPORAL_TASK_QUEUE,)- # Only new address should be emailed- assert mock_send_email.call_count == 1- assert mock_send_email.call_args_list[0][0][0] == "[email protected]"+ assert [call.args[0] for call in mock_send_email.call_args_list] == expected_recipients# SLO events emitted exactly once (child only, not parent)started_calls = [@@ -1202,6 +1223,86 @@ async def test_create_export_assets_dashboard_with_multiple_insights()+@patch("posthog.slo.events.posthoganalytics")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event")+@freeze_time("2022-02-02T08:55:00.000Z")+async def test_stale_dashboard_selection_fails_without_retrying(+ mock_capture_delivery_failed: MagicMock,+ mock_send_email: MagicMock,+ mock_slo_analytics: MagicMock,+ team,+ user,+):+ dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Stale selection", created_by=user)+ active_insight = await sync_to_async(Insight.objects.create)(team=team, short_id="active01", name="Active")+ stale_insight = await sync_to_async(Insight.objects.create)(team=team, short_id="stale01", name="Removed")+ await sync_to_async(DashboardTile.objects.create)(dashboard=dashboard, insight=active_insight)+ subscription = await sync_to_async(create_subscription)(team=team, dashboard=dashboard, created_by=user)+ await sync_to_async(subscription.dashboard_export_insights.add)(stale_insight)++ 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]+ trigger_type=SubscriptionTriggerType.SCHEDULED,+ 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,+ )++ delivery = await sync_to_async(SubscriptionDelivery.objects.get)(subscription=subscription)+ assert delivery.status == SubscriptionDelivery.Status.FAILED+ assert delivery.error is not None+ assert delivery.error["type"] == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS+ assert delivery.error["reason"] == NoExportableInsightsReason.SELECTED_INSIGHTS_NO_LONGER_AVAILABLE+ assert delivery.error["resource_type"] == "dashboard"+ assert delivery.error["available_insight_count"] == 1+ assert delivery.error["selected_insight_count"] == 1+ mock_send_email.assert_not_called()+ mock_capture_delivery_failed.assert_called_once()+ assert mock_capture_delivery_failed.call_args.args[2] == {+ "reason": NoExportableInsightsReason.SELECTED_INSIGHTS_NO_LONGER_AVAILABLE,+ "resource_type": "dashboard",+ "available_insight_count": 1,+ "selected_insight_count": 1,+ }++ completed_calls = [+ call+ for call in mock_slo_analytics.capture.call_args_list+ if call.kwargs.get("event") == "slo_operation_completed"+ and call.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY+ ]+ assert len(completed_calls) == 1+ properties = completed_calls[0].kwargs["properties"]+ assert properties["outcome"] == SloOutcome.SUCCESS+ assert properties["error_type"] == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS+ assert properties["failure_type"] == "configuration"+ assert properties["reason"] == NoExportableInsightsReason.SELECTED_INSIGHTS_NO_LONGER_AVAILABLE++@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_create_export_assets_excludes_deleted_insights(team, user):@@ -1226,16 +1327,52 @@ async def test_create_export_assets_excludes_deleted_insights(team, user):@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncio-async def test_create_export_assets_raises_on_missing_resource(team, user):+async def test_create_export_assets_classifies_missing_resource(team, user):subscription = await sync_to_async(create_subscription)(team=team, created_by=user)- env = ActivityEnvironment()- with pytest.raises(Exception, match="There are no insights to be sent"):- await env.run(- create_export_assets,- CreateExportAssetsInputs(subscription_id=subscription.id),+ with patch("products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"):+ result = await ActivityEnvironment().run(+ create_export_assets, CreateExportAssetsInputs(subscription_id=subscription.id))+ assert result.status == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS+ assert result.failure_context == {+ "reason": NoExportableInsightsReason.MISSING_RESOURCE,+ "resource_type": "unknown",+ "available_insight_count": 0,+ "selected_insight_count": 0,+ }+++async def test_resolve_exportable_insights_classifies_deleted_dashboard(team, user):+ dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Deleted", created_by=user, deleted=True)+ subscription = await sync_to_async(create_subscription)(team=team, dashboard=dashboard, created_by=user)++ result = await _resolve_exportable_insights(subscription)++ assert result.tile_insight_pairs == []+ assert result.available_insight_count == 0+ assert result.selected_insight_count == 0+ assert result.no_exportable_reason == NoExportableInsightsReason.DASHBOARD_DELETED+++async def test_resolve_exportable_insights_filters_explicit_dashboard_selection(team, user):+ dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Selected", created_by=user)+ selected_insight = await sync_to_async(Insight.objects.create)(team=team, short_id="selected01", name="Selected")+ other_insight = await sync_to_async(Insight.objects.create)(team=team, short_id="other01", name="Other")+ stale_insight = await sync_to_async(Insight.objects.create)(team=team, short_id="stale02", name="Stale")+ await sync_to_async(DashboardTile.objects.create)(dashboard=dashboard, insight=selected_insight)+ await sync_to_async(DashboardTile.objects.create)(dashboard=dashboard, insight=other_insight)+ subscription = await sync_to_async(create_subscription)(team=team, dashboard=dashboard, created_by=user)+ await sync_to_async(subscription.dashboard_export_insights.add)(selected_insight, stale_insight)++ result = await _resolve_exportable_insights(subscription)++ assert [insight.id for _, insight in result.tile_insight_pairs] == [selected_insight.id]+ assert result.available_insight_count == 2+ assert result.selected_insight_count == 2+ assert result.no_exportable_reason is None+@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncio@@ -1257,27 +1394,52 @@ async def test_create_export_assets_respects_max_asset_count(team, user):assert result.total_insight_count == 10+async def test_create_export_assets_rejects_non_positive_max_asset_count():+ with pytest.raises(ApplicationError, match="Dashboard insight export limit must be at least 1, received 0"):+ await ActivityEnvironment().run(+ create_export_assets, CreateExportAssetsInputs(subscription_id=1, max_asset_count=0)+ )++@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_create_export_assets_empty_dashboard(team, user):dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Empty", created_by=user)subscription = await sync_to_async(create_subscription)(team=team, dashboard=dashboard, created_by=user)- env = ActivityEnvironment()- result = await env.run(- create_export_assets,- CreateExportAssetsInputs(subscription_id=subscription.id),- )+ with patch("products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"):+ result = await ActivityEnvironment().run(+ create_export_assets, CreateExportAssetsInputs(subscription_id=subscription.id)+ )assert result.exported_asset_ids == []assert result.total_insight_count == 0+ assert result.status == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS+ assert result.failure_context is not None+ assert result.failure_context["reason"] == NoExportableInsightsReason.EMPTY_DASHBOARD+++@freeze_time("2022-02-02T08:55:00.000Z")+async def test_create_export_assets_excludes_deleted_standalone_insight(team, user):+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="deleted01", deleted=True)+ subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)++ with patch("products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"):+ result = await ActivityEnvironment().run(+ create_export_assets, CreateExportAssetsInputs(subscription_id=subscription.id)+ )++ assert result.status == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS+ assert result.failure_context is not None+ assert result.failure_context["reason"] == NoExportableInsightsReason.MISSING_RESOURCE@patch("ee.tasks.subscriptions.get_metric_meter")@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncio-async def test_deliver_subscription_sends_email(+async def test_deliver_subscription_legacy_false_sends_all_recipients(mock_send_email: MagicMock,mock_metric_meter: MagicMock,temporal_client: Client,@@ -1301,6 +1463,8 @@ async def test_deliver_subscription_sends_email(subscription_id=subscription.id,exported_asset_ids=[asset.id],total_insight_count=1,+ previous_value="[email protected]",+ is_new_subscription_target=False,),)@@ -1429,7 +1593,7 @@ async def test_new_subscription_sends_invite_email(subscription_id=subscription.id,team_id=subscription.team_id,distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]- previous_value="",+ previous_target_value="",invite_message="Welcome!",),id=str(uuid.uuid4()),@@ -1488,7 +1652,7 @@ async def test_manual_send_uses_regular_template_not_invite(subscription_id=subscription.id,team_id=subscription.team_id,distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]- previous_value=None,+ previous_target_value=None,invite_message=None,trigger_type=SubscriptionTriggerType.MANUAL,),diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pyindex 8e4b9074be52..effcb7d46b51 100644--- a/products/exports/backend/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -2,6 +2,7 @@ import jsonimport uuidimport typingimport datetime as dt+import dataclassesfrom datetime import datetimefrom django.db.models import Q@@ -32,7 +33,10 @@ from products.exports.backend.temporal.subscriptions.types import (CreateExportAssetsResult,DeliverSubscriptionInputs,DeliverSubscriptionResult,+ ExportAssetPreparationStatus,FetchDueSubscriptionsActivityInputs,+ NoExportableInsightsContext,+ NoExportableInsightsReason,RecipientResult,SubscriptionAbortInfo,SubscriptionInfo,@@ -48,6 +52,7 @@ from ee.tasks.subscriptions.auto_disable import ()from ee.tasks.subscriptions.email_subscriptions import send_email_subscription_reportfrom ee.tasks.subscriptions.slack_subscriptions import send_slack_message_with_integration_async+from ee.tasks.subscriptions.subscription_utils import MAX_DASHBOARD_INSIGHTSLOGGER = get_logger(__name__)@@ -56,6 +61,89 @@ LOGGER = get_logger(__name__)NO_ASSETS_REASON = "No assets to deliver — likely a transient export pipeline failure; will retry on next schedule"+class NoExportableInsightsError(Exception):+ pass+++class ResolvedExportableInsights:+ tile_insight_pairs: list[tuple[DashboardTile | None, Insight]]+ available_insight_count: int+ selected_insight_count: int+ no_exportable_reason: str | None+++async def _resolve_exportable_insights(subscription: Subscription) -> ResolvedExportableInsights:+ dashboard = subscription.dashboard+ if dashboard:+ if dashboard.deleted:+ return ResolvedExportableInsights(+ tile_insight_pairs=[],+ available_insight_count=0,+ selected_insight_count=0,+ no_exportable_reason=NoExportableInsightsReason.DASHBOARD_DELETED,+ )++ tiles = await database_sync_to_async(+ lambda: list(+ dashboard.tiles.select_related("insight").filter(insight__isnull=False, insight__deleted=False).all()+ ),+ thread_sensitive=False,+ )()+ tiles.sort(+ key=lambda x: (+ (x.layouts or {}).get("sm", {}).get("y", 100),+ (x.layouts or {}).get("sm", {}).get("x", 100),+ )+ )+ tile_insight_pairs: list[tuple[DashboardTile | None, Insight]] = [+ (tile, tile.insight) for tile in tiles if tile.insight+ ]+ available_insight_count = len(tile_insight_pairs)+ selected_ids = await database_sync_to_async(+ lambda: (+ set(subscription.dashboard_export_insights.values_list("id", flat=True))+ if subscription.dashboard_export_insights.exists()+ else None+ ),+ thread_sensitive=False,+ )()+ if selected_ids:+ selected_pairs: list[tuple[DashboardTile | None, Insight]] = [+ (tile, insight) for tile, insight in tile_insight_pairs if insight.id in selected_ids+ ]+ return ResolvedExportableInsights(+ tile_insight_pairs=selected_pairs,+ available_insight_count=available_insight_count,+ selected_insight_count=len(selected_ids),+ no_exportable_reason=(+ None if selected_pairs else NoExportableInsightsReason.SELECTED_INSIGHTS_NO_LONGER_AVAILABLE+ ),+ )++ return ResolvedExportableInsights(+ tile_insight_pairs=tile_insight_pairs,+ available_insight_count=available_insight_count,+ selected_insight_count=0,+ no_exportable_reason=None if tile_insight_pairs else NoExportableInsightsReason.EMPTY_DASHBOARD,+ )++ if subscription.insight and not subscription.insight.deleted:+ return ResolvedExportableInsights(+ tile_insight_pairs=[(None, subscription.insight)],+ available_insight_count=1,+ selected_insight_count=0,+ no_exportable_reason=None,+ )++ return ResolvedExportableInsights(+ tile_insight_pairs=[],+ available_insight_count=0,+ selected_insight_count=0,+ no_exportable_reason=NoExportableInsightsReason.MISSING_RESOURCE,+ )++async def _persist_content_snapshot(*,delivery_id: uuid.UUID,@@ -163,6 +251,13 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExportsubscription_id=inputs.subscription_id,)+ max_asset_count = inputs.max_asset_count if inputs.max_asset_count is not None else MAX_DASHBOARD_INSIGHTS+ if max_asset_count <= 0:+ raise ApplicationError(+ f"Dashboard insight export limit must be at least 1, received {max_asset_count} for subscription {inputs.subscription_id}",+ non_retryable=True,+ )+subscription = await database_sync_to_async(Subscription.objects.select_related("created_by", "insight", "dashboard", "team").get,thread_sensitive=False,@@ -179,53 +274,44 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExporttarget_type=subscription.target_type,)- # Early exit if target value hasn't changed — avoids creating orphaned assets- # for subs whose payload is identical to the previous delivery.- if inputs.previous_value is not None and subscription.target_value == inputs.previous_value:- await LOGGER.ainfo(- "create_export_assets.no_change_skipping",+ resolved_insights = await _resolve_exportable_insights(subscription)+ tile_insight_pairs = resolved_insights.tile_insight_pairs++ total_insight_count = len(tile_insight_pairs)++ if not tile_insight_pairs:+ no_exportable_reason = resolved_insights.no_exportable_reason+ if no_exportable_reason is None:+ raise RuntimeError("No-exportable-insights resolution missing a failure reason")+ failure_context: NoExportableInsightsContext = {+ "reason": no_exportable_reason,+ "resource_type": "dashboard" if dashboard else "insight" if subscription.insight_id else "unknown",+ "available_insight_count": resolved_insights.available_insight_count,+ "selected_insight_count": resolved_insights.selected_insight_count,+ }+ await LOGGER.awarning(+ "create_export_assets.no_exportable_insights",subscription_id=inputs.subscription_id,+ dashboard_id=subscription.dashboard_id,+ insight_id=subscription.insight_id,+ **failure_context,+ )+ _capture_delivery_failed_event(+ subscription,+ NoExportableInsightsError(no_exportable_reason),+ failure_context,)return CreateExportAssetsResult(exported_asset_ids=[],- total_insight_count=0,+ total_insight_count=total_insight_count,team_id=team.id,+ distinct_id=str(subscription.created_by.distinct_id) if subscription.created_by else str(team.id),+ target_type=subscription.target_type,+ status=ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS,+ failure_context=failure_context,)- if dashboard:- tiles = await database_sync_to_async(- lambda: list(- dashboard.tiles.select_related("insight").filter(insight__isnull=False, insight__deleted=False).all()- ),- thread_sensitive=False,- )()- tiles.sort(- key=lambda x: (- (x.layouts or {}).get("sm", {}).get("y", 100),- (x.layouts or {}).get("sm", {}).get("x", 100),- )- )- tile_insight_pairs: list[tuple[DashboardTile | None, Insight]] = [- (tile, tile.insight) for tile in tiles if tile.insight- ]-- selected_ids = await database_sync_to_async(- lambda: (- set(subscription.dashboard_export_insights.values_list("id", flat=True))- if subscription.dashboard_export_insights.exists()- else None- ),- thread_sensitive=False,- )()- if selected_ids:- tile_insight_pairs = [(t, i) for t, i in tile_insight_pairs if i.id in selected_ids]- elif subscription.insight:- tile_insight_pairs = [(None, subscription.insight)]- else:- raise Exception("There are no insights to be sent for this Subscription")-- total_insight_count = len(tile_insight_pairs)- export_pairs = tile_insight_pairs[: inputs.max_asset_count]+ export_pairs = tile_insight_pairs[:max_asset_count]expiry = ExportedAsset.compute_expires_after(ExportedAsset.ExportFormat.PNG)assets = [@@ -310,25 +396,37 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubsLOGGER.info("deliver_subscription.skipped_disabled", subscription_id=inputs.subscription_id)return DeliverSubscriptionResult(recipient_results=[])+ previous_target_value = inputs.previous_target_value+ if previous_target_value is None:+ previous_target_value = inputs.previous_value+ send_only_to_new_recipients = (+ inputs.is_new_subscription_target+ if inputs.is_new_subscription_target is not None+ else previous_target_value is not None and previous_target_value != subscription.target_value+ )+await LOGGER.ainfo("deliver_subscription.starting",subscription_id=inputs.subscription_id,target_type=subscription.target_type,asset_count=len(inputs.exported_asset_ids),- is_new=inputs.is_new_subscription_target,+ is_new=send_only_to_new_recipients,resource_type=subscription.resource_type,)if subscription.resource_type == Subscription.ResourceType.AI_PROMPT:return await _deliver_ai_subscription(subscription, inputs, recipient_results)- return await _deliver_insight_dashboard_subscription(subscription, inputs, recipient_results)+ return await _deliver_insight_dashboard_subscription(+ subscription, inputs, recipient_results, send_only_to_new_recipients+ )async def _deliver_insight_dashboard_subscription(subscription: Subscription,inputs: DeliverSubscriptionInputs,recipient_results: list[RecipientResult],+ send_only_to_new_recipients: bool,) -> DeliverSubscriptionResult:if (get_subscription_disable_reason(subscription.target_type, subscription.integration_id)@@ -381,7 +479,7 @@ async def _deliver_insight_dashboard_subscription(email,subscription,assets,- invite_message=inputs.invite_message or "" if inputs.is_new_subscription_target else None,+ invite_message=inputs.invite_message or "" if send_only_to_new_recipients else None,total_asset_count=inputs.total_insight_count,send_async=False,change_summary=inputs.change_summary,@@ -398,7 +496,7 @@ async def _deliver_insight_dashboard_subscription(subscription,assets,total_asset_count=inputs.total_insight_count,- is_new_subscription=inputs.is_new_subscription_target,+ is_new_subscription=send_only_to_new_recipients,change_summary=inputs.change_summary,summary_skipped_over_budget=inputs.summary_skipped_over_budget,),diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.pyindex 5cb6cf7c4807..1241fcd0242a 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py@@ -357,7 +357,7 @@ class TestLastSuccessfulDeliveryAnchor(APIBaseTest):SubscriptionTriggerType.MANUAL, SubscriptionDelivery.Status.COMPLETED, scheduled_at + timedelta(days=1))self._delivery(- SubscriptionTriggerType.TARGET_CHANGE,+ SubscriptionTriggerType.SUBSCRIPTION_CHANGE,SubscriptionDelivery.Status.COMPLETED,scheduled_at + timedelta(days=2),)diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.pyindex 961cf2b1c6c2..087d7a3966e2 100644--- a/products/exports/backend/temporal/subscriptions/delivery_common.py+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py@@ -78,8 +78,16 @@ async def deliver_email("""Send to each recipient via `send_one`. Partial success is kept; only an all-failed runraises, so a Temporal retry won't re-send to recipients who already succeeded."""emails = list(dict.fromkeys(e.strip() for e in subscription.target_value.split(",") if e.strip()))- if inputs.is_new_subscription_target and inputs.previous_value is not None:- previous = {e.strip() for e in inputs.previous_value.split(",") if e.strip()}+ previous_target_value = inputs.previous_target_value+ if previous_target_value is None:+ previous_target_value = inputs.previous_value+ send_only_to_new_recipients = (+ inputs.is_new_subscription_target+ if inputs.is_new_subscription_target is not None+ else previous_target_value is not None and previous_target_value != subscription.target_value+ )+ if send_only_to_new_recipients:+ previous = {e.strip() for e in (previous_target_value or "").split(",") if e.strip()}emails = [e for e in emails if e not in previous]await LOGGER.ainfo(diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pyindex c191d7549948..e207802de7f8 100644--- a/products/exports/backend/temporal/subscriptions/types.py+++ b/products/exports/backend/temporal/subscriptions/types.py@@ -4,8 +4,6 @@ import dataclassesfrom posthog.slo.types import SloConfig-from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT-class DeliveryStatus:"""Mirrors SubscriptionDelivery.Status choices for use in Temporal workflows.@@ -20,6 +18,30 @@ class DeliveryStatus:SKIPPED = "skipped"+class ExportAssetPreparationStatus:+ READY = "ready"+ NO_EXPORTABLE_INSIGHTS = "no_exportable_insights"+++class NoExportableInsightsReason:+ DASHBOARD_DELETED = "dashboard_deleted"+ EMPTY_DASHBOARD = "empty_dashboard"+ MISSING_RESOURCE = "missing_resource"+ SELECTED_INSIGHTS_NO_LONGER_AVAILABLE = "selected_insights_no_longer_available"+++class NoExportableInsightsContext(typing.TypedDict):+ reason: str+ resource_type: str+ available_insight_count: int+ selected_insight_count: int+++class NoExportableInsightsErrorDetails(NoExportableInsightsContext):+ message: str+ type: str++# Mirrors Subscription.ResourceType.AI_PROMPT — a plain constant so the Temporal# workflow sandbox can route by resource type without importing the Django model.AI_PROMPT_RESOURCE_TYPE = "ai_prompt"@@ -47,7 +69,7 @@ class SubscriptionTriggerType:"""SCHEDULED = "scheduled" # Regular cron-based delivery- TARGET_CHANGE = "target_change" # Target changed (previous_value is the old target)+ SUBSCRIPTION_CHANGE = "target_change" # An API create or edit triggered an immediate delivery.MANUAL = "manual" # User clicked "Test delivery"@@ -76,7 +98,8 @@ class FetchDueSubscriptionsActivityInputs:@dataclasses.dataclassclass CreateExportAssetsInputs:subscription_id: int- max_asset_count: int = DEFAULT_MAX_ASSET_COUNT+ max_asset_count: int | None = None+ # TODO(2026-07-30): Remove in a follow-up after this PR is fully deployed and pre-deployment activity payloads expire.previous_value: typing.Optional[str] = None# When set, the activity persists the per-insight snapshot directly onto# SubscriptionDelivery.content_snapshot. Keeps multi-MB query_results off@@ -99,6 +122,8 @@ class CreateExportAssetsResult:team_id: int = 0distinct_id: str = ""target_type: str = ""+ status: str = ExportAssetPreparationStatus.READY+ failure_context: NoExportableInsightsContext | None = None@dataclasses.dataclass@@ -106,8 +131,10 @@ class DeliverSubscriptionInputs:subscription_id: intexported_asset_ids: list[int]total_insight_count: int- is_new_subscription_target: bool = False+ previous_target_value: typing.Optional[str] = None+ # TODO(2026-07-30): Remove these legacy keys in a follow-up after this PR is fully deployed and pre-deployment activity payloads expire.previous_value: typing.Optional[str] = None+ is_new_subscription_target: bool | None = Noneinvite_message: typing.Optional[str] = Nonechange_summary: typing.Optional[str] = Nonesummary_skipped_over_budget: bool = False@@ -121,9 +148,11 @@ class ProcessSubscriptionWorkflowInputs:subscription_id: intteam_id: int = 0distinct_id: str = ""+ previous_target_value: typing.Optional[str] = None+ # TODO(2026-07-30): Remove in a follow-up after this PR is fully deployed and pre-deployment workflow payloads expire.previous_value: typing.Optional[str] = Noneinvite_message: typing.Optional[str] = None- trigger_type: str = SubscriptionTriggerType.TARGET_CHANGE+ trigger_type: str = SubscriptionTriggerType.SUBSCRIPTION_CHANGEscheduled_at: typing.Optional[str] = None# Lets HandleSubscriptionValueChangeWorkflow route AI-prompt subs to# ProcessAISubscriptionWorkflow. Passed by the API from the loaded instance.@@ -143,10 +172,12 @@ class TrackedSubscriptionInputs:subscription_id: intteam_id: int = 0distinct_id: str = ""+ previous_target_value: typing.Optional[str] = None+ # TODO(2026-07-30): Remove in a follow-up after this PR is fully deployed and pre-deployment workflow payloads expire.previous_value: typing.Optional[str] = Noneinvite_message: typing.Optional[str] = Noneslo: SloConfig | None = None- trigger_type: str = SubscriptionTriggerType.TARGET_CHANGE+ trigger_type: str = SubscriptionTriggerType.SUBSCRIPTION_CHANGEscheduled_at: typing.Optional[str] = Noneresource_type: str = ""@@ -253,7 +284,7 @@ class UpdateDeliveryRecordInputs:status: strexported_asset_ids: typing.Optional[list[int]] = Nonerecipient_results: typing.Optional[list[dict[str, typing.Any]]] = None- error: typing.Optional[dict[str, typing.Any]] = None+ error: typing.Optional[dict[str, typing.Any] | NoExportableInsightsErrorDetails] = Nonechange_summary: typing.Optional[str] = Nonefinished: bool = Falsediff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pyindex d1d9d28fc016..091591fa8cc3 100644--- a/products/exports/backend/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -46,8 +46,10 @@ from products.exports.backend.temporal.subscriptions.types import (DeliverSubscriptionInputs,DeliverSubscriptionResult,DeliveryStatus,+ ExportAssetPreparationStatus,FetchDueSubscriptionsActivityInputs,GenerateAIReportInputs,+ NoExportableInsightsErrorDetails,ProcessSubscriptionWorkflowInputs,RecipientResult,ScheduleAllSubscriptionsWorkflowInputs,@@ -191,6 +193,8 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):@staticmethoddef parse_inputs(inputs: list[str]) -> TrackedSubscriptionInputs:loaded = json.loads(inputs[0])+ if "previous_target_value" not in loaded and "previous_value" in loaded:+ loaded["previous_target_value"] = loaded["previous_value"]return TrackedSubscriptionInputs(**loaded)@temporalio.workflow.run@@ -199,6 +203,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):total_assets = 0asset_errors: list[ExportError] = []caught_error: BaseException | None = None+ delivery_error: NoExportableInsightsErrorDetails | None = None# Delivery record trackingdelivery_id: uuid.UUID | None = None@@ -252,7 +257,6 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):create_export_assets,CreateExportAssetsInputs(subscription_id=inputs.subscription_id,- previous_value=inputs.previous_value,delivery_id=delivery_id,),start_to_close_timeout=dt.timedelta(minutes=5),@@ -264,7 +268,39 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):)if not prepare_result.exported_asset_ids:- # No assets to export — SKIPPED status, finalized in finally+ if prepare_result.status == ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS:+ failure_context = prepare_result.failure_context+ if failure_context is None:+ raise ApplicationError(+ "No-exportable-insights result missing failure context", non_retryable=True+ )+ delivery_error = NoExportableInsightsErrorDetails(+ message="This subscription has no available insights to export. Add insights to the dashboard or update the subscription's insight selection.",+ type=ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS,+ reason=failure_context["reason"],+ resource_type=failure_context["resource_type"],+ available_insight_count=failure_context["available_insight_count"],+ selected_insight_count=failure_context["selected_insight_count"],+ )+ final_status = DeliveryStatus.FAILED+ temporalio.workflow.logger.warning(+ "process_subscription.no_exportable_insights",+ extra={+ "subscription_id": inputs.subscription_id,+ "trigger_type": inputs.trigger_type,+ "error_type": ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS,+ **failure_context,+ },+ )+ if inputs.slo:+ inputs.slo.completion_properties.update(+ {+ "error_type": ExportAssetPreparationStatus.NO_EXPORTABLE_INSIGHTS,+ "error_message": delivery_error["message"],+ "failure_type": "configuration",+ **failure_context,+ }+ )returndelivery_exported_asset_ids = prepare_result.exported_asset_ids@@ -336,17 +372,18 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):# a "failed to generate" placeholder in the email/Slack message)delivery_asset_ids = prepare_result.exported_asset_ids- # is_new is true for target change triggers, false for scheduled and manual sends- is_new = inputs.trigger_type == SubscriptionTriggerType.TARGET_CHANGE-deliver_result: DeliverSubscriptionResult = await temporalio.workflow.execute_activity(deliver_subscription,DeliverSubscriptionInputs(subscription_id=inputs.subscription_id,exported_asset_ids=delivery_asset_ids,total_insight_count=prepare_result.total_insight_count,- is_new_subscription_target=is_new,- previous_value=inputs.previous_value,+ previous_target_value=inputs.previous_target_value,+ previous_value=(+ inputs.previous_target_value+ if inputs.previous_target_value is not None+ else inputs.previous_value+ ),invite_message=inputs.invite_message,change_summary=change_summary,summary_skipped_over_budget=summary_skipped_over_budget,@@ -384,9 +421,11 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):exported_asset_ids=delivery_exported_asset_ids or None,recipient_results=delivery_recipient_results or None,change_summary=change_summary,- error={"message": str(caught_error)[:500], "type": type(caught_error).__name__}- if caught_error- else None,+ error=(+ {"message": str(caught_error)[:500], "type": type(caught_error).__name__}+ if caught_error+ else delivery_error+ ),finished=True,),start_to_close_timeout=dt.timedelta(minutes=2),@@ -513,16 +552,19 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):final_status = DeliveryStatus.SKIPPEDreturn- # Phase 2: ship the persisted report. is_new only for target-change triggers.- is_new = inputs.trigger_type == SubscriptionTriggerType.TARGET_CHANGE+ # Phase 2: ship the persisted report.deliver_result = await temporalio.workflow.execute_activity(deliver_subscription,DeliverSubscriptionInputs(subscription_id=inputs.subscription_id,exported_asset_ids=[],total_insight_count=0,- is_new_subscription_target=is_new,- previous_value=inputs.previous_value,+ previous_target_value=inputs.previous_target_value,+ previous_value=(+ inputs.previous_target_value+ if inputs.previous_target_value is not None+ else inputs.previous_value+ ),invite_message=inputs.invite_message,delivery_id=delivery_id,),@@ -605,6 +647,8 @@ class HandleSubscriptionValueChangeWorkflow(PostHogWorkflow):@staticmethoddef parse_inputs(inputs: list[str]) -> ProcessSubscriptionWorkflowInputs:loaded = json.loads(inputs[0])+ if "previous_target_value" not in loaded and "previous_value" in loaded:+ loaded["previous_target_value"] = loaded["previous_value"]return ProcessSubscriptionWorkflowInputs(**loaded)@temporalio.workflow.run@@ -613,7 +657,10 @@ class HandleSubscriptionValueChangeWorkflow(PostHogWorkflow):subscription_id=inputs.subscription_id,team_id=inputs.team_id,distinct_id=inputs.distinct_id,- previous_value=inputs.previous_value,+ previous_target_value=inputs.previous_target_value,+ previous_value=(+ inputs.previous_target_value if inputs.previous_target_value is not None else inputs.previous_value+ ),invite_message=inputs.invite_message,trigger_type=inputs.trigger_type,resource_type=inputs.resource_type,diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 636acd6b642b..dea859e7254b 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -476,7 +476,7 @@ export interface SubscriptionDeliveryApi {readonly temporal_workflow_id: string/** Dedupes activity retries for the same logical run. */readonly idempotency_key: string- /** Why the run started (e.g. scheduled, manual, target_change). */+ /** Why the run started (e.g. scheduled, manual, subscription update). */readonly trigger_type: string/*** Planned send time when applicable.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 45cfc46932ca..3462ff7050ad 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45817,7 +45817,7 @@ export namespace Schemas {readonly temporal_workflow_id: string;/** Dedupes activity retries for the same logical run. */readonly idempotency_key: string;- /** Why the run started (e.g. scheduled, manual, target_change). */+ /** Why the run started (e.g. scheduled, manual, subscription update). */readonly trigger_type: string;/*** Planned send time when applicable.