Skip to content

: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.

feat(subscriptions): scheduled AI delivery via Temporal (email + Slack) (#59631)

Vasco de Krijgera9bd43305b1b
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index fe8a390f7ecb..205efb436a58 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -526,6 +526,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
previous_value="",
invite_message=invite_message,
trigger_type=SubscriptionTriggerType.TARGET_CHANGE,
+ resource_type=instance.resource_type,
),
id=workflow_id,
task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
@@ -599,6 +600,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
previous_value=previous_value,
invite_message=invite_message,
trigger_type=SubscriptionTriggerType.TARGET_CHANGE,
+ resource_type=instance.resource_type,
),
id=workflow_id,
task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
@@ -801,6 +803,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
previous_value=None,
invite_message=None,
trigger_type=SubscriptionTriggerType.MANUAL,
+ resource_type=subscription.resource_type,
),
id=workflow_id,
task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
diff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.py
index de1a6473c2ea..7c739a5508c9 100644
--- a/ee/tasks/subscriptions/auto_disable.py
+++ b/ee/tasks/subscriptions/auto_disable.py
@@ -35,6 +35,16 @@ SLACK_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(
description="PostHog can no longer post to this Slack channel",
user_message="Cannot re-enable {target_type} subscription: PostHog can't post to this Slack channel. Reconnect Slack or re-add the bot to the channel, then try again.",
)
+AI_PROMPT_INVALID_DISABLE_REASON = DisableReason(
+ key="ai_prompt_invalid",
+ description="AI subscription prompt or creator is invalid",
+ user_message="Cannot re-enable AI subscription: the original creator is unavailable or the prompt is invalid. Edit the subscription with a valid prompt to re-enable.",
+)
+AI_CONSENT_REVOKED_DISABLE_REASON = DisableReason(
+ key="ai_consent_revoked",
+ description="Organization has not approved AI data processing",
+ user_message="Cannot re-enable AI subscription: your organization has not approved AI data processing. Approve it in your organization settings, then re-enable this subscription.",
+)
logger = structlog.get_logger(__name__)
@@ -88,9 +98,7 @@ def disable_invalid_subscription(subscription: Subscription, reason: DisableReas
if subscription.created_by and subscription.created_by.email:
try:
- send_notifications_for_disabled_subscription(
- subscription, reason.description, [subscription.created_by.email]
- )
+ send_notifications_for_disabled_subscription(subscription, reason, [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)
@@ -105,7 +113,9 @@ def disable_invalid_subscription(subscription: Subscription, reason: DisableReas
)
-def send_notifications_for_disabled_subscription(subscription: Subscription, reason: str, targets: list[str]) -> None:
+def send_notifications_for_disabled_subscription(
+ subscription: Subscription, reason: DisableReason, targets: list[str]
+) -> None:
logger.info(
"subscription.send_disabled_notification",
subscription_id=subscription.id,
@@ -127,7 +137,8 @@ def send_notifications_for_disabled_subscription(subscription: Subscription, rea
template_context={
"subscription_url": subscription.url,
"subscription_title": display_name,
- "reason": reason,
+ "reason": reason.description,
+ "action_message": reason.user_message.format(target_type=subscription.target_type),
},
)
for target in targets:
diff --git a/ee/tasks/subscriptions/test_auto_disable.py b/ee/tasks/subscriptions/test_auto_disable.py
index 70681967872d..3d7f65da1a29 100644
--- a/ee/tasks/subscriptions/test_auto_disable.py
+++ b/ee/tasks/subscriptions/test_auto_disable.py
@@ -8,6 +8,7 @@ from parameterized import parameterized
from products.exports.backend.models.subscription import Subscription
from ee.tasks.subscriptions.auto_disable import (
+ AI_PROMPT_INVALID_DISABLE_REASON,
SLACK_DISCONNECTED_DISABLE_REASON,
disable_invalid_subscription,
send_notifications_for_disabled_subscription,
@@ -67,7 +68,7 @@ class TestDisableInvalidSubscription(APIBaseTest):
sub.refresh_from_db()
assert sub.enabled is False
- send_mock.assert_called_once_with(sub, SLACK_DISCONNECTED_DISABLE_REASON.description, [self.user.email])
+ send_mock.assert_called_once_with(sub, SLACK_DISCONNECTED_DISABLE_REASON, [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,
@@ -107,12 +108,8 @@ class TestDisableInvalidSubscription(APIBaseTest):
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]
- )
+ send_notifications_for_disabled_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON, [self.user.email])
+ send_notifications_for_disabled_subscription(sub, SLACK_DISCONNECTED_DISABLE_REASON, [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"]
@@ -123,6 +120,18 @@ class TestDisableInvalidSubscription(APIBaseTest):
assert first_key.startswith(prefix)
assert second_key.startswith(prefix)
+ def test_disabled_email_includes_actionable_remediation(self):
+ sub = self._make_subscription()
+
+ with patch("ee.tasks.subscriptions.auto_disable.EmailMessage") as email_cls:
+ send_notifications_for_disabled_subscription(sub, AI_PROMPT_INVALID_DISABLE_REASON, [self.user.email])
+
+ ctx = email_cls.call_args.kwargs["template_context"]
+ assert ctx["reason"] == AI_PROMPT_INVALID_DISABLE_REASON.description
+ assert ctx["action_message"] == AI_PROMPT_INVALID_DISABLE_REASON.user_message.format(
+ target_type=sub.target_type
+ )
+
def test_disable_persists_when_email_send_fails(self):
"""Disabling is the durable side effect; email is best-effort.
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 5e8f07182937..6a26ef30c61a 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -1486,12 +1486,13 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
{"name": "another", "use_dashboard": existing_dashboard.id}
)
- after_duplication_insight_id = duplicate_response["tiles"][0]["insight"]["id"]
- assert after_duplication_insight_id == insight_one_id
- assert duplicate_response["tiles"][0]["insight"]["name"] == "the insight"
+ insight_tile = next(t for t in duplicate_response["tiles"] if t.get("insight"))
+ text_tile = next(t for t in duplicate_response["tiles"] if t.get("text"))
+ assert insight_tile["insight"]["id"] == insight_one_id
+ assert insight_tile["insight"]["name"] == "the insight"
- after_duplication_tile_id = duplicate_response["tiles"][1]["text"]["id"]
- assert after_duplication_tile_id == dashboard_with_tiles["tiles"][1]["text"]["id"]
+ original_text_tile = next(t for t in dashboard_with_tiles["tiles"] if t.get("text"))
+ assert text_tile["text"]["id"] == original_text_tile["text"]["id"]
def test_dashboard_duplication_without_tile_duplicate_excludes_soft_deleted_tiles(self):
existing_dashboard = Dashboard.objects.create(team=self.team, name="existing dashboard", created_by=self.user)
@@ -1534,12 +1535,13 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
}
)
- after_duplication_insight_id = duplicate_response["tiles"][0]["insight"]["id"]
- assert after_duplication_insight_id != insight_one_id
- assert duplicate_response["tiles"][0]["insight"]["name"] == "the insight (Copy)"
+ insight_tile = next(t for t in duplicate_response["tiles"] if t.get("insight"))
+ text_tile = next(t for t in duplicate_response["tiles"] if t.get("text"))
+ assert insight_tile["insight"]["id"] != insight_one_id
+ assert insight_tile["insight"]["name"] == "the insight (Copy)"
- after_duplication_tile_id = duplicate_response["tiles"][1]["text"]["id"]
- assert after_duplication_tile_id != dashboard_with_tiles["tiles"][1]["text"]["id"]
+ original_text_tile = next(t for t in dashboard_with_tiles["tiles"] if t.get("text"))
+ assert text_tile["text"]["id"] != original_text_tile["text"]["id"]
@parameterized.expand(
[
@@ -1589,19 +1591,13 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
assert duplicate_response is not None
assert len(duplicate_response.get("tiles", [])) == 2
- insight_tile = next(tile for tile in duplicate_response["tiles"] if "insight" in tile)
- text_tile = next(tile for tile in duplicate_response["tiles"] if "text" in tile)
-
- # this test only needs to check that insight name is still None,
- # but it flaps in CI.
- # my guess was that the order of the response is not guaranteed
- # but even after lifting insight tile out specifically, it still flaps
- # it isn't clear from the error if insight_tile or insight_tile["insight"] is None
- with self.retry_assertion():
- assert insight_tile is not None
- assert insight_tile["insight"] is not None
- assert insight_tile["insight"]["name"] is None
- assert text_tile is not None
+ # Every serialized tile carries both "insight" and "text" keys (the absent one is None),
+ # so select by which is populated — not by key presence or list order, which isn't guaranteed.
+ insight_tile = next(tile for tile in duplicate_response["tiles"] if tile.get("insight"))
+ text_tile = next(tile for tile in duplicate_response["tiles"] if tile.get("text"))
+
+ assert insight_tile["insight"]["name"] is None
+ assert text_tile["text"] is not None
def test_dashboard_duplication(self):
existing_dashboard = Dashboard.objects.create(team=self.team, name="existing dashboard", created_by=self.user)
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index aee6d90d5f47..3acc9e77d2bc 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -101,6 +101,24 @@ class TestSubscription(BaseTest):
with self.assertRaises(ValueError):
_ = subscription.resource_type
+ @parameterized.expand(
+ [
+ ("insight", 1, None, None, Subscription.ResourceType.INSIGHT),
+ ("dashboard", None, 2, None, Subscription.ResourceType.DASHBOARD),
+ ("prompt", None, None, "Summarize signups", Subscription.ResourceType.AI_PROMPT),
+ ("insight_takes_precedence", 1, 2, "ignored", Subscription.ResourceType.INSIGHT),
+ ]
+ )
+ def test_derive_resource_type(
+ self, _name: str, insight_id: int | None, dashboard_id: int | None, prompt: str | None, expected: str
+ ):
+ assert Subscription.derive_resource_type(insight_id, dashboard_id, prompt) == expected
+
+ @parameterized.expand([("all_none", None), ("empty_prompt", "")])
+ def test_derive_resource_type_raises_when_relationless(self, _name: str, prompt: str | None):
+ with pytest.raises(ValueError, match="no insight, dashboard, or prompt"):
+ Subscription.derive_resource_type(None, None, prompt)
+
def test_update_next_delivery_date_on_save(self):
subscription = self._create_insight_subscription()
subscription.save()
diff --git a/posthog/templates/email/subscription_disabled.html b/posthog/templates/email/subscription_disabled.html
index edfe8be98052..0ca60fd2136b 100644
--- a/posthog/templates/email/subscription_disabled.html
+++ b/posthog/templates/email/subscription_disabled.html
@@ -4,9 +4,11 @@
<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 action_message %}
+ <p>{{ action_message }}</p>
+ {% else %}
+ <p>To resume delivery, fix the issue above and re-enable the subscription.</p>
+ {% endif %}
{% if subscription_url %}
<div class="mb mt text-center">
<a class="button" href="{% absolute_uri subscription_url %}">Manage subscription</a>
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index 6d1c4445ab45..d752e03b7497 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -15,6 +15,7 @@ import pytest_asyncio
from asgiref.sync import sync_to_async
from slack_sdk.errors import SlackApiError
from temporalio.client import Client
+from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
@@ -41,12 +42,15 @@ from products.exports.backend.temporal.subscriptions.activities import (
update_delivery_record,
validate_subscription_for_delivery,
)
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_report
+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
from products.exports.backend.temporal.subscriptions.types import (
CreateDeliveryRecordInputs,
CreateExportAssetsInputs,
DeliverSubscriptionInputs,
DeliveryStatus,
FetchDueSubscriptionsActivityInputs,
+ GenerateAIReportInputs,
ProcessSubscriptionWorkflowInputs,
ScheduleAllSubscriptionsWorkflowInputs,
SubscriptionTriggerType,
@@ -55,16 +59,22 @@ from products.exports.backend.temporal.subscriptions.types import (
)
from products.exports.backend.temporal.subscriptions.workflows import (
HandleSubscriptionValueChangeWorkflow,
+ ProcessAISubscriptionWorkflow,
ProcessSubscriptionWorkflow,
ScheduleAllSubscriptionsWorkflow,
)
from products.product_analytics.backend.models.insight import Insight
+from ee.tasks.subscriptions.auto_disable import AI_CONSENT_REVOKED_DISABLE_REASON, SLACK_DISCONNECTED_DISABLE_REASON
from ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult
from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
+_GENERATE_MARKDOWN = (
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.generate_ai_subscription_markdown"
+)
+
SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
Sequence[Callable[..., Any]],
[
@@ -74,6 +84,7 @@ SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
create_export_assets,
export_asset_activity,
deliver_subscription,
+ generate_ai_subscription_report,
update_delivery_record,
advance_next_delivery_date,
],
@@ -87,6 +98,7 @@ SUBSCRIPTION_PROCESS_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
create_export_assets,
export_asset_activity,
deliver_subscription,
+ generate_ai_subscription_report,
update_delivery_record,
advance_next_delivery_date,
],
@@ -104,6 +116,7 @@ async def subscriptions_worker(temporal_client: Client):
ScheduleAllSubscriptionsWorkflow,
HandleSubscriptionValueChangeWorkflow,
ProcessSubscriptionWorkflow,
+ ProcessAISubscriptionWorkflow,
],
activities=SUBSCRIPTION_SCHEDULE_ACTIVITIES,
interceptors=[SloInterceptor()],
@@ -191,7 +204,9 @@ async def test_subscription_delivery_scheduling(
@patch("posthog.temporal.exports.activities.exporter")
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
-@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)
+@patch(
+ "products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team", return_value=None
+)
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
@freeze_time("2022-02-02T08:55:00.000Z")
@pytest.mark.asyncio
@@ -333,7 +348,7 @@ async def test_handle_subscription_value_change_email(
"products.exports.backend.temporal.subscriptions.activities.send_slack_message_with_integration_async",
new_callable=AsyncMock,
)
-@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team")
+@patch("products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team")
@patch("posthog.temporal.exports.activities.exporter")
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@@ -407,7 +422,9 @@ async def test_deliver_subscription_report_slack(
@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")
@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")
-@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)
+@patch(
+ "products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team", return_value=None
+)
@freeze_time("2022-02-02T08:55:00.000Z")
@pytest.mark.asyncio
async def test_process_subscription_records_missing_slack_integration_failure(
@@ -537,11 +554,11 @@ async def test_deliver_subscription_auto_disables_invalid_subscriptions(
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(
- "products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team",
+ "products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team",
return_value=None,
),
patch(
- "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"
+ "products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"
) as capture_mock,
):
result = await env.run(
@@ -643,7 +660,7 @@ async def test_deliver_subscription_retry_idempotent_after_auto_disable(team, us
with (
patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,
patch(
- "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"
+ "products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"
) as capture_mock,
):
first_result = await env.run(deliver_subscription, inputs)
@@ -663,7 +680,7 @@ async def test_deliver_subscription_retry_idempotent_after_auto_disable(team, us
with (
patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,
patch(
- "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"
+ "products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"
) as capture_mock,
):
second_result = await env.run(deliver_subscription, inputs)
@@ -823,7 +840,7 @@ async def test_deliver_subscription_handles_slack_api_errors(team, user, slack_e
with (
patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,
patch(
- "products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team",
+ "products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team",
return_value=mock_integration,
),
patch(
@@ -832,7 +849,7 @@ async def test_deliver_subscription_handles_slack_api_errors(team, user, slack_e
side_effect=slack_error,
),
patch(
- "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"
+ "products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"
) as capture_mock,
):
if expect_auto_disable:
@@ -1882,7 +1899,9 @@ async def test_fetch_due_subscriptions_excludes_disabled(team, user):
@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")
@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")
-@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)
+@patch(
+ "products.exports.backend.temporal.subscriptions.delivery_common.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")
@@ -1980,3 +1999,238 @@ async def test_deliver_subscription_emits_success_slo_when_disabling(
assert props["outcome"] == SloOutcome.SUCCESS, (
f"subscription_delivery SLO must stay success after auto-disable, got {props}"
)
+
+
+@sync_to_async
+def _create_ai_subscription(team, user, *, target_type="email", target_value="[email protected]") -> Subscription:
+ return create_subscription(
+ team=team,
+ created_by=user,
+ prompt="Top events",
+ title="AI report",
+ target_type=target_type,
+ target_value=target_value,
+ )
+
+
+@sync_to_async
+def _create_ai_delivery(subscription: Subscription, *, report: str | None = None) -> SubscriptionDelivery:
+ return SubscriptionDelivery.objects.create(
+ subscription=subscription,
+ team=subscription.team,
+ temporal_workflow_id="wf-test",
+ idempotency_key=str(uuid.uuid4()),
+ trigger_type="scheduled",
+ target_type=subscription.target_type,
+ target_value=subscription.target_value,
+ content_snapshot={"ai_report": report} if report is not None else {},
+ )
+
+
+@sync_to_async
+def _set_ai_consent(team, approved: bool) -> None:
+ org = team.organization
+ org.is_ai_data_processing_approved = approved
+ org.save(update_fields=["is_ai_data_processing_approved"])
+
+
+def _ai_delivery_inputs(subscription_id: int, delivery_id) -> DeliverSubscriptionInputs:
+ return DeliverSubscriptionInputs(
+ subscription_id=subscription_id, exported_asset_ids=[], total_insight_count=0, delivery_id=delivery_id
+ )
+
+
+async def test_generate_ai_report_consent_revoked_aborts_and_auto_disables(team, user):
+ await _set_ai_consent(team, False)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub)
+
+ with patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.aborted is True
+ error = result.recipient_results[0].error
+ assert error is not None and error["type"] == AI_CONSENT_REVOKED_DISABLE_REASON.key
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.enabled is False
+
+
+async def test_generate_ai_report_prompt_rejected_aborts_and_auto_disables(team, user):
+ await _set_ai_consent(team, True)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub)
+
+ with (
+ patch(_GENERATE_MARKDOWN, side_effect=PromptRejectedError("Prompt is empty.")),
+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"),
+ ):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.aborted is True
+ # The PromptRejectedError detail must reach the delivery record, not be swallowed.
+ assert any(r.error and r.error.get("type") == "PromptRejectedError" for r in result.recipient_results), (
+ "prompt-rejected abort must carry the rejection detail in recipient_results"
+ )
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.enabled is False
+
+
+async def test_generate_ai_report_persists_report_for_delivery(team, user):
+ await _set_ai_consent(team, True)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub)
+
+ with patch(_GENERATE_MARKDOWN, return_value="# Report"):
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.aborted is False
+ # The report is handed to delivery via the row, not the activity return value.
+ refreshed = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery.id)
+ assert refreshed.content_snapshot["ai_report"] == "# Report"
+
+
+async def test_deliver_ai_subscription_sends_persisted_report_to_email(team, user):
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub, report="# Report")
+
+ with patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report"
+ ) as mock_send:
+ result = await ActivityEnvironment().run(deliver_subscription, _ai_delivery_inputs(sub.id, delivery.id))
+
+ mock_send.assert_called_once()
+ assert mock_send.call_args.kwargs["markdown"] == "# Report"
+ assert result.recipient_results[0].status == "success"
+
+
+async def test_deliver_ai_subscription_missing_slack_integration_auto_disables(team, user):
+ sub = await _create_ai_subscription(team, user, target_type="slack", target_value="C123|#channel")
+ delivery = await _create_ai_delivery(sub, report="# Report")
+
+ with (
+ patch(
+ "products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team",
+ return_value=None,
+ ),
+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"),
+ ):
+ result = await ActivityEnvironment().run(deliver_subscription, _ai_delivery_inputs(sub.id, delivery.id))
+
+ error = result.recipient_results[0].error
+ assert error is not None and error["type"] == SLACK_DISCONNECTED_DISABLE_REASON.key
+ await sync_to_async(sub.refresh_from_db)()
+ assert sub.enabled is False
+
+
+async def test_deliver_ai_subscription_missing_report_raises_for_retry(team, user):
+ # Generation persists the report before delivery is scheduled; a missing report
+ # means the row was lost, so delivery must fail loudly rather than send an empty report.
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub, report=None)
+
+ with pytest.raises(ApplicationError) as exc_info:
+ await ActivityEnvironment().run(deliver_subscription, _ai_delivery_inputs(sub.id, delivery.id))
+ # Non-retryable is the load-bearing behavior: re-running delivery can't regenerate the
+ # report, so Temporal must not retry.
+ assert exc_info.value.non_retryable is True
+
+
+async def test_deliver_ai_subscription_without_delivery_id_raises(team, user):
+ # The AI workflow always creates the delivery row before delivery; a None reference is
+ # a wiring bug, so it must fail rather than silently no-op.
+ sub = await _create_ai_subscription(team, user)
+
+ with pytest.raises(ApplicationError) as exc_info:
+ await ActivityEnvironment().run(deliver_subscription, _ai_delivery_inputs(sub.id, None))
+ assert exc_info.value.non_retryable is True
+
+
+async def test_generate_ai_report_skips_regeneration_when_already_persisted(team, user):
+ # Idempotency on Temporal redispatch: a prior attempt already wrote the report, so the
+ # LLM pipeline must not run again (no re-bill).
+ await _set_ai_consent(team, True)
+ sub = await _create_ai_subscription(team, user)
+ delivery = await _create_ai_delivery(sub, report="# Already here")
+
+ with patch(_GENERATE_MARKDOWN) as mock_generate:
+ result = await ActivityEnvironment().run(
+ generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)
+ )
+
+ assert result.aborted is False
+ mock_generate.assert_not_called()
+
+
+@patch("posthog.slo.events.posthoganalytics")
+@patch("ee.tasks.subscriptions.get_metric_meter")
+@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
+@patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.activities.generate_ai_subscription_markdown",
+ return_value="# AI Report",
+)
+@freeze_time("2022-02-02T08:55:00.000Z")
+async def test_schedule_routes_ai_subscription_through_full_workflow(
+ mock_generate: MagicMock,
+ mock_send_email: MagicMock,
+ mock_metric_meter: MagicMock,
+ mock_analytics: MagicMock,
+ temporal_client: Client,
+ team,
+ user,
+):
+ # End-to-end: the scheduler fans a due AI sub out to ProcessAISubscriptionWorkflow,
+ # which runs create-record -> validate -> generate (persist) -> deliver -> finalize.
+ # Activity-level tests don't catch wrong activity sequencing / input wiring; this does.
+ sub = await _create_ai_subscription(team, user)
+ await sync_to_async(Subscription.objects.filter(pk=sub.id).update)(
+ next_delivery_date=datetime(2022, 2, 2, 8, 0, tzinfo=ZoneInfo("UTC"))
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=settings.TEMPORAL_TASK_QUEUE,
+ workflows=[ScheduleAllSubscriptionsWorkflow, ProcessSubscriptionWorkflow, ProcessAISubscriptionWorkflow],
+ activities=SUBSCRIPTION_SCHEDULE_ACTIVITIES,
+ interceptors=[SloInterceptor()],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ activity_executor=ThreadPoolExecutor(max_workers=50),
+ debug_mode=True,
+ ):
+ await env.client.execute_workflow(
+ ScheduleAllSubscriptionsWorkflow.run,
+ ScheduleAllSubscriptionsWorkflowInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=settings.TEMPORAL_TASK_QUEUE,
+ )
+
+ # The LLM ran once, the report was shipped, and the delivery record landed COMPLETED.
+ mock_generate.assert_called_once()
+ mock_send_email.assert_called_once()
+ assert mock_send_email.call_args.kwargs["markdown"] == "# AI Report"
+ delivery = await sync_to_async(SubscriptionDelivery.objects.filter(subscription=sub).latest)("created_at")
+ assert delivery.status == SubscriptionDelivery.Status.COMPLETED
+
+
+async def test_fetch_due_subscriptions_includes_ai_with_resource_type(team, user):
+ sub = await _create_ai_subscription(team, user)
+ # `Subscription.save` recomputes next_delivery_date from the rrule, so write a past
+ # value via `.update()` to make it due.
+ await sync_to_async(Subscription.objects.filter(pk=sub.id).update)(
+ next_delivery_date=datetime(2020, 1, 1, tzinfo=ZoneInfo("UTC"))
+ )
+
+ fetched = await ActivityEnvironment().run(
+ fetch_due_subscriptions_activity, FetchDueSubscriptionsActivityInputs(buffer_minutes=15)
+ )
+
+ match = next((s for s in fetched if s.subscription_id == sub.id), None)
+ assert match is not None, "due AI subscription must be picked up by the shared scheduler fetch"
+ assert match.resource_type == Subscription.ResourceType.AI_PROMPT
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 1aa10640f472..8494dd852d32 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -181,15 +181,26 @@ class Subscription(ModelActivityMixin, models.Model):
kwargs["update_fields"].append("next_delivery_date")
super().save(*args, **kwargs)
+ @classmethod
+ def derive_resource_type(cls, insight_id: int | None, dashboard_id: int | None, prompt: str | None) -> str:
+ # Shared by the `resource_type` property and the scheduler's `.values()` fan-out
+ # (which has field dicts, not model instances) so the derivation stays single-source.
+ if insight_id:
+ return cls.ResourceType.INSIGHT
+ if dashboard_id:
+ return cls.ResourceType.DASHBOARD
+ if prompt:
+ return cls.ResourceType.AI_PROMPT
+ raise ValueError("Subscription has no insight, dashboard, or prompt to derive a resource type from")
+
@property
def resource_type(self) -> str:
- if self.insight_id:
- return self.ResourceType.INSIGHT
- if self.dashboard_id:
- return self.ResourceType.DASHBOARD
- if self.prompt:
- return self.ResourceType.AI_PROMPT
- raise ValueError(f"Subscription {self.pk} has no insight, dashboard, or prompt to derive a resource type from")
+ return self.derive_resource_type(self.insight_id, self.dashboard_id, self.prompt)
+
+ @property
+ def _has_resource(self) -> bool:
+ # Guards url/resource_info from resource_type's raise on a relationless sub.
+ return bool(self.insight_id or self.dashboard_id or self.prompt)
@staticmethod
def _build_rrule(
@@ -267,7 +278,7 @@ class Subscription(ModelActivityMixin, models.Model):
@property
def url(self) -> str | None:
- if not (self.insight_id or self.dashboard_id or self.prompt):
+ if not self._has_resource:
return None
match self.resource_type:
case self.ResourceType.INSIGHT if self.insight:
@@ -280,7 +291,7 @@ class Subscription(ModelActivityMixin, models.Model):
@property
def resource_info(self) -> Optional[SubscriptionResourceInfo]:
- if not (self.insight_id or self.dashboard_id or self.prompt):
+ if not self._has_resource:
return None
match self.resource_type:
case self.ResourceType.INSIGHT if self.insight:
diff --git a/products/exports/backend/temporal/subscriptions/__init__.py b/products/exports/backend/temporal/subscriptions/__init__.py
index 39643ec1cf1d..ccb87e9dfbec 100644
--- a/products/exports/backend/temporal/subscriptions/__init__.py
+++ b/products/exports/backend/temporal/subscriptions/__init__.py
@@ -7,20 +7,28 @@ from products.exports.backend.temporal.subscriptions.activities import (
update_delivery_record,
validate_subscription_for_delivery,
)
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_report
from products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights
from products.exports.backend.temporal.subscriptions.workflows import (
HandleSubscriptionValueChangeWorkflow,
+ ProcessAISubscriptionWorkflow,
ProcessSubscriptionWorkflow,
ScheduleAllSubscriptionsWorkflow,
)
-WORKFLOWS = [ScheduleAllSubscriptionsWorkflow, HandleSubscriptionValueChangeWorkflow, ProcessSubscriptionWorkflow]
+WORKFLOWS = [
+ ScheduleAllSubscriptionsWorkflow,
+ HandleSubscriptionValueChangeWorkflow,
+ ProcessSubscriptionWorkflow,
+ ProcessAISubscriptionWorkflow,
+]
ACTIVITIES = [
fetch_due_subscriptions_activity,
validate_subscription_for_delivery,
create_export_assets,
deliver_subscription,
+ generate_ai_subscription_report,
advance_next_delivery_date,
create_delivery_record,
update_delivery_record,
diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.py
index d1cda9a87ea9..9a9cf44b7952 100644
--- a/products/exports/backend/temporal/subscriptions/activities.py
+++ b/products/exports/backend/temporal/subscriptions/activities.py
@@ -4,19 +4,24 @@ import typing
import datetime as dt
from datetime import datetime
+from django.db.models import Q
from django.utils import timezone as tz
import temporalio.activity
-from slack_sdk.errors import SlackApiError
from structlog import get_logger
from temporalio.exceptions import ApplicationError
-from posthog.exceptions_capture import capture_exception
from posthog.sync import database_sync_to_async
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.exports.backend.models.exported_asset import ExportedAsset
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import _deliver_ai_subscription
+from products.exports.backend.temporal.subscriptions.delivery_common import (
+ auto_disable_and_return,
+ deliver_email,
+ deliver_slack,
+)
from products.exports.backend.temporal.subscriptions.insight_snapshot import (
build_initial_content_snapshot,
build_insight_delivery_snapshot,
@@ -35,20 +40,14 @@ from products.exports.backend.temporal.subscriptions.types import (
)
from products.product_analytics.backend.models.insight import Insight
-from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_event
+from ee.tasks.subscriptions import _capture_delivery_failed_event
from ee.tasks.subscriptions.auto_disable import (
- SLACK_DISCONNECTED_DISABLE_REASON,
- SLACK_PERMISSION_REVOKED_DISABLE_REASON,
UNSUPPORTED_TARGET_DISABLE_REASON,
- DisableReason,
disable_invalid_subscription,
get_subscription_disable_reason,
)
from ee.tasks.subscriptions.email_subscriptions import send_email_subscription_report
-from ee.tasks.subscriptions.slack_subscriptions import (
- get_slack_integration_for_team,
- send_slack_message_with_integration_async,
-)
+from ee.tasks.subscriptions.slack_subscriptions import send_slack_message_with_integration_async
LOGGER = get_logger(__name__)
@@ -100,11 +99,18 @@ async def fetch_due_subscriptions_activity(inputs: FetchDueSubscriptionsActivity
if sub["created_by__distinct_id"]
else str(sub["team_id"]),
next_delivery_date=sub["next_delivery_date"].isoformat() if sub["next_delivery_date"] else None,
+ resource_type=Subscription.derive_resource_type(sub["insight_id"], sub["dashboard_id"], sub["prompt"]),
)
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")
+ # Skip relationless subs — derive_resource_type raises on them, and one bad row would fail the whole batch.
+ .exclude(
+ Q(insight_id__isnull=True) & Q(dashboard_id__isnull=True) & (Q(prompt__isnull=True) | Q(prompt=""))
+ )
+ .values(
+ "id", "team_id", "created_by__distinct_id", "next_delivery_date", "insight_id", "dashboard_id", "prompt"
+ )
]
subscriptions = await get_subscriptions()
@@ -172,6 +178,7 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExport
)
# 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",
@@ -281,27 +288,6 @@ 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.defn
async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubscriptionResult:
recipient_results: list[RecipientResult] = []
@@ -325,8 +311,20 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubs
target_type=subscription.target_type,
asset_count=len(inputs.exported_asset_ids),
is_new=inputs.is_new_subscription_target,
+ 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)
+
+
+async def _deliver_insight_dashboard_subscription(
+ subscription: Subscription,
+ inputs: DeliverSubscriptionInputs,
+ recipient_results: list[RecipientResult],
+) -> DeliverSubscriptionResult:
if (
get_subscription_disable_reason(subscription.target_type, subscription.integration_id)
== UNSUPPORTED_TARGET_DISABLE_REASON
@@ -336,7 +334,7 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubs
subscription_id=inputs.subscription_id,
target_type=subscription.target_type,
)
- return await _auto_disable_and_return(subscription, UNSUPPORTED_TARGET_DISABLE_REASON, recipient_results)
+ return await auto_disable_and_return(subscription, UNSUPPORTED_TARGET_DISABLE_REASON, recipient_results)
assets_by_id = await database_sync_to_async(
lambda: {
@@ -371,95 +369,26 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubs
_capture_delivery_failed_event(subscription, Exception(NO_ASSETS_REASON))
return DeliverSubscriptionResult(recipient_results=recipient_results)
- if subscription.target_type == "email":
- emails = subscription.target_value.split(",")
- await LOGGER.ainfo(
- "deliver_subscription.sending_email",
- subscription_id=inputs.subscription_id,
- recipient_count=len(emails),
- )
- if inputs.is_new_subscription_target:
- previous_emails = inputs.previous_value.split(",") if inputs.previous_value else []
- emails = list(set(emails) - set(previous_emails))
-
- last_error: Exception | None = None
- success_count = 0
- for email in emails:
- try:
- await database_sync_to_async(send_email_subscription_report, thread_sensitive=False)(
- email,
- subscription,
- assets,
- invite_message=inputs.invite_message or "" if inputs.is_new_subscription_target else None,
- total_asset_count=inputs.total_insight_count,
- send_async=False,
- change_summary=inputs.change_summary,
- summary_skipped_over_budget=inputs.summary_skipped_over_budget,
- )
- success_count += 1
- recipient_results.append(RecipientResult(recipient=email, status="success"))
- except Exception as e:
- _capture_delivery_failed_event(subscription, e)
- LOGGER.error(
- "deliver_subscription.email_failed",
- subscription_id=subscription.id,
- email=email,
- next_delivery_date=subscription.next_delivery_date,
- destination=subscription.target_type,
- exc_info=True,
- )
- capture_exception(e)
- last_error = e
- recipient_results.append(
- RecipientResult(
- recipient=email,
- status="failed",
- error={"message": str(e), "type": type(e).__name__},
- )
- )
+ if subscription.target_type == Subscription.SubscriptionTarget.EMAIL:
- await LOGGER.ainfo(
- "deliver_subscription.email_complete",
- subscription_id=inputs.subscription_id,
- success_count=success_count,
- total_count=len(emails),
- )
+ async def _send_email(email: str) -> None:
+ await database_sync_to_async(send_email_subscription_report, thread_sensitive=False)(
+ email,
+ subscription,
+ assets,
+ invite_message=inputs.invite_message or "" if inputs.is_new_subscription_target else None,
+ total_asset_count=inputs.total_insight_count,
+ send_async=False,
+ change_summary=inputs.change_summary,
+ summary_skipped_over_budget=inputs.summary_skipped_over_budget,
+ )
- # Only retry if ALL recipients failed — partial success is acceptable
- # to avoid duplicate sends to already-delivered recipients
- if last_error is not None and success_count == 0:
- raise last_error
-
- elif subscription.target_type == "slack":
- try:
- integration = subscription.integration
- if integration is None:
- integration = await database_sync_to_async(get_slack_integration_for_team, thread_sensitive=False)(
- subscription.team_id
- )
- elif integration.kind != "slack":
- LOGGER.warn(
- "deliver_subscription.invalid_integration_kind",
- subscription_id=subscription.id,
- integration_id=integration.id,
- kind=integration.kind,
- )
- integration = await database_sync_to_async(get_slack_integration_for_team, thread_sensitive=False)(
- subscription.team_id
- )
-
- if not integration:
- LOGGER.warning(
- "deliver_subscription.no_slack_integration",
- subscription_id=inputs.subscription_id,
- )
- # 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)
- delivery_result = await send_slack_message_with_integration_async(
+ result = await deliver_email(subscription, inputs, recipient_results, _send_email)
+ elif subscription.target_type == Subscription.SubscriptionTarget.SLACK:
+ result = await deliver_slack(
+ subscription,
+ recipient_results,
+ lambda integration: send_slack_message_with_integration_async(
integration,
subscription,
assets,
@@ -467,60 +396,20 @@ async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubs
is_new_subscription=inputs.is_new_subscription_target,
change_summary=inputs.change_summary,
summary_skipped_over_budget=inputs.summary_skipped_over_budget,
- )
-
- if delivery_result.is_complete_success:
- await LOGGER.ainfo(
- "deliver_subscription.slack_sent",
- subscription_id=inputs.subscription_id,
- )
- recipient_results.append(RecipientResult(recipient=subscription.target_value, status="success"))
- elif delivery_result.is_partial_failure:
- await LOGGER.awarning(
- "deliver_subscription.slack_partial_failure",
- subscription_id=inputs.subscription_id,
- failed_thread_count=len(delivery_result.failed_thread_message_indices),
- total_thread_count=delivery_result.total_thread_messages,
- )
- recipient_results.append(
- RecipientResult(
- recipient=subscription.target_value,
- status="partial",
- error={
- "message": f"{len(delivery_result.failed_thread_message_indices)} thread message(s) failed",
- "type": "partial_thread_failure",
- },
- )
- )
-
- except ApplicationError:
- raise
- except Exception as e:
- slack_error_code = e.response.get("error") if isinstance(e, SlackApiError) else None
- is_user_config_error = slack_error_code in SLACK_USER_CONFIG_ERRORS
- _capture_delivery_failed_event(subscription, e)
- LOGGER.error(
- "deliver_subscription.slack_failed",
- subscription_id=subscription.id,
- next_delivery_date=subscription.next_delivery_date,
- destination=subscription.target_type,
- exc_info=True,
- )
- capture_exception(e)
- if is_user_config_error:
- # Won't self-heal without user action — auto-disable so the subscription
- # stops re-firing every cycle.
- return await _auto_disable_and_return(
- subscription, SLACK_PERMISSION_REVOKED_DISABLE_REASON, recipient_results
- )
- raise # Transient Slack errors — let Temporal retry
+ ),
+ )
+ else:
+ raise ApplicationError(
+ f"Subscription delivery reached an unsupported target {subscription.target_type!r}",
+ non_retryable=True,
+ )
await LOGGER.ainfo(
"deliver_subscription.completed",
subscription_id=inputs.subscription_id,
target_type=subscription.target_type,
)
- return DeliverSubscriptionResult(recipient_results=recipient_results)
+ return result
@temporalio.activity.defn
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
new file mode 100644
index 000000000000..5605d5fc23c1
--- /dev/null
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -0,0 +1,169 @@
+import uuid
+
+import temporalio.activity
+from structlog import get_logger
+from temporalio.exceptions import ApplicationError
+
+from posthog.sync import database_sync_to_async
+
+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
+from products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (
+ generate_ai_subscription_markdown,
+ send_email_ai_subscription_report,
+ send_slack_ai_subscription_report,
+)
+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
+from products.exports.backend.temporal.subscriptions.delivery_common import (
+ auto_disable_and_return,
+ deliver_email,
+ deliver_slack,
+)
+from products.exports.backend.temporal.subscriptions.types import (
+ DeliverSubscriptionInputs,
+ DeliverSubscriptionResult,
+ GenerateAIReportInputs,
+ GenerateAIReportResult,
+ RecipientResult,
+)
+
+from ee.tasks.subscriptions import _capture_delivery_failed_event
+from ee.tasks.subscriptions.auto_disable import AI_CONSENT_REVOKED_DISABLE_REASON, AI_PROMPT_INVALID_DISABLE_REASON
+
+LOGGER = get_logger(__name__)
+
+# `SubscriptionDelivery.content_snapshot` key the AI report markdown is written under by
+# `generate_ai_subscription_report` and read back by `_deliver_ai_subscription`. The markdown
+# can exceed Temporal's ~2 MiB payload cap, so it travels through Postgres by reference rather
+# than on the wire — the same pattern insight snapshots use.
+AI_REPORT_SNAPSHOT_KEY = "ai_report"
+
+
+async def _load_ai_report(delivery_id: uuid.UUID) -> str | None:
+ @database_sync_to_async(thread_sensitive=False)
+ def _read() -> str | None:
+ # DoesNotExist is tolerated here (read side): a missing row just means "no report yet".
+ try:
+ snapshot = SubscriptionDelivery.objects.values_list("content_snapshot", flat=True).get(pk=delivery_id)
+ except SubscriptionDelivery.DoesNotExist:
+ return None
+ if not isinstance(snapshot, dict):
+ return None
+ report = snapshot.get(AI_REPORT_SNAPSHOT_KEY)
+ return report if isinstance(report, str) and report else None
+
+ return await _read()
+
+
+async def _persist_ai_report(delivery_id: uuid.UUID, markdown: str) -> None:
+ @database_sync_to_async(thread_sensitive=False)
+ def _write() -> None:
+ # No DoesNotExist guard: create_delivery_record always writes this row before
+ # generation runs, so a missing row is a wiring bug — let it raise loudly.
+ delivery = SubscriptionDelivery.objects.get(pk=delivery_id)
+ delivery.content_snapshot = {**(delivery.content_snapshot or {}), AI_REPORT_SNAPSHOT_KEY: markdown}
+ delivery.save(update_fields=["content_snapshot", "last_updated_at"])
+
+ await _write()
+
+
+async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> GenerateAIReportResult:
+ # The "decide what to send" phase, split from delivery so the LLM runs once up front with
+ # its own retry policy. Terminal failures (consent revoked, prompt invalid) auto-disable and
+ # return aborted=True; transient errors bubble up for the activity's Temporal retry.
+ subscription = await database_sync_to_async(
+ Subscription.objects.select_related("created_by", "team", "team__organization").get,
+ thread_sensitive=False,
+ )(pk=inputs.subscription_id)
+
+ # Idempotency on Temporal redispatch: if a prior attempt already produced the report,
+ # don't re-bill the LLM — the point of the generate -> deliver split is one LLM run.
+ if await _load_ai_report(inputs.delivery_id) is not None:
+ await LOGGER.ainfo("generate_ai_subscription_report.already_generated", subscription_id=subscription.id)
+ return GenerateAIReportResult(aborted=False)
+
+ # Consent is gated once here, before any LLM cost — creation-time gates don't catch an
+ # org that revokes AI-data-processing approval later. Auto-disable so it stops re-firing.
+ if not subscription.team.organization.is_ai_data_processing_approved:
+ LOGGER.warning("generate_ai_subscription_report.consent_revoked", subscription_id=subscription.id)
+ aborted = await auto_disable_and_return(subscription, AI_CONSENT_REVOKED_DISABLE_REASON, [])
+ return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results)
+
+ try:
+ markdown = await generate_ai_subscription_markdown(subscription)
+ except PromptRejectedError as exc:
+ # Structurally permanent: no creator, prompt now fails sanitization, or the
+ # planner returned a malformed plan. Re-firing wastes LLM tokens every cycle.
+ LOGGER.warning(
+ "generate_ai_subscription_report.prompt_rejected",
+ subscription_id=subscription.id,
+ reason=str(exc),
+ )
+ _capture_delivery_failed_event(subscription, exc)
+ # Seed a recipient result with the exception detail first — it carries planner
+ # context that the disable reason (appended next by `auto_disable_and_return`)
+ # doesn't.
+ recipient_results = [
+ RecipientResult(
+ recipient=subscription.target_value,
+ status="failed",
+ error={"message": str(exc), "type": "PromptRejectedError"},
+ )
+ ]
+ aborted = await auto_disable_and_return(subscription, AI_PROMPT_INVALID_DISABLE_REASON, recipient_results)
+ return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results)
+
+ await _persist_ai_report(inputs.delivery_id, markdown)
+ return GenerateAIReportResult(aborted=False)
+
+
+async def _deliver_ai_subscription(
+ subscription: Subscription,
+ inputs: DeliverSubscriptionInputs,
+ recipient_results: list[RecipientResult],
+) -> DeliverSubscriptionResult:
+ # Ships the report generate_ai_subscription_report already produced (read back from the
+ # delivery row) — no LLM work here. Transient send errors retry; terminal Slack errors auto-disable.
+ if inputs.delivery_id is None:
+ # The AI workflow always creates the delivery row and runs generation before
+ # delivery, so a missing reference is a wiring bug, not a runtime state.
+ raise ApplicationError(f"AI delivery for subscription {subscription.id} has no delivery_id", non_retryable=True)
+
+ markdown = await _load_ai_report(inputs.delivery_id)
+ if markdown is None:
+ # Generation persists the report before delivery is scheduled, so a missing report
+ # means the row was lost. Non-retryable: re-running *delivery* can't regenerate the
+ # report, so retrying just burns attempts — fail loud rather than ship an empty report.
+ raise ApplicationError(
+ f"AI report missing for subscription {subscription.id} (delivery {inputs.delivery_id})",
+ non_retryable=True,
+ )
+
+ if subscription.target_type == Subscription.SubscriptionTarget.EMAIL:
+ # Dedup key for MessagingRecord: stable across this run's retries, unique per run so a re-test re-sends.
+ workflow_run_id = temporalio.activity.info().workflow_run_id
+ if workflow_run_id is None:
+ raise ApplicationError("AI email delivery requires a workflow run id", non_retryable=True)
+
+ async def _send_email(email: str) -> None:
+ await database_sync_to_async(send_email_ai_subscription_report, thread_sensitive=False)(
+ email=email,
+ subscription=subscription,
+ markdown=markdown,
+ delivery_run_id=workflow_run_id,
+ )
+
+ return await deliver_email(subscription, inputs, recipient_results, _send_email)
+ if subscription.target_type == Subscription.SubscriptionTarget.SLACK:
+ return await deliver_slack(
+ subscription,
+ recipient_results,
+ lambda integration: send_slack_ai_subscription_report(
+ subscription=subscription, markdown=markdown, integration=integration
+ ),
+ )
+ # `validate_subscription_for_delivery` auto-disables unsupported targets up front,
+ # so reaching here means an invariant was violated.
+ raise ApplicationError(
+ f"AI delivery reached an unsupported target {subscription.target_type!r}", non_retryable=True
+ )
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 47a7fd5885f5..067812a9d300 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -22,7 +22,6 @@ from ee.tasks.subscriptions.slack_subscriptions import (
SlackDeliveryResult,
SlackMessageData,
deliver_slack_message_data,
- get_slack_integration_for_team,
)
logger = structlog.get_logger(__name__)
@@ -209,30 +208,6 @@ def send_email_ai_subscription_report(
message.send(send_async=False)
-class SlackIntegrationMissingError(RuntimeError):
- pass
-
-
-def _resolve_slack_integration(subscription: Subscription) -> Integration:
- # prefer the explicitly attached integration, else the team-wide first match; raise on missing
- integration = subscription.integration
- if integration is not None and integration.kind != "slack":
- logger.warning(
- "ai_subscription.slack_invalid_integration_kind",
- subscription_id=subscription.id,
- integration_id=integration.id,
- kind=integration.kind,
- )
- integration = None
- if integration is None:
- integration = get_slack_integration_for_team(subscription.team_id)
- if not integration:
- raise SlackIntegrationMissingError(
- f"No Slack integration available for subscription {subscription.id} (team {subscription.team_id})"
- )
- return integration
-
-
def _build_ai_slack_message(subscription: Subscription, markdown: str) -> SlackMessageData:
utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"
channel = subscription.target_value.split("|")[0]
@@ -279,9 +254,8 @@ async def send_slack_ai_subscription_report(
*,
subscription: Subscription,
markdown: str,
+ integration: Integration,
) -> SlackDeliveryResult:
- # resolving the integration touches the ORM, so it must run off the event loop
- integration = await database_sync_to_async(_resolve_slack_integration, thread_sensitive=False)(subscription)
message_data = _build_ai_slack_message(subscription, markdown)
return await deliver_slack_message_data(integration, subscription, message_data)
diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.py
new file mode 100644
index 000000000000..c82271df8676
--- /dev/null
+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py
@@ -0,0 +1,176 @@
+from collections.abc import Awaitable, Callable
+
+from slack_sdk.errors import SlackApiError
+from structlog import get_logger
+from temporalio.exceptions import ApplicationError
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.integration import Integration
+from posthog.sync import database_sync_to_async
+
+from products.exports.backend.models.subscription import Subscription
+from products.exports.backend.temporal.subscriptions.types import (
+ DeliverSubscriptionInputs,
+ DeliverSubscriptionResult,
+ RecipientResult,
+)
+
+from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_event
+from ee.tasks.subscriptions.auto_disable import (
+ SLACK_DISCONNECTED_DISABLE_REASON,
+ SLACK_PERMISSION_REVOKED_DISABLE_REASON,
+ DisableReason,
+ disable_invalid_subscription,
+)
+from ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult, get_slack_integration_for_team
+
+LOGGER = get_logger(__name__)
+
+
+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. Shared by the insight/dashboard and AI delivery paths."""
+ 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)
+
+
+async def deliver_email(
+ subscription: Subscription,
+ inputs: DeliverSubscriptionInputs,
+ recipient_results: list[RecipientResult],
+ send_one: Callable[[str], Awaitable[None]],
+) -> DeliverSubscriptionResult:
+ """Send to each recipient via `send_one`. Partial success is kept; only an all-failed run
+ raises, 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()}
+ emails = [e for e in emails if e not in previous]
+
+ await LOGGER.ainfo(
+ "deliver_subscription.sending_email", subscription_id=subscription.id, recipient_count=len(emails)
+ )
+
+ success_count = 0
+ last_error: Exception | None = None
+ for email in emails:
+ try:
+ await send_one(email)
+ recipient_results.append(RecipientResult(recipient=email, status="success", error=None))
+ success_count += 1
+ except Exception as exc:
+ LOGGER.error(
+ "deliver_subscription.email_failed",
+ subscription_id=subscription.id,
+ email=email,
+ next_delivery_date=subscription.next_delivery_date,
+ destination=subscription.target_type,
+ exc_info=True,
+ )
+ capture_exception(exc)
+ _capture_delivery_failed_event(subscription, exc)
+ recipient_results.append(
+ RecipientResult(
+ recipient=email, status="failed", error={"message": str(exc), "type": type(exc).__name__}
+ )
+ )
+ last_error = exc
+
+ await LOGGER.ainfo(
+ "deliver_subscription.email_complete",
+ subscription_id=subscription.id,
+ success_count=success_count,
+ total_count=len(emails),
+ )
+
+ if last_error is not None and success_count == 0:
+ raise last_error
+ return DeliverSubscriptionResult(recipient_results=recipient_results)
+
+
+def _resolve_slack_integration(subscription: Subscription) -> Integration | None:
+ integration = subscription.integration
+ if integration is not None and integration.kind != "slack":
+ LOGGER.warning(
+ "deliver_subscription.invalid_integration_kind",
+ subscription_id=subscription.id,
+ integration_id=integration.id,
+ kind=integration.kind,
+ )
+ integration = None
+ if integration is None:
+ integration = get_slack_integration_for_team(subscription.team_id)
+ return integration
+
+
+async def deliver_slack(
+ subscription: Subscription,
+ recipient_results: list[RecipientResult],
+ send: Callable[[Integration], Awaitable[SlackDeliveryResult]],
+) -> DeliverSubscriptionResult:
+ """A missing integration or a permanent Slack config error auto-disables the subscription;
+ transient Slack errors raise so Temporal retries."""
+ integration = await database_sync_to_async(_resolve_slack_integration, thread_sensitive=False)(subscription)
+ if integration is None:
+ LOGGER.warning("deliver_subscription.no_slack_integration", subscription_id=subscription.id)
+ return await auto_disable_and_return(subscription, SLACK_DISCONNECTED_DISABLE_REASON, recipient_results)
+
+ LOGGER.info("deliver_subscription.sending_slack_message", subscription_id=subscription.id)
+ try:
+ result = await send(integration)
+ except ApplicationError:
+ raise
+ except Exception as exc:
+ slack_error_code = exc.response.get("error") if isinstance(exc, SlackApiError) else None
+ _capture_delivery_failed_event(subscription, exc)
+ LOGGER.error(
+ "deliver_subscription.slack_failed",
+ subscription_id=subscription.id,
+ slack_error=slack_error_code,
+ next_delivery_date=subscription.next_delivery_date,
+ destination=subscription.target_type,
+ exc_info=True,
+ )
+ capture_exception(exc)
+ if slack_error_code in SLACK_USER_CONFIG_ERRORS:
+ # Won't self-heal without user action — auto-disable so it stops re-firing.
+ return await auto_disable_and_return(
+ subscription, SLACK_PERMISSION_REVOKED_DISABLE_REASON, recipient_results
+ )
+ raise # Transient Slack errors — let Temporal retry
+
+ if result.is_complete_success:
+ await LOGGER.ainfo("deliver_subscription.slack_sent", subscription_id=subscription.id)
+ recipient_results.append(RecipientResult(recipient=subscription.target_value, status="success", error=None))
+ elif result.is_partial_failure:
+ await LOGGER.awarning(
+ "deliver_subscription.slack_partial_failure",
+ subscription_id=subscription.id,
+ failed_thread_count=len(result.failed_thread_message_indices),
+ total_thread_count=result.total_thread_messages,
+ )
+ recipient_results.append(
+ RecipientResult(
+ recipient=subscription.target_value,
+ status="partial",
+ error={
+ "message": f"{len(result.failed_thread_message_indices)} thread message(s) failed",
+ "type": "partial_thread_failure",
+ },
+ )
+ )
+ return DeliverSubscriptionResult(recipient_results=recipient_results)
diff --git a/products/exports/backend/temporal/subscriptions/retry_policy.py b/products/exports/backend/temporal/subscriptions/retry_policy.py
new file mode 100644
index 000000000000..c23c962f1eef
--- /dev/null
+++ b/products/exports/backend/temporal/subscriptions/retry_policy.py
@@ -0,0 +1,21 @@
+import datetime as dt
+
+from temporalio.common import RetryPolicy
+
+SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY = RetryPolicy(
+ initial_interval=dt.timedelta(seconds=5),
+ maximum_interval=dt.timedelta(minutes=1),
+ maximum_attempts=3,
+)
+
+SUBSCRIPTION_VALIDATE_RETRY_POLICY = RetryPolicy(
+ initial_interval=dt.timedelta(seconds=5),
+ maximum_interval=dt.timedelta(seconds=30),
+ maximum_attempts=3,
+)
+
+SUBSCRIPTION_DELIVER_RETRY_POLICY = RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(minutes=5),
+ maximum_attempts=5,
+)
diff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.py
index 593b7dfe40f3..62b1af2f3834 100644
--- a/products/exports/backend/temporal/subscriptions/types.py
+++ b/products/exports/backend/temporal/subscriptions/types.py
@@ -20,6 +20,11 @@ class DeliveryStatus:
SKIPPED = "skipped"
+# 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"
+
+
class SubscriptionTriggerType:
"""How a subscription delivery was triggered.
@@ -38,6 +43,9 @@ class SubscriptionInfo:
team_id: int
distinct_id: str
next_delivery_date: typing.Optional[str] = None
+ # Lets the scheduler fan out AI-prompt subscriptions to ProcessAISubscriptionWorkflow
+ # and everything else to ProcessSubscriptionWorkflow.
+ resource_type: str = ""
@dataclasses.dataclass
@@ -89,6 +97,9 @@ class DeliverSubscriptionInputs:
invite_message: typing.Optional[str] = None
change_summary: typing.Optional[str] = None
summary_skipped_over_budget: bool = False
+ # The delivery row to write outcomes onto. AI deliveries also read the generated
+ # report markdown back from it (kept off the Temporal wire, ~2 MiB cap).
+ delivery_id: typing.Optional[uuid.UUID] = None
@dataclasses.dataclass
@@ -100,6 +111,9 @@ class ProcessSubscriptionWorkflowInputs:
invite_message: typing.Optional[str] = None
trigger_type: str = SubscriptionTriggerType.TARGET_CHANGE
scheduled_at: typing.Optional[str] = None
+ # Lets HandleSubscriptionValueChangeWorkflow route AI-prompt subs to
+ # ProcessAISubscriptionWorkflow. Passed by the API from the loaded instance.
+ resource_type: str = ""
@dataclasses.dataclass
@@ -120,6 +134,7 @@ class TrackedSubscriptionInputs:
slo: SloConfig | None = None
trigger_type: str = SubscriptionTriggerType.TARGET_CHANGE
scheduled_at: typing.Optional[str] = None
+ resource_type: str = ""
RecipientResultStatus = typing.Literal["success", "failed", "partial"]
@@ -137,6 +152,24 @@ class DeliverSubscriptionResult:
recipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)
+class GenerateAIReportInputs:
+ subscription_id: int
+ # The report markdown is written onto this SubscriptionDelivery row rather than
+ # returned on the wire — it can exceed Temporal's ~2 MiB payload cap.
+ delivery_id: uuid.UUID
+
+
+class GenerateAIReportResult:
+ """Outcome of the generation phase. `aborted` signals a terminal pre-delivery
+ failure (consent revoked, prompt invalid) that already auto-disabled the
+ subscription; the workflow records `recipient_results` as FAILED and skips delivery."""
+
+ aborted: bool = False
+ recipient_results: list[RecipientResult] = dataclasses.field(default_factory=list)
+
+
@dataclasses.dataclass
class SubscriptionAbortInfo:
"""Returned by `validate_subscription_for_delivery` when the workflow should abort.
diff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.py
index a38e543336ca..e46fa6af480e 100644
--- a/products/exports/backend/temporal/subscriptions/workflows.py
+++ b/products/exports/backend/temporal/subscriptions/workflows.py
@@ -3,6 +3,8 @@ import uuid
import asyncio
import datetime as dt
import dataclasses
+from collections.abc import Callable, Coroutine
+from typing import Any
import temporalio.common
import temporalio.workflow
@@ -30,15 +32,24 @@ from products.exports.backend.temporal.subscriptions.activities import (
update_delivery_record,
validate_subscription_for_delivery,
)
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_report
+from products.exports.backend.temporal.subscriptions.retry_policy import (
+ SUBSCRIPTION_DELIVER_RETRY_POLICY,
+ SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
+ SUBSCRIPTION_VALIDATE_RETRY_POLICY,
+)
from products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights
from products.exports.backend.temporal.subscriptions.types import (
+ AI_PROMPT_RESOURCE_TYPE,
CreateDeliveryRecordInputs,
CreateExportAssetsInputs,
DeliverSubscriptionInputs,
DeliverSubscriptionResult,
DeliveryStatus,
FetchDueSubscriptionsActivityInputs,
+ GenerateAIReportInputs,
ProcessSubscriptionWorkflowInputs,
+ RecipientResult,
ScheduleAllSubscriptionsWorkflowInputs,
SnapshotInsightsInputs,
SubscriptionInfo,
@@ -48,6 +59,13 @@ from products.exports.backend.temporal.subscriptions.types import (
)
+def _to_recipient_dicts(recipient_results: list[RecipientResult]) -> list[dict]:
+ return [
+ {"recipient": r.recipient, "status": r.status, **({"error": r.error} if r.error else {})}
+ for r in recipient_results
+ ]
+
+
def _build_outcome_assets(
asset_ids: list[int],
export_results: list[ExportAssetResult | BaseException],
@@ -107,23 +125,34 @@ class ScheduleAllSubscriptionsWorkflow(PostHogWorkflow):
# share the same ID, so a still-running child rejects the duplicate start.
tasks = []
for sub in subscription_infos:
- task = temporalio.workflow.execute_child_workflow(
- ProcessSubscriptionWorkflow.run,
- TrackedSubscriptionInputs(
- subscription_id=sub.subscription_id,
+ tracked = TrackedSubscriptionInputs(
+ subscription_id=sub.subscription_id,
+ team_id=sub.team_id,
+ distinct_id=sub.distinct_id,
+ trigger_type=SubscriptionTriggerType.SCHEDULED,
+ scheduled_at=sub.next_delivery_date,
+ resource_type=sub.resource_type,
+ slo=SloConfig(
+ operation=SloOperation.SUBSCRIPTION_DELIVERY,
+ area=SloArea.ANALYTIC_PLATFORM,
team_id=sub.team_id,
+ resource_id=str(sub.subscription_id),
distinct_id=sub.distinct_id,
- trigger_type=SubscriptionTriggerType.SCHEDULED,
- scheduled_at=sub.next_delivery_date,
- slo=SloConfig(
- operation=SloOperation.SUBSCRIPTION_DELIVERY,
- area=SloArea.ANALYTIC_PLATFORM,
- team_id=sub.team_id,
- resource_id=str(sub.subscription_id),
- distinct_id=sub.distinct_id,
- ),
),
- id=f"process-subscription-{sub.subscription_id}",
+ )
+ # AI-prompt subs run a dedicated workflow; distinct child-ID prefixes keep the
+ # overlapping-duplicate guarantee per type.
+ workflow: Callable[..., Coroutine[Any, Any, None]]
+ if sub.resource_type == AI_PROMPT_RESOURCE_TYPE:
+ workflow = ProcessAISubscriptionWorkflow.run
+ child_id = f"process-ai-subscription-{sub.subscription_id}"
+ else:
+ workflow = ProcessSubscriptionWorkflow.run
+ child_id = f"process-subscription-{sub.subscription_id}"
+ task = temporalio.workflow.execute_child_workflow(
+ workflow,
+ tracked,
+ id=child_id,
parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
execution_timeout=dt.timedelta(hours=2),
)
@@ -196,11 +225,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
idempotency_key=str(temporalio.workflow.uuid4()),
),
start_to_close_timeout=dt.timedelta(minutes=2),
- retry_policy=temporalio.common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=5),
- maximum_interval=dt.timedelta(minutes=1),
- maximum_attempts=3,
- ),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
)
# Validate up-front: if the subscription is already disabled or its target
@@ -210,11 +235,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
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,
- ),
+ retry_policy=SUBSCRIPTION_VALIDATE_RETRY_POLICY,
)
if abort_info is not None:
# Just-disabled → FAILED with reason. Already-disabled (no failed_recipient) → SKIPPED default.
@@ -331,22 +352,11 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
summary_skipped_over_budget=summary_skipped_over_budget,
),
start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=temporalio.common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=10),
- maximum_interval=dt.timedelta(minutes=5),
- maximum_attempts=5,
- ),
+ retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,
)
# Capture per-recipient results for the delivery record
- delivery_recipient_results = [
- {
- "recipient": r.recipient,
- "status": r.status,
- **({"error": r.error} if r.error else {}),
- }
- for r in deliver_result.recipient_results
- ]
+ delivery_recipient_results = _to_recipient_dicts(deliver_result.recipient_results)
final_status = DeliveryStatus.COMPLETED
except Exception as e:
@@ -380,11 +390,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
finished=True,
),
start_to_close_timeout=dt.timedelta(minutes=2),
- retry_policy=temporalio.common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=5),
- maximum_interval=dt.timedelta(minutes=1),
- maximum_attempts=3,
- ),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
)
except Exception:
temporalio.workflow.logger.exception(
@@ -401,11 +407,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
advance_next_delivery_date,
inputs.subscription_id,
start_to_close_timeout=dt.timedelta(minutes=2),
- retry_policy=temporalio.common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=5),
- maximum_interval=dt.timedelta(minutes=1),
- maximum_attempts=3,
- ),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
)
# Enrich SLO event with per-insight detail (non-user errors only).
@@ -429,6 +431,159 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
raise caught_error
[email protected](name="process-ai-subscription")
+class ProcessAISubscriptionWorkflow(PostHogWorkflow):
+ """Scheduled delivery for AI-prompt subs: create-record -> validate -> generate (LLM) -> deliver.
+
+ The lifecycle scaffolding mirrors ProcessSubscriptionWorkflow (only the middle phase
+ differs); keep the two in sync. Not a shared base — Temporal workflow classes can't
+ share run-method control flow without sandbox-determinism risk.
+ """
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> TrackedSubscriptionInputs:
+ loaded = json.loads(inputs[0])
+ return TrackedSubscriptionInputs(**loaded)
+
+ @temporalio.workflow.run
+ async def run(self, inputs: TrackedSubscriptionInputs) -> None:
+ delivery_id: uuid.UUID | None = None
+ final_status = DeliveryStatus.SKIPPED
+ delivery_recipient_results: list[dict] = []
+ caught_error: BaseException | None = None
+
+ try:
+ delivery_id = await temporalio.workflow.execute_activity(
+ create_delivery_record,
+ CreateDeliveryRecordInputs(
+ subscription_id=inputs.subscription_id,
+ team_id=inputs.team_id,
+ trigger_type=inputs.trigger_type,
+ scheduled_at=inputs.scheduled_at,
+ temporal_workflow_id=temporalio.workflow.info().workflow_id,
+ idempotency_key=str(temporalio.workflow.uuid4()),
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=2),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
+ )
+
+ # Up-front validation: already-disabled (idempotency redispatch) or a
+ # permanently broken target (e.g. unsupported target_type) auto-disables and
+ # short-circuits before any LLM cost.
+ abort_info = await temporalio.workflow.execute_activity(
+ validate_subscription_for_delivery,
+ inputs.subscription_id,
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ retry_policy=SUBSCRIPTION_VALIDATE_RETRY_POLICY,
+ )
+ if abort_info is not None:
+ # Just-disabled → FAILED with reason. Already-disabled (no failed_recipient)
+ # → SKIPPED default (idempotency redispatch). Matches ProcessSubscriptionWorkflow.
+ if abort_info.failed_recipient is not None:
+ delivery_recipient_results = [dataclasses.asdict(abort_info.failed_recipient)]
+ final_status = DeliveryStatus.FAILED
+ return
+
+ # Phase 1: generate the report. Consent is gated inside, before any LLM cost.
+ # The markdown is persisted onto the delivery row (read back by delivery),
+ # never returned on the wire — it can exceed Temporal's ~2 MiB payload cap.
+ generate_result = await temporalio.workflow.execute_activity(
+ generate_ai_subscription_report,
+ GenerateAIReportInputs(subscription_id=inputs.subscription_id, delivery_id=delivery_id),
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ retry_policy=temporalio.common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=30),
+ maximum_interval=dt.timedelta(minutes=5),
+ maximum_attempts=3,
+ ),
+ )
+ if generate_result.aborted:
+ # Consent revoked or prompt invalid — generation already auto-disabled.
+ delivery_recipient_results = _to_recipient_dicts(generate_result.recipient_results)
+ final_status = DeliveryStatus.FAILED
+ return
+
+ # Phase 2: ship the persisted report. is_new only for target-change triggers.
+ is_new = inputs.trigger_type == SubscriptionTriggerType.TARGET_CHANGE
+ 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,
+ invite_message=inputs.invite_message,
+ delivery_id=delivery_id,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,
+ )
+ delivery_recipient_results = _to_recipient_dicts(deliver_result.recipient_results)
+ final_status = DeliveryStatus.COMPLETED
+
+ except Exception as e:
+ # Preserve recipient outcomes carried in non-retryable delivery errors so the
+ # delivery history isn't empty on failure (matches ProcessSubscriptionWorkflow).
+ if isinstance(e, ActivityError) and isinstance(e.cause, ApplicationError):
+ details = e.cause.details
+ if details and isinstance(details[0], dict):
+ recipient_results = details[0].get("recipient_results")
+ if isinstance(recipient_results, list):
+ delivery_recipient_results = recipient_results
+ caught_error = e
+ final_status = DeliveryStatus.FAILED
+
+ finally:
+ if delivery_id is not None:
+ try:
+ await temporalio.workflow.execute_activity(
+ update_delivery_record,
+ UpdateDeliveryRecordInputs(
+ delivery_id=delivery_id,
+ status=final_status,
+ recipient_results=delivery_recipient_results or None,
+ error={"message": str(caught_error)[:500], "type": type(caught_error).__name__}
+ if caught_error
+ else None,
+ finished=True,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=2),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
+ )
+ except Exception:
+ temporalio.workflow.logger.exception(
+ "update_delivery_record failed (delivery history is best-effort when a prior error exists)"
+ )
+ if caught_error is None:
+ raise
+
+ # Advance schedule for scheduled deliveries even on failure — the activity
+ # 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,
+ inputs.subscription_id,
+ start_to_close_timeout=dt.timedelta(minutes=2),
+ retry_policy=SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,
+ )
+
+ # Auto-disable aborts (consent revoked / prompt invalid) return normally rather
+ # than raising, so they record delivery status FAILED but keep the SLO outcome
+ # SUCCESS — a user-config terminal state is not a platform failure (matches the
+ # non-AI auto-disable convention). Genuine errors set caught_error and re-raise
+ # below; SloInterceptor maps the exception to a FAILURE outcome, same as
+ # ProcessSubscriptionWorkflow, so we don't set the outcome here.
+ if inputs.slo:
+ inputs.slo.completion_properties.setdefault("resource_type", AI_PROMPT_RESOURCE_TYPE)
+
+ # Re-raise after cleanup completes — Temporal blocks activity scheduling in the
+ # finally block while an exception is propagating.
+ if caught_error:
+ raise caught_error
+
+
@temporalio.workflow.defn(name="handle-subscription-value-change")
class HandleSubscriptionValueChangeWorkflow(PostHogWorkflow):
@staticmethod
@@ -445,6 +600,7 @@ class HandleSubscriptionValueChangeWorkflow(PostHogWorkflow):
previous_value=inputs.previous_value,
invite_message=inputs.invite_message,
trigger_type=inputs.trigger_type,
+ resource_type=inputs.resource_type,
slo=SloConfig(
operation=SloOperation.SUBSCRIPTION_DELIVERY,
area=SloArea.ANALYTIC_PLATFORM,
@@ -453,9 +609,17 @@ class HandleSubscriptionValueChangeWorkflow(PostHogWorkflow):
distinct_id=inputs.distinct_id,
),
)
- child_id = f"process-subscription-{inputs.trigger_type}-{inputs.subscription_id}"
+ # Route AI-prompt subs (test delivery / target change) to the AI workflow, same
+ # as the scheduler fan-out.
+ child_workflow: Callable[..., Coroutine[Any, Any, None]]
+ if inputs.resource_type == AI_PROMPT_RESOURCE_TYPE:
+ child_workflow = ProcessAISubscriptionWorkflow.run
+ child_id = f"process-ai-subscription-{inputs.trigger_type}-{inputs.subscription_id}"
+ else:
+ child_workflow = ProcessSubscriptionWorkflow.run
+ child_id = f"process-subscription-{inputs.trigger_type}-{inputs.subscription_id}"
await temporalio.workflow.execute_child_workflow(
- ProcessSubscriptionWorkflow.run,
+ child_workflow,
tracked,
id=child_id,
parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,