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.

fix(subscriptions): deliver repeat test emails reliably (#76019)

Matt Puaedae470f184e
diff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.py
index e6919e1847cc..ca569917dfbf 100644
--- a/ee/tasks/subscriptions/email_subscriptions.py
+++ b/ee/tasks/subscriptions/email_subscriptions.py
@@ -3,7 +3,7 @@ from typing import Optional
import structlog
-from posthog.email import EmailMessage
+from posthog.email import EmailMessage, raise_if_delivery_rejected
from posthog.utils import absolute_uri
from products.exports.backend.models.exported_asset import ExportedAsset
@@ -53,6 +53,7 @@ def send_email_subscription_report(
send_async: bool = True,
change_summary: Optional[str] = None,
summary_skipped_over_budget: bool = False,
+ delivery_id: Optional[uuid.UUID] = None,
) -> None:
utm_tags = f"{UTM_TAGS_BASE}&utm_medium=email"
@@ -68,12 +69,12 @@ def send_email_subscription_report(
raise NotImplementedError("This type of subscription resource is not supported")
subject = f"PostHog {resource_info.kind} report - {resource_info.name}"
- # Subscription id scopes MessagingRecord dedupe per subscription; without it, shared recipients only get
- # one send per (resource kind, next_delivery_date) because campaign_key collided across subscriptions.
- campaign_key = (
- f"{resource_info.kind.lower()}_subscription_report_{subscription.pk}_"
- f"{subscription.next_delivery_date.isoformat() if subscription.next_delivery_date is not None else 'unscheduled'}"
- )
+ delivery_key = "unscheduled"
+ if subscription.next_delivery_date is not None:
+ delivery_key = subscription.next_delivery_date.isoformat()
+ if delivery_id is not None:
+ delivery_key = str(delivery_id)
+ campaign_key = f"{resource_info.kind.lower()}_subscription_report_{subscription.pk}_{delivery_key}"
unsubscribe_url = absolute_uri(f"/unsubscribe?token={get_unsubscribe_token(subscription, email)}&{utm_tags}")
@@ -87,7 +88,8 @@ def send_email_subscription_report(
else:
inviter_name = (inviter.first_name if inviter else None) or "Someone"
subject = f"{inviter_name} subscribed you to a PostHog {resource_info.kind}"
- campaign_key = f"{resource_info.kind.lower()}_subscription_new_{uuid.uuid4()}"
+ invite_delivery_key = str(delivery_id) if delivery_id is not None else str(uuid.uuid4())
+ campaign_key = f"{resource_info.kind.lower()}_subscription_new_{subscription.pk}_{invite_delivery_key}"
message = EmailMessage(
campaign_key=campaign_key,
@@ -112,3 +114,6 @@ def send_email_subscription_report(
)
message.add_recipient(email=email)
message.send(send_async=send_async)
+
+ if not send_async:
+ raise_if_delivery_rejected(campaign_key, email)
diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.py
index af08bca6fc73..cea358353187 100644
--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py
+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py
@@ -1,8 +1,13 @@
+import uuid
+import smtplib
+
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from posthog.email import EmailDeliveryError
from posthog.models.instance_setting import set_instance_setting
+from posthog.models.messaging import MessagingRecord, get_email_hashes
from posthog.tasks.test.utils_email_tests import mock_email_messages
from products.dashboards.backend.models.dashboard import Dashboard
@@ -159,3 +164,75 @@ class TestEmailSubscriptionsTasks(APIBaseTest):
assert mocked_email_messages[0].campaign_key != mocked_email_messages[1].campaign_key
assert str(self.subscription.pk) in mocked_email_messages[0].campaign_key
assert str(subscription_b.pk) in mocked_email_messages[1].campaign_key
+
+ def test_delivery_id_scopes_campaign_deduplication(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_ee_email_messages(MockEmailMessage)
+ first_delivery_id = uuid.uuid4()
+ second_delivery_id = uuid.uuid4()
+
+ send_email_subscription_report(
+ "[email protected]", self.subscription, [self.asset], delivery_id=first_delivery_id
+ )
+ send_email_subscription_report(
+ "[email protected]", self.subscription, [self.asset], delivery_id=first_delivery_id
+ )
+ send_email_subscription_report(
+ "[email protected]", self.subscription, [self.asset], delivery_id=second_delivery_id
+ )
+
+ assert mocked_email_messages[0].campaign_key == mocked_email_messages[1].campaign_key
+ assert mocked_email_messages[0].campaign_key != mocked_email_messages[2].campaign_key
+ assert str(first_delivery_id) in mocked_email_messages[0].campaign_key
+ assert str(second_delivery_id) in mocked_email_messages[2].campaign_key
+
+ def test_invite_retries_reuse_delivery_campaign(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_ee_email_messages(MockEmailMessage)
+ delivery_id = uuid.uuid4()
+
+ for _ in range(2):
+ send_email_subscription_report(
+ self.subscription,
+ [self.asset],
+ invite_message="Welcome",
+ delivery_id=delivery_id,
+ )
+
+ assert mocked_email_messages[0].campaign_key == mocked_email_messages[1].campaign_key
+ assert str(delivery_id) in mocked_email_messages[0].campaign_key
+
+
+@freeze_time("2022-02-02T08:55:00.000Z")
+class TestEmailSubscriptionDeliveryDetection(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, short_id="detect", name="Detection insight")
+ self.asset = ExportedAsset.objects.create(
+ team=self.team,
+ insight_id=self.insight.id,
+ export_format="image/png",
+ content_location="s3://bucket/test.png",
+ )
+ self.subscription = create_subscription(team=self.team, insight=self.insight, created_by=self.user)
+ set_instance_setting("EMAIL_HOST", "localhost")
+ set_instance_setting("EMAIL_ENABLED", True)
+
+ def test_raises_when_permanent_smtp_failure_is_swallowed(self) -> None:
+ with patch(
+ "django.core.mail.backends.locmem.EmailBackend.send_messages",
+ side_effect=smtplib.SMTPRecipientsRefused({"[email protected]": (550, b"no such user")}),
+ ):
+ with self.assertRaises(EmailDeliveryError):
+ send_email_subscription_report("[email protected]", self.subscription, [self.asset], send_async=False)
+
+ def test_does_not_raise_when_delivery_recorded(self) -> None:
+ send_email_subscription_report("[email protected]", self.subscription, [self.asset], send_async=False)
+
+ assert MessagingRecord.objects.filter(
+ email_hash__in=get_email_hashes("[email protected]"), sent_at__isnull=False
+ ).exists()
+
+ def test_raises_when_smtp_backend_accepts_no_messages(self) -> None:
+ with patch("django.core.mail.backends.locmem.EmailBackend.send_messages", return_value=0):
+ with self.assertRaises(EmailDeliveryError):
+ send_email_subscription_report("[email protected]", self.subscription, [self.asset], send_async=False)
diff --git a/posthog/email.py b/posthog/email.py
index c8118a93391c..372d979883bb 100644
--- a/posthog/email.py
+++ b/posthog/email.py
@@ -29,7 +29,7 @@ from posthog.celery_queues import CeleryQueue
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import sanitize_display_name, sanitize_email_string
from posthog.models.instance_setting import get_instance_setting
-from posthog.models.messaging import MessagingRecord
+from posthog.models.messaging import MessagingRecord, get_email_hashes
logger = structlog.get_logger(__name__)
@@ -246,20 +246,26 @@ def _send_via_http(
provider_response = response.json()
- posthoganalytics.capture(
- distinct_id=dest.get("distinct_id") or dest["raw_email"],
- event="transactional email triggered",
- properties={
- "template_name": template_name,
- "campaign_key": campaign_key,
- "recipient_email": dest["raw_email"],
- **provider_response,
- },
- )
-
+ # Mark delivery before any non-essential step so a delivered email is never
+ # recorded as rejected (raise_if_delivery_rejected keys off sent_at). Analytics
+ # is best-effort and isolated so its failure can't roll back a successful send.
record.sent_at = timezone.now()
record.save()
+ try:
+ posthoganalytics.capture(
+ distinct_id=dest.get("distinct_id") or dest["raw_email"],
+ event="transactional email triggered",
+ properties={
+ "template_name": template_name,
+ "campaign_key": campaign_key,
+ "recipient_email": dest["raw_email"],
+ **provider_response,
+ },
+ )
+ except Exception as analytics_err:
+ logger.warning("email_send_analytics_capture_failed", error=str(analytics_err))
+
EMAIL_SEND_COUNTER.labels(outcome="sent", transport="http").inc()
sent_count += 1
@@ -320,11 +326,23 @@ def _send_via_smtp(
)
email_message.attach_alternative(html_body, "text/html")
- connection.send_messages([email_message])
-
- record.sent_at = timezone.now()
- record.save()
- EMAIL_SEND_COUNTER.labels(outcome="sent", transport="smtp").inc()
+ # Django's contract returns the accepted count, but some backends return None.
+ # Treat only an explicit 0 as rejection — a non-zero count or a None (backend that
+ # returns nothing after a non-raising handoff) means the provider took the email.
+ accepted_count = connection.send_messages([email_message])
+ if accepted_count == 0:
+ logger.warning("email_send_smtp_not_accepted", recipient=dest["raw_email"])
+ EMAIL_SEND_COUNTER.labels(outcome="failed", transport="smtp").inc()
+ else:
+ if accepted_count != 1:
+ logger.warning(
+ "email_send_smtp_unexpected_count",
+ recipient=dest["raw_email"],
+ accepted_count=accepted_count,
+ )
+ record.sent_at = timezone.now()
+ record.save()
+ EMAIL_SEND_COUNTER.labels(outcome="sent", transport="smtp").inc()
except _TRANSIENT_SMTP_ERRORS as err:
# Re-raise so the task's autoretry (3x + backoff) retries instead of dropping the email.
# warning, not capture_exception: expected + auto-retried, capturing each attempt is noise.
@@ -361,6 +379,29 @@ def _send_via_smtp(
logger.warning("email_connection_close_failed", error=str(err))
+class EmailDeliveryError(Exception):
+ """A synchronous send returned without the provider accepting the email."""
+
+
+def was_email_delivered(campaign_key: str, email: str) -> bool:
+ """Return whether the provider accepted this campaign for this recipient (MessagingRecord.sent_at set)."""
+ return MessagingRecord.objects.filter(
+ campaign_key=campaign_key, email_hash__in=get_email_hashes(email), sent_at__isnull=False
+ ).exists()
+
+
+def raise_if_delivery_rejected(campaign_key: str, email: str) -> None:
+ """Raise EmailDeliveryError only when the provider accepted nothing for this recipient.
+
+ Only fires when zero messages were accepted: SMTP `send_messages` returned 0, or a 5xx
+ `SMTPRecipientsRefused` was swallowed without recording any delivery. Any accepted email
+ sets `MessagingRecord.sent_at` *before* a post-accept step (posthog capture, record save)
+ can raise, so a delivered email never reaches this branch.
+ """
+ if not was_email_delivered(campaign_key, email):
+ raise EmailDeliveryError(f"provider accepted no email for {email} under {campaign_key}")
+
+
# `utm_tags` carries hardcoded query-string fragments (`a=1&b=2`) and is never
# user-controlled. It must pass through verbatim so the `&` separators don't
# get HTML-escaped before reaching Customer.io — Liquid renders the value raw,
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index 498b2e9b89f3..7e2aa8fcd407 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -1,4 +1,5 @@
import uuid
+import smtplib
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
@@ -22,6 +23,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.hogql.errors import QueryError
+from posthog.email import EmailDeliveryError
from posthog.errors import CHQueryErrorS3Error
from posthog.models import OrganizationMembership
from posthog.models.instance_setting import set_instance_setting
@@ -41,6 +43,7 @@ from products.exports.backend.temporal.subscriptions.activities import (
create_delivery_record,
create_export_assets,
deliver_subscription,
+ deliver_subscription_v2,
fetch_due_subscriptions_activity,
update_delivery_record,
validate_subscription_for_delivery,
@@ -53,6 +56,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.activities
)
from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import AiReportResult
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError
+from products.exports.backend.temporal.subscriptions.delivery_common import deliver_email
from products.exports.backend.temporal.subscriptions.types import (
CreateDeliveryRecordInputs,
CreateExportAssetsInputs,
@@ -101,6 +105,66 @@ async def test_subscription_workflows_accept_legacy_previous_target_payload() ->
assert update_inputs.previous_target_value == "[email protected]"
+async def test_email_delivery_error_is_non_retryable(team, user) -> None:
+ subscription = await sync_to_async(create_subscription)(team=team, created_by=user)
+ inputs = DeliverSubscriptionInputs(
+ subscription_id=subscription.id,
+ exported_asset_ids=[],
+ total_insight_count=0,
+ )
+
+ async def fail_send(_email: str) -> None:
+ raise EmailDeliveryError("provider rejected delivery")
+
+ with patch("products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"):
+ with pytest.raises(ApplicationError) as error:
+ await deliver_email(subscription, inputs, [], fail_send)
+
+ assert error.value.non_retryable is True
+ assert error.value.details[0]["recipient_results"][0]["status"] == "failed"
+
+
+async def test_mixed_permanent_and_transient_failures_are_retryable(team, user) -> None:
+ subscription = await sync_to_async(create_subscription)(team=team, target_value="[email protected],[email protected]")
+ inputs = DeliverSubscriptionInputs(
+ subscription_id=subscription.id,
+ exported_asset_ids=[],
+ total_insight_count=0,
+ )
+
+ async def mixed_send(email: str) -> None:
+ if email == "[email protected]":
+ raise EmailDeliveryError("permanent rejection")
+ raise smtplib.SMTPException("transient relay timeout")
+
+ with patch("products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"):
+ with pytest.raises(smtplib.SMTPException):
+ await deliver_email(subscription, inputs, [], mixed_send)
+
+
+async def test_non_retryable_error_details_are_bounded(team, user) -> None:
+ subscription = await sync_to_async(create_subscription)(
+ team=team, target_value=",".join(f"user{i}@posthog.com" for i in range(120))
+ )
+ inputs = DeliverSubscriptionInputs(
+ subscription_id=subscription.id,
+ exported_asset_ids=[],
+ total_insight_count=0,
+ )
+
+ async def fail_send(_email: str) -> None:
+ raise EmailDeliveryError("permanent rejection")
+
+ with patch("products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"):
+ with pytest.raises(ApplicationError) as error:
+ await deliver_email(subscription, inputs, [], fail_send)
+
+ details = error.value.details[0]["recipient_results"]
+ assert error.value.non_retryable is True
+ assert len(details) == 51 # 50 capped results + truncation sentinel
+ assert details[-1]["truncated_count"] == 70
+
+
SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
Sequence[Callable[..., Any]],
[
@@ -110,6 +174,7 @@ SUBSCRIPTION_SCHEDULE_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
create_export_assets,
export_asset_activity,
deliver_subscription,
+ deliver_subscription_v2,
generate_ai_subscription_report,
update_delivery_record,
advance_next_delivery_date,
@@ -124,6 +189,7 @@ SUBSCRIPTION_PROCESS_ACTIVITIES: Sequence[Callable[..., Any]] = cast(
create_export_assets,
export_asset_activity,
deliver_subscription,
+ deliver_subscription_v2,
generate_ai_subscription_report,
update_delivery_record,
advance_next_delivery_date,
@@ -1526,6 +1592,8 @@ async def test_deliver_subscription_workflow_end_to_end(
# 2 recipients
assert mock_send_email.call_count == 2
+ delivery = await sync_to_async(SubscriptionDelivery.objects.get)(subscription=subscription)
+ assert {call.kwargs["delivery_id"] for call in mock_send_email.call_args_list} == {delivery.id}
# Both started and completed events flow through posthog.slo.events
started_calls = [
diff --git a/products/exports/backend/temporal/subscriptions/__init__.py b/products/exports/backend/temporal/subscriptions/__init__.py
index ccb87e9dfbec..604f9206c0db 100644
--- a/products/exports/backend/temporal/subscriptions/__init__.py
+++ b/products/exports/backend/temporal/subscriptions/__init__.py
@@ -3,6 +3,7 @@ from products.exports.backend.temporal.subscriptions.activities import (
create_delivery_record,
create_export_assets,
deliver_subscription,
+ deliver_subscription_v2,
fetch_due_subscriptions_activity,
update_delivery_record,
validate_subscription_for_delivery,
@@ -28,6 +29,7 @@ ACTIVITIES = [
validate_subscription_for_delivery,
create_export_assets,
deliver_subscription,
+ deliver_subscription_v2,
generate_ai_subscription_report,
advance_next_delivery_date,
create_delivery_record,
diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.py
index effcb7d46b51..ef4a600862da 100644
--- a/products/exports/backend/temporal/subscriptions/activities.py
+++ b/products/exports/backend/temporal/subscriptions/activities.py
@@ -381,6 +381,17 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExport
@temporalio.activity.defn
async def deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubscriptionResult:
+ # TODO(2026-07-31): After workflows started before 2026-07-31 have drained, remove this v1 activity,
+ # rename deliver_subscription_v2 to deliver_subscription, and remove the workflow patch.
+ return await _deliver_subscription(inputs)
+
+
[email protected](name="deliver-subscription-v2")
+async def deliver_subscription_v2(inputs: DeliverSubscriptionInputs) -> DeliverSubscriptionResult:
+ return await _deliver_subscription(inputs)
+
+
+async def _deliver_subscription(inputs: DeliverSubscriptionInputs) -> DeliverSubscriptionResult:
recipient_results: list[RecipientResult] = []
subscription = await database_sync_to_async(
@@ -484,6 +495,7 @@ async def _deliver_insight_dashboard_subscription(
send_async=False,
change_summary=inputs.change_summary,
summary_skipped_over_budget=inputs.summary_skipped_over_budget,
+ delivery_id=inputs.delivery_id,
)
result = await deliver_email(subscription, inputs, recipient_results, _send_email)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 9a356d3b8286..962e361d1b29 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -7,7 +7,7 @@ import structlog
from markdown_it import MarkdownIt
from markdown_to_mrkdwn import SlackMarkdownConverter
-from posthog.email import EmailMessage
+from posthog.email import EmailMessage, raise_if_delivery_rejected
from posthog.exceptions_capture import capture_exception
from posthog.helpers.markdown_safety import strip_external_links_markdown
from posthog.helpers.slack_subscription_explore import build_explore_hint
@@ -254,6 +254,8 @@ def send_email_ai_subscription_report(
message.add_recipient(email=email)
message.send(send_async=False)
+ raise_if_delivery_rejected(campaign_key, email)
+
def send_email_ai_subscription_credit_limited(
*,
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.py
index 1241fcd0242a..58089e53e0cb 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
@@ -280,6 +280,11 @@ class TestFeedbackFooter:
"products.exports.backend.temporal.subscriptions.ai_subscription.delivery.get_unsubscribe_token",
return_value="tok",
),
+ # Mocking EmailMessage means no real send + no MessagingRecord, so the
+ # post-send acceptance check would hit the DB; delivery is covered separately.
+ patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.raise_if_delivery_rejected"
+ ),
):
send_email_ai_subscription_report(
diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.py
index 087d7a3966e2..59f4540eefbf 100644
--- a/products/exports/backend/temporal/subscriptions/delivery_common.py
+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py
@@ -5,6 +5,7 @@ from slack_sdk.errors import SlackApiError
from structlog import get_logger
from temporalio.exceptions import ApplicationError
+from posthog.email import EmailDeliveryError
from posthog.exceptions_capture import capture_exception
from posthog.models.integration import Integration
from posthog.sync import database_sync_to_async
@@ -27,6 +28,11 @@ from ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult, get_
LOGGER = get_logger(__name__)
+# Cap recipient_results echoed into an ApplicationError's details — Temporal serializes error
+# details into history events capped at the gRPC payload limit, and an oversized non-retryable
+# error can't be recorded, leaving the workflow unable to complete its failing task.
+_MAX_ERROR_DETAIL_RESULTS = 50
+
def strip_null_bytes(value: Any) -> Any:
"""Recursively remove NUL (\\x00) from strings — Postgres text/jsonb columns cannot store it.
@@ -95,7 +101,7 @@ async def deliver_email(
)
success_count = 0
- last_error: Exception | None = None
+ failures: list[tuple[str, Exception]] = []
for email in emails:
try:
await send_one(email)
@@ -117,7 +123,7 @@ async def deliver_email(
recipient=email, status="failed", error={"message": str(exc), "type": type(exc).__name__}
)
)
- last_error = exc
+ failures.append((email, exc))
await LOGGER.ainfo(
"deliver_subscription.email_complete",
@@ -126,8 +132,33 @@ async def deliver_email(
total_count=len(emails),
)
- if last_error is not None and success_count == 0:
- raise last_error
+ if failures and success_count == 0:
+ # Whole batch failed. Retryability is decided per recipient, not by which error
+ # happened to be last: any transient failure means a retry must run so those
+ # recipients get another attempt (dedupe skips the already-delivered ones). Only
+ # when every recipient hit a permanent rejection (EmailDeliveryError) is the batch
+ # non-retryable — retrying then could never succeed.
+ # Bound the error details: a huge recipient list with a domain-wide bounce would
+ # otherwise exceed Temporal's gRPC payload cap and wedge the workflow mid-failure.
+ details: list[dict[str, Any]] = [
+ {
+ "recipient": result.recipient,
+ "status": result.status,
+ **({"error": result.error} if result.error else {}),
+ }
+ for result in recipient_results[:_MAX_ERROR_DETAIL_RESULTS]
+ ]
+ if len(recipient_results) > _MAX_ERROR_DETAIL_RESULTS:
+ details.append({"truncated_count": len(recipient_results) - _MAX_ERROR_DETAIL_RESULTS})
+ permanent = [err for _, err in failures if isinstance(err, EmailDeliveryError)]
+ if permanent and len(permanent) == len(failures):
+ raise ApplicationError(
+ f"all {len(failures)} recipients permanently rejected delivery",
+ {"recipient_results": details},
+ non_retryable=True,
+ ) from permanent[0]
+ # Mixed or all-transient: re-raise a retryable error so Temporal retries the batch.
+ raise next(err for _, err in failures if not isinstance(err, EmailDeliveryError))
return DeliverSubscriptionResult(recipient_results=recipient_results)
diff --git a/products/exports/backend/temporal/subscriptions/test_delivery_activities.py b/products/exports/backend/temporal/subscriptions/test_delivery_activities.py
new file mode 100644
index 000000000000..d4e043638f04
--- /dev/null
+++ b/products/exports/backend/temporal/subscriptions/test_delivery_activities.py
@@ -0,0 +1,148 @@
+import uuid
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from asgiref.sync import sync_to_async
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import ActivityEnvironment
+
+from posthog.email import EmailDeliveryError
+from posthog.temporal.exports.activities import export_asset_activity
+from posthog.temporal.exports.types import ExportAssetResult
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.exports.backend.temporal.subscriptions.activities import (
+ advance_next_delivery_date,
+ create_delivery_record,
+ create_export_assets,
+ deliver_subscription,
+ deliver_subscription_v2,
+ 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.types import (
+ CreateExportAssetsResult,
+ DeliverSubscriptionInputs,
+ DeliverSubscriptionResult,
+ GenerateAIReportResult,
+ SnapshotInsightsResult,
+ TrackedSubscriptionInputs,
+)
+from products.exports.backend.temporal.subscriptions.workflows import (
+ ProcessAISubscriptionWorkflow,
+ ProcessSubscriptionWorkflow,
+)
+from products.product_analytics.backend.models.insight import Insight
+
+from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
+
+
+# v1 only exists as a Temporal history-compat shim for pre-patch workflows. Both
+# entry points must hit the shared delivery + EmailDeliveryError -> non-retryable
+# ApplicationError mapping, so the delivery record keeps per-recipient results.
[email protected]("activity", [deliver_subscription, deliver_subscription_v2])
+async def test_deliver_subscription_wraps_email_delivery_error(team, user, activity) -> None:
+ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="covdg", name="Coverage delegation")
+ asset = await sync_to_async(ExportedAsset.objects.create)(
+ team=team, insight=insight, export_format="image/png", content_location="s3://bucket/cov.png"
+ )
+ subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)
+ inputs = DeliverSubscriptionInputs(
+ subscription_id=subscription.id,
+ exported_asset_ids=[asset.id],
+ total_insight_count=1,
+ )
+
+ with (
+ patch(
+ "products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report",
+ side_effect=EmailDeliveryError("provider rejected delivery"),
+ ),
+ patch("products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"),
+ ):
+ with pytest.raises(ApplicationError) as error:
+ await ActivityEnvironment().run(activity, inputs)
+
+ assert error.value.non_retryable is True
+ assert error.value.details[0]["recipient_results"][0]["status"] == "failed"
+
+
+# The patch-gated activity switch is the rollout seam for the v2 delivery campaign: new
+# executions take v2, in-flight pre-patch executions stay on v1 for history compatibility.
+# Driving through the workflow (not just the patched() helper) pins both the selection and
+# that the chosen activity is what execute_activity receives.
[email protected]("patch_active", [True, False], ids=["patched_v2", "pre_patch_v1"])
+async def test_process_subscription_picks_delivery_activity_from_patch(patch_active) -> None:
+ picked = None
+
+ async def fake_execute_activity(activity, inputs, **_kwargs):
+ nonlocal picked
+ if activity is create_delivery_record:
+ return uuid.uuid4()
+ if activity is validate_subscription_for_delivery:
+ return None
+ if activity is create_export_assets:
+ return CreateExportAssetsResult(exported_asset_ids=[1], total_insight_count=1)
+ if activity is export_asset_activity:
+ return ExportAssetResult(exported_asset_id=1, success=True)
+ if activity is snapshot_subscription_insights:
+ return SnapshotInsightsResult()
+ if activity in (deliver_subscription, deliver_subscription_v2):
+ picked = activity
+ return DeliverSubscriptionResult()
+ if activity is update_delivery_record:
+ return None
+ raise AssertionError(f"unexpected activity {activity}")
+
+ with (
+ patch("temporalio.workflow.execute_activity", side_effect=fake_execute_activity),
+ patch("temporalio.workflow.patched", return_value=patch_active),
+ patch("temporalio.workflow.info") as mock_info,
+ patch("temporalio.workflow.uuid4", return_value=uuid.uuid4()),
+ patch("temporalio.workflow.logger", MagicMock()),
+ ):
+ mock_info.return_value = MagicMock(workflow_id="wf-test")
+ await ProcessSubscriptionWorkflow().run(
+ TrackedSubscriptionInputs(subscription_id=1, team_id=1, distinct_id="u1")
+ )
+
+ assert picked is (deliver_subscription_v2 if patch_active else deliver_subscription)
+
+
[email protected]("patch_active", [True, False], ids=["patched_v2", "pre_patch_v1"])
+async def test_process_ai_subscription_picks_delivery_activity_from_patch(patch_active) -> None:
+ picked = None
+
+ async def fake_execute_activity(activity, inputs, **_kwargs):
+ nonlocal picked
+ if activity is create_delivery_record:
+ return uuid.uuid4()
+ if activity is validate_subscription_for_delivery:
+ return None
+ if activity is generate_ai_subscription_report:
+ return GenerateAIReportResult()
+ if activity in (deliver_subscription, deliver_subscription_v2):
+ picked = activity
+ return DeliverSubscriptionResult()
+ if activity in (update_delivery_record, advance_next_delivery_date):
+ return None
+ raise AssertionError(f"unexpected activity {activity}")
+
+ with (
+ patch("temporalio.workflow.execute_activity", side_effect=fake_execute_activity),
+ patch("temporalio.workflow.patched", return_value=patch_active),
+ patch("temporalio.workflow.info") as mock_info,
+ patch("temporalio.workflow.uuid4", return_value=uuid.uuid4()),
+ patch("temporalio.workflow.logger", MagicMock()),
+ ):
+ mock_info.return_value = MagicMock(workflow_id="wf-test-ai")
+ await ProcessAISubscriptionWorkflow().run(
+ TrackedSubscriptionInputs(subscription_id=1, team_id=1, distinct_id="u1")
+ )
+
+ assert picked is (deliver_subscription_v2 if patch_active else deliver_subscription)
diff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.py
index 091591fa8cc3..fdbf8743a087 100644
--- a/products/exports/backend/temporal/subscriptions/workflows.py
+++ b/products/exports/backend/temporal/subscriptions/workflows.py
@@ -28,6 +28,7 @@ from products.exports.backend.temporal.subscriptions.activities import (
create_delivery_record,
create_export_assets,
deliver_subscription,
+ deliver_subscription_v2,
fetch_due_subscriptions_activity,
update_delivery_record,
validate_subscription_for_delivery,
@@ -372,8 +373,13 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
# a "failed to generate" placeholder in the email/Slack message)
delivery_asset_ids = prepare_result.exported_asset_ids
+ delivery_activity = (
+ deliver_subscription_v2
+ if temporalio.workflow.patched("subscription-delivery-campaign-v2")
+ else deliver_subscription
+ )
deliver_result: DeliverSubscriptionResult = await temporalio.workflow.execute_activity(
- deliver_subscription,
+ delivery_activity,
DeliverSubscriptionInputs(
subscription_id=inputs.subscription_id,
exported_asset_ids=delivery_asset_ids,
@@ -387,6 +393,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
invite_message=inputs.invite_message,
change_summary=change_summary,
summary_skipped_over_budget=summary_skipped_over_budget,
+ delivery_id=delivery_id,
),
start_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,
@@ -553,8 +560,13 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):
return
# Phase 2: ship the persisted report.
+ delivery_activity = (
+ deliver_subscription_v2
+ if temporalio.workflow.patched("subscription-delivery-campaign-v2")
+ else deliver_subscription
+ )
deliver_result = await temporalio.workflow.execute_activity(
- deliver_subscription,
+ delivery_activity,
DeliverSubscriptionInputs(
subscription_id=inputs.subscription_id,
exported_asset_ids=[],