:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): detect and pause workflows breaching complaint or bounce rates (#89879)
Meikel Ratzf04cbb5bccfa
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.pyindex df9f4f85281c..2b4af5e9fc7d 100644--- a/posthog/api/app_metrics2.py+++ b/posthog/api/app_metrics2.py@@ -248,6 +248,7 @@ def fetch_app_metric_totals_by_source(after: Optional[datetime] = None,before: Optional[datetime] = None,name: Optional[list[str]] = None,+ hour_aligned: bool = False,) -> dict[str, dict[str, int]]:"""Per-`app_source_id` metric totals for a whole team in one grouped query.@@ -259,6 +260,13 @@ def fetch_app_metric_totals_by_source(# Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a# team-timezone-aware bound would otherwise shift the window by the team's offset.+ # Hour-aligned bounds compare on toStartOfHour(timestamp) with a half-open upper bound. The+ # table's sorting key collapses rows per clock hour and keeps one arbitrary raw timestamp, so a+ # mid-hour bound on the raw column includes or excludes a whole collapsed hour by luck. Callers+ # pass hour-start datetimes; whole hours are then in or out deterministically.+ bound_expr = "toStartOfHour(timestamp)" if hour_aligned else "timestamp"+ before_op = "<" if hour_aligned else "<="+clickhouse_kwargs: dict[str, Any] = {"team_id": team_id,"app_source": app_source,@@ -275,8 +283,8 @@ def fetch_app_metric_totals_by_source(FROM app_metrics2WHERE team_id = %(team_id)sAND app_source = %(app_source)s- {"AND timestamp >= toDateTime64(%(after)s, 6)" if after else ""}- {"AND timestamp <= toDateTime64(%(before)s, 6)" if before else ""}+ {f"AND {bound_expr} >= toDateTime64(%(after)s, 6)" if after else ""}+ {f"AND {bound_expr} {before_op} toDateTime64(%(before)s, 6)" if before else ""}AND metric_name IN %(name)sGROUP BY app_source_id, metric_name"""@@ -300,6 +308,8 @@ def fetch_app_metric_totals_by_team_and_source(team_ids: Optional[list[int]] = None,min_totals: Optional[dict[str, int]] = None,any_min_totals: Optional[dict[str, int]] = None,+ hour_aligned: bool = False,+ per_source: bool = True,) -> dict[int, dict[str, dict[str, int]]]:"""Per-`app_source_id` metric totals across many teams in one grouped query.@@ -319,6 +329,13 @@ def fetch_app_metric_totals_by_team_and_source(# Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a# team-timezone-aware bound would otherwise shift the window by the team's offset.+ # Hour-aligned bounds compare on toStartOfHour(timestamp) with a half-open upper bound. The+ # table's sorting key collapses rows per clock hour and keeps one arbitrary raw timestamp, so a+ # mid-hour bound on the raw column includes or excludes a whole collapsed hour by luck. Callers+ # pass hour-start datetimes; whole hours are then in or out deterministically.+ bound_expr = "toStartOfHour(timestamp)" if hour_aligned else "timestamp"+ before_op = "<" if hour_aligned else "<="+clickhouse_kwargs: dict[str, Any] = {"app_source": app_source,"after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if after else None,@@ -348,18 +365,23 @@ def fetch_app_metric_totals_by_team_and_source(if any_clauses:having_clauses.append(f"({' OR '.join(any_clauses)})")+ # per_source=False gates and groups at the team level: a caller discovering candidates must not+ # exclude a team whose per-source rows each sit under a gate while their sum crosses it. The+ # source key in the result is then a single empty string.+ source_select = "app_source_id," if per_source else "'' AS app_source_id,"+ group_by = "team_id, app_source_id" if per_source else "team_id"clickhouse_query = f"""SELECTteam_id,- app_source_id,+ {source_select}{selects}FROM app_metrics2WHERE app_source = %(app_source)s{"AND team_id IN %(team_ids)s" if team_ids else ""}- {"AND timestamp >= toDateTime64(%(after)s, 6)" if after else ""}- {"AND timestamp <= toDateTime64(%(before)s, 6)" if before else ""}+ {f"AND {bound_expr} >= toDateTime64(%(after)s, 6)" if after else ""}+ {f"AND {bound_expr} {before_op} toDateTime64(%(before)s, 6)" if before else ""}AND metric_name IN %(name)s- GROUP BY team_id, app_source_id+ GROUP BY {group_by}{f"HAVING {' AND '.join(having_clauses)}" if having_clauses else ""}"""diff --git a/posthog/email.py b/posthog/email.pyindex d7b7e37a8d43..531c93aa87d1 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -65,6 +65,15 @@ def is_smtp_email_service_available() -> bool:return bool(get_instance_setting("EMAIL_HOST"))+def single_line(value: str) -> str:+ """Flatten CR/LF to spaces so a user-set value is safe in an email Subject.++ A CR or LF in a Subject makes Django raise BadHeaderError, which the send path swallows, so+ the whole notification would be dropped.+ """+ return value.replace("\r", " ").replace("\n", " ")++def is_email_available(with_absolute_urls: bool = False) -> bool:"""Returns whether email services are available on this instance (i.e. settings are in place).diff --git a/posthog/settings/ses.py b/posthog/settings/ses.pyindex 9ed5dafc0df0..0959e351c96f 100644--- a/posthog/settings/ses.py+++ b/posthog/settings/ses.py@@ -2,6 +2,8 @@ import osfrom typing import Optionalfrom posthog.settings.base_variables import DEBUG, TEST+from posthog.settings.utils import get_from_env+from posthog.utils import str_to_boolif TEST or DEBUG:SES_ENDPOINT = os.getenv("SES_ENDPOINT", "http://localhost:4566")@@ -34,6 +36,69 @@ WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS: list[str] = [arn.strip() for arn in os.getenv("WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS", "").split(",") if arn.strip()]+# Automatic per-workflow email pause. The detector sweeps every workflow's spam-complaint and+# hard-bounce rates and pauses the ones that breach a threshold, because all workflow email shares+# one SES account and one bad workflow drags deliverability down for every customer.+#+# Off by default. While off, the detector logs what it would have paused and increments its+# counter, but writes nothing, which is how the thresholds below get calibrated per region before+# anything enforces.+WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED: bool = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED", False, type_cast=str_to_bool+)++# Volume gates. A workflow that sent 12 emails and drew 1 complaint is a 8% complaint rate and+# no information, so a breach needs both enough sends in the window and enough feedback events.+WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_1H: int = get_from_env("WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_1H", 200, type_cast=int)+WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_24H: int = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_24H", 1000, type_cast=int+)++# Complaint thresholds sit below AWS's account danger zone (about 0.1% draws warnings and about+# 0.5% risks enforcement) because a single workflow held at 0.3% measurably drags the shared+# account down.+WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_1H: int = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_1H", 5, type_cast=int+)+WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_1H: float = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_1H", 0.01, type_cast=float+)+WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_24H: int = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_24H", 10, type_cast=int+)+WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_24H: float = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_24H", 0.003, type_cast=float+)++# Hard-bounce thresholds mirror AWS's own bounce guidance: 5% warn, 10% enforce.+WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_1H: int = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_1H", 20, type_cast=int+)+WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_1H: float = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_1H", 0.10, type_cast=float+)+WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_24H: int = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_24H", 50, type_cast=int+)+WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_24H: float = get_from_env(+ "WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_24H", 0.05, type_cast=float+)++# Warning band: at these rates the workflow's admins get a heads-up email, and at the pause rates+# above the workflow's email stops. Half the pause rate, with the same volume gates, so a warning+# always precedes a slow-burning pause while an acute burst can still pause without one.+WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_1H: float = get_from_env(+ "WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_1H", 0.005, type_cast=float+)+WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_24H: float = get_from_env(+ "WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_24H", 0.0015, type_cast=float+)+WORKFLOW_EMAIL_WARN_BOUNCE_RATE_1H: float = get_from_env("WORKFLOW_EMAIL_WARN_BOUNCE_RATE_1H", 0.05, type_cast=float)+WORKFLOW_EMAIL_WARN_BOUNCE_RATE_24H: float = get_from_env("WORKFLOW_EMAIL_WARN_BOUNCE_RATE_24H", 0.025, type_cast=float)++# How long one warning covers a workflow. Without this bound the hourly detector would repeat the+# same email every run while the workflow sits inside the warning band.+WORKFLOW_EMAIL_WARN_COOLDOWN_DAYS: int = get_from_env("WORKFLOW_EMAIL_WARN_COOLDOWN_DAYS", 7, type_cast=int)# SES ISP dimension values to break sending health down by. The only API that names providers is# GetDomainStatisticsReport, which needs the Deliverability dashboard subscription, so the list# comes from us. These names are read off the VDM dashboard's ISP table, which reports the samediff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 454b10055cc3..9b79e9e0b4d3 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -17,7 +17,13 @@ from prometheus_client import Counter, Histogramfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY-from posthog.email import EMAIL_TASK_KWARGS, EmailMessage, get_email_team_and_org_context, is_email_available+from posthog.email import (+ EMAIL_TASK_KWARGS,+ EmailMessage,+ get_email_team_and_org_context,+ is_email_available,+ single_line,+)from posthog.event_usage import groupsfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.email_utils import sanitize_display_name, sanitize_message_body@@ -804,6 +810,77 @@ def send_email_sending_suspended(team_id: int, reason: str, suspended_at: str) -message.send()+@shared_task(**EMAIL_TASK_KWARGS)+@with_team_scope()+def send_workflow_email_sending_paused(+ team_id: int, hog_flow_id: str, hog_flow_name: str, reason: str, paused_at: str, resumable: bool = True+) -> None:+ """+ Tell a project's admins that one workflow's email sending was paused automatically because its+ spam complaint or hard bounce rate crossed a threshold. Not gated by notification settings:+ that workflow's email stays paused until someone acts on it.+ """+ if not is_email_available(with_absolute_urls=True):+ return+ team = Team.objects.get(id=team_id)+ memberships_to_email = _get_project_admins_to_notify_of_email_sending_suspension(team)+ if not memberships_to_email:+ return+ workflow_label = single_line(hog_flow_name or "an unnamed workflow")+ message = EmailMessage(+ campaign_key=f"workflow_email_sending_paused_{hog_flow_id}_{paused_at}",+ # No urgency prefix in the subject, for the same deliverability reason as the project-wide+ # suspension email above.+ subject=f"Email sending is paused for '{workflow_label}' in project '{single_line(str(team))}'",+ template_name="workflow_email_sending_paused",+ template_context={+ "team": team,+ "hog_flow_name": workflow_label,+ "reason": reason,+ "resumable": resumable,+ "workflow_path": f"/project/{team.id}/workflows/{hog_flow_id}/workflow",+ },+ )+ for membership in memberships_to_email:+ message.add_user_recipient(membership.user)+ message.send()+++@shared_task(**EMAIL_TASK_KWARGS)+@with_team_scope()+def send_workflow_email_sending_warning(+ team_id: int, hog_flow_id: str, hog_flow_name: str, reason: str, pause_rate: str, warned_at: str+) -> None:+ """+ Warn a project's admins that one workflow's spam complaint or hard bounce rate is approaching+ the pause threshold, while there is still time to act. Not gated by notification settings:+ ignoring it leads to the pause email above.+ """+ if not is_email_available(with_absolute_urls=True):+ return+ team = Team.objects.get(id=team_id)+ memberships_to_email = _get_project_admins_to_notify_of_email_sending_suspension(team)+ if not memberships_to_email:+ return+ workflow_label = single_line(hog_flow_name or "an unnamed workflow")+ message = EmailMessage(+ campaign_key=f"workflow_email_sending_warning_{hog_flow_id}_{warned_at}",+ # No urgency prefix in the subject, for the same deliverability reason as the emails above.+ subject=f"Email from '{workflow_label}' in project '{single_line(str(team))}' needs attention",+ template_name="workflow_email_sending_warning",+ template_context={+ "team": team,+ "hog_flow_name": workflow_label,+ "reason": reason,+ "pause_rate": pause_rate,+ "workflow_path": f"/project/{team.id}/workflows/{hog_flow_id}/workflow",+ },+ )+ for membership in memberships_to_email:+ message.add_user_recipient(membership.user)+ message.send()++@shared_task(**EMAIL_TASK_KWARGS)@with_team_scope()def send_email_sending_reputation_finding(diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 41c248fbbd08..8c073e78208c 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -137,6 +137,7 @@ from products.wizard.backend.facade.tasks import reconcile_wizard_runsfrom products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiersfrom products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputationfrom products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_states+from products.workflows.backend.tasks.workflow_email_health import sweep_workflow_email_deliverabilityTWENTY_FOUR_HOURS = 24 * 60 * 60@@ -447,6 +448,17 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:expires_seconds=10 * 60,)+ # Pause the email of any workflow whose complaint or hard bounce rate breaches a threshold+ # Hourly rather than a tight poll: the tier system's hourly send bucket bounds how much a+ # breaching workflow can send between runs, and the detection windows are 1h and 24h anyway.+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="35"),+ sweep_workflow_email_deliverability.s(),+ name="sweep workflow email deliverability",+ expires_seconds=30 * 60,+ )+# Flags cache sync - hourlysender.add_periodic_task(crontab(hour="*", minute="15"),diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex f649607caad8..3b605d0f9924 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -72,6 +72,8 @@'posthog.tasks.email.send_two_factor_auth_enabled_email','posthog.tasks.email.send_two_factor_reset_email','posthog.tasks.email.send_wizard_pr_ready_email',+ 'posthog.tasks.email.send_workflow_email_sending_paused',+ 'posthog.tasks.email.send_workflow_email_sending_warning','posthog.tasks.exporter.export_asset','posthog.tasks.gateway_credential.drain_gateway_credential_last_used_task','posthog.tasks.gateway_credential.refresh_gateway_credentials',diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 3536359b07f9..b38898d1bef2 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -1,6 +1,7 @@import uuidimport datetime as dtfrom typing import cast+from uuid import uuid4import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, run_clickhouse_statement_in_parallel@@ -48,6 +49,8 @@ from posthog.tasks.email import (send_provisioning_welcome,send_team_matview_failure_digest,send_wizard_pr_ready_email,+ send_workflow_email_sending_paused,+ send_workflow_email_sending_warning,should_send_pipeline_error_notification,)from posthog.tasks.test.utils_email_tests import mock_email_messages@@ -153,6 +156,38 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert mocked_email_messages[0].send.call_count == 1assert mocked_email_messages[0].html_body+ def test_workflow_email_subjects_survive_a_newline_in_the_name(self, MockEmailMessage: MagicMock) -> None:+ # A CR or LF in the workflow name would make Django reject the whole email as a multiline+ # header. The send path swallows that error, so a name with an embedded newline would+ # silently drop this notice to every project admin.+ mock_email_messages(MockEmailMessage)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ name_with_newline = "Welcome series\nBcc: [email protected]"++ send_workflow_email_sending_paused(+ team_id=self.team.id,+ hog_flow_id=str(uuid4()),+ hog_flow_name=name_with_newline,+ reason="Spam complaints reached 2% of the 400 emails this workflow sent in the last hour.",+ paused_at="2026-01-01T00:00:00+00:00",+ )+ send_workflow_email_sending_warning(+ team_id=self.team.id,+ hog_flow_id=str(uuid4()),+ hog_flow_name=name_with_newline,+ reason="Spam complaints reached 0.2% of the 10,000 emails this workflow sent in the last 24 hours.",+ pause_rate="0.3%",+ warned_at="2026-01-01T00:00:00+00:00",+ )++ subjects = [call.kwargs["subject"] for call in MockEmailMessage.call_args_list]+ assert len(subjects) == 2+ for subject in subjects:+ assert "\n" not in subject+ assert "\r" not in subject+ assert "Welcome series" in subject+def test_send_delegation_invite_falls_back_when_organization_name_is_a_url(self, MockEmailMessage: MagicMock) -> None:diff --git a/posthog/templates/email/workflow_email_sending_paused.html b/posthog/templates/email/workflow_email_sending_paused.htmlnew file mode 100644index 000000000000..9b29005af8d6--- /dev/null+++ b/posthog/templates/email/workflow_email_sending_paused.html@@ -0,0 +1,43 @@+{% extends "email/base.html" %}+{% load posthog_assets %}+{% block heading %}Email sending is paused for one workflow{% endblock %}+{% block section %}+ <!-- prettier-ignore -->+ <p>+ We paused email sending for the workflow <b>{{ hog_flow_name }}</b> in project <b>{{ team }}</b>. Only this workflow's email sending is paused; its other steps still run.+ </p>+ <p>+ Why: <b>{{ reason }}</b>+ </p>+ <p>+ Spam complaints and emails to addresses that do not exist tell mailbox providers that a sender is not worth delivering, and that judgment follows every PostHog customer sharing our sending reputation. Pausing one workflow's email keeps the rest of your email delivering.+ </p>+ <p>+ What to do next: remove old, bought or scraped addresses from this workflow's audience, stop sending to people who never open anything, and check that the content matches what recipients signed up for.{% if resumable %} Then resume sending from the workflow page.{% endif %}+ </p>+ {% if resumable %}+ <p>+ Sending pauses again automatically if the problem continues, so there is no need to wait on support before resuming.+ </p>+ {% else %}+ <p>+ PostHog staff paused this workflow's email sending, so only we can resume it. Contact support once you have cleaned up the audience.+ </p>+ {% endif %}+ <div class="mb mt text-center">+ <a class="button" href="{% absolute_uri workflow_path %}">Open workflow</a>+ </div>+ <div class="mt">+ <p>+ If the button above doesn't work, paste this link into your browser:+ <br />+ <a href="{% absolute_uri workflow_path %}">{% absolute_uri workflow_path %}</a>+ </p>+ </div>+{% endblock %}+{% block footer %}+ Need a hand cleaning up your list?+ <a href="https://posthog.com/questions?{{ utm_tags }}" target="_blank"><b>Contact support</b></a>+ or+ <a href="https://posthog.com/docs?{{ utm_tags }}" target="_blank"><b>read our documentation</b></a>.+{% endblock %}diff --git a/posthog/templates/email/workflow_email_sending_warning.html b/posthog/templates/email/workflow_email_sending_warning.htmlnew file mode 100644index 000000000000..b6c49342f79c--- /dev/null+++ b/posthog/templates/email/workflow_email_sending_warning.html@@ -0,0 +1,34 @@+{% extends "email/base.html" %}+{% load posthog_assets %}+{% block heading %}One workflow's email needs attention{% endblock %}+{% block section %}+ <!-- prettier-ignore -->+ <p>+ Email from the workflow <b>{{ hog_flow_name }}</b> in project <b>{{ team }}</b> is drawing more negative feedback than healthy sending should. This workflow's email is still sending, and nothing is paused.+ </p>+ <p>+ What we saw: <b>{{ reason }}</b>+ </p>+ <p>+ If this rate reaches <b>{{ pause_rate }}</b>, we pause this workflow's email automatically to protect delivery for your project and every other PostHog customer sharing our sending reputation. Acting now avoids that interruption.+ </p>+ <p>+ What to do: remove old, bought or scraped addresses from this workflow's audience, stop sending to people who never open anything, and check that the content matches what recipients signed up for.+ </p>+ <div class="mb mt text-center">+ <a class="button" href="{% absolute_uri workflow_path %}">Open workflow</a>+ </div>+ <div class="mt">+ <p>+ If the button above doesn't work, paste this link into your browser:+ <br />+ <a href="{% absolute_uri workflow_path %}">{% absolute_uri workflow_path %}</a>+ </p>+ </div>+{% endblock %}+{% block footer %}+ Need a hand cleaning up your list?+ <a href="https://posthog.com/questions?{{ utm_tags }}" target="_blank"><b>Contact support</b></a>+ or+ <a href="https://posthog.com/docs?{{ utm_tags }}" target="_blank"><b>read our documentation</b></a>.+{% endblock %}diff --git a/products/workflows/backend/admin/hog_flow_admin.py b/products/workflows/backend/admin/hog_flow_admin.pyindex d5c26caa36e1..c79f7ca529ec 100644--- a/products/workflows/backend/admin/hog_flow_admin.py+++ b/products/workflows/backend/admin/hog_flow_admin.py@@ -1,9 +1,25 @@-from django.contrib import admin+from django.contrib import admin, messages+from django.db.models import QuerySet+from django.http import HttpRequestfrom django.urls import reversefrom django.utils.html import format_html+import structlog+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule+from products.workflows.backend.services.workflow_email_health import (+ PAUSED_BY_STAFF,+ pause_workflow_email_sending,+ resume_workflow_email_sending,+)++logger = structlog.get_logger(__name__)++# What the customer is told when staff pause a workflow by hand rather than the detector doing it.+# Deliberately vague about the trigger: staff reach for this for reasons the detector cannot see,+# such as a report from a mailbox provider.+STAFF_PAUSE_REASON = "PostHog staff paused this workflow's email to protect delivery for everyone."class HogFlowScheduleInline(admin.TabularInline):@@ -19,14 +35,16 @@ class HogFlowScheduleInline(admin.TabularInline):@admin.register(HogFlow)class HogFlowAdmin(admin.ModelAdmin):inlines = [HogFlowScheduleInline]- list_display = ("id", "name", "status", "version", "team_link", "created_at")+ list_display = ("id", "name", "status", "version", "team_link", "email_sending_state", "created_at")list_filter = (("status", admin.ChoicesFieldListFilter),("updated_at", admin.DateFieldListFilter),+ ("email_sending_paused_at", admin.EmptyFieldListFilter),)list_select_related = ("team",)search_fields = ("name", "team__name", "team__organization__name")ordering = ("-created_at",)+ actions = ("pause_email_sending", "resume_email_sending")readonly_fields = ("id","version",@@ -42,6 +60,9 @@ class HogFlowAdmin(admin.ModelAdmin):"actions","variables","billable_action_types",+ "email_sending_paused_at",+ "email_sending_paused_reason",+ "email_sending_resumed_at",)fields = ("name",@@ -61,6 +82,9 @@ class HogFlowAdmin(admin.ModelAdmin):"actions","variables","billable_action_types",+ "email_sending_paused_at",+ "email_sending_paused_reason",+ "email_sending_resumed_at",)@admin.display(description="Team")@@ -70,3 +94,58 @@ class HogFlowAdmin(admin.ModelAdmin):reverse("admin:posthog_team_change", args=[hog_flow.team.pk]),hog_flow.team.name,)++ @admin.display(description="Email sending")+ def email_sending_state(self, hog_flow: HogFlow) -> str:+ if hog_flow.email_sending_paused_at is None:+ return "Sending"+ return format_html('<span style="color: #C0392B;">Paused {}</span>', hog_flow.email_sending_paused_at)++ @admin.action(description="Pause workflow email sending")+ def pause_email_sending(self, request: HttpRequest, queryset: QuerySet[HogFlow]) -> None:+ paused = 0+ for hog_flow in queryset.filter(email_sending_paused_at__isnull=True):+ if pause_workflow_email_sending(+ team_id=hog_flow.team_id,+ hog_flow_id=str(hog_flow.id),+ hog_flow_name=hog_flow.name or "",+ reason=STAFF_PAUSE_REASON,+ paused_by=PAUSED_BY_STAFF,+ ):+ paused += 1+ logger.warning(+ "admin_pause_workflow_email_sending",+ team_id=hog_flow.team_id,+ hog_flow_id=str(hog_flow.id),+ triggered_by=getattr(request.user, "email", None),+ )+ # Durable audit trail in the object's admin history: the bulk action bypasses+ # save_model, so without this the acting staff user is recorded only in the log+ # aggregator, not anywhere an audit view can show.+ self.log_change(request, hog_flow, "Paused email sending")+ self.message_user(+ request,+ f"Paused email sending for {paused} workflow(s). Workers pick this up within a few minutes; "+ "the project's admins have been notified. Only staff can resume a staff pause.",+ level=messages.WARNING if paused else messages.INFO,+ )++ @admin.action(description="Resume workflow email sending")+ def resume_email_sending(self, request: HttpRequest, queryset: QuerySet[HogFlow]) -> None:+ resumed = 0+ for hog_flow in queryset.filter(email_sending_paused_at__isnull=False):+ if resume_workflow_email_sending(hog_flow, actor=PAUSED_BY_STAFF):+ resumed += 1+ logger.info(+ "admin_resume_workflow_email_sending",+ team_id=hog_flow.team_id,+ hog_flow_id=str(hog_flow.id),+ triggered_by=getattr(request.user, "email", None),+ )+ self.log_change(request, hog_flow, "Resumed email sending")+ self.message_user(+ request,+ f"Resumed email sending for {resumed} workflow(s). The detector re-arms, so a workflow that is "+ "still generating complaints or hard bounces pauses again on its own.",+ level=messages.SUCCESS if resumed else messages.INFO,+ )diff --git a/products/workflows/backend/services/email_sending_attribution.py b/products/workflows/backend/services/email_sending_attribution.pynew file mode 100644index 000000000000..6ecc520a8c7f--- /dev/null+++ b/products/workflows/backend/services/email_sending_attribution.py@@ -0,0 +1,93 @@+import uuid as uuid_mod+from collections.abc import Mapping+from typing import Final++from django.db.models import QuerySet++from posthog.dataclasses import frozen++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob++# The app metric names the deliverability signals are read from. A Complaint (the recipient's+# "report spam" relayed through the provider's feedback loop) is recorded as `email_blocked`, and+# only permanent bounces count as `email_bounced_hard`, matching how AWS counts its bounce rate.+# See the SES webhook handler in nodejs/src/cdp/services/messaging/helpers/ses.ts.+SENT_METRIC: Final[str] = "email_sent"+HARD_BOUNCE_METRIC: Final[str] = "email_bounced_hard"+COMPLAINT_METRIC: Final[str] = "email_blocked"+EMAIL_HEALTH_METRIC_NAMES: Final[list[str]] = [SENT_METRIC, HARD_BOUNCE_METRIC, COMPLAINT_METRIC]+++@frozen+class EmailSendingCounts:+ sent: int = 0+ bounced_hard: int = 0+ complained: int = 0++ def plus(self, counts: Mapping[str, int]) -> "EmailSendingCounts":+ return EmailSendingCounts(+ sent=self.sent + counts.get(SENT_METRIC, 0),+ bounced_hard=self.bounced_hard + counts.get(HARD_BOUNCE_METRIC, 0),+ complained=self.complained + counts.get(COMPLAINT_METRIC, 0),+ )+++def looks_like_uuid(value: str) -> bool:+ try:+ uuid_mod.UUID(value)+ return True+ except (ValueError, AttributeError, TypeError):+ return False+++@frozen+class FlowEmailTotals:+ counts_by_flow: dict[str, EmailSendingCounts]+ names_by_flow_id: dict[str, str]+++def fold_email_totals_by_flow(+ *,+ team_id: int,+ totals_by_source: Mapping[str, Mapping[str, int]],+ flows: QuerySet[HogFlow],+) -> FlowEmailTotals:+ """Attribute per-`app_source_id` email metric totals to the workflow that produced them.++ Email metrics are recorded under the workflow id for event-triggered runs and under the+ `HogFlowBatchJob` id for batch runs, so a batch send looks like an unrelated source until its+ job is resolved back to its parent workflow. A large batch send is the case that matters most+ here, so both are resolved and the batch counts are folded into the parent.++ `flows` scopes which workflows can be attributed to, which lets an access-controlled caller+ pass a filtered queryset. Sources matching neither a workflow nor a batch job (a deleted+ workflow, a non-UUID id) are dropped. Unnamed workflows come back as `""` so the name stays a+ plain string.+ """+ source_ids = [source_id for source_id in totals_by_source if looks_like_uuid(source_id)]+ # Only names are needed and HogFlow rows are wide (full step graphs in edges/actions/draft), so+ # don't hydrate model instances for an uncapped id list.+ names_by_flow_id = {+ str(flow_id): name or "" for flow_id, name in flows.filter(id__in=source_ids).values_list("id", "name")+ }+ unmatched_ids = [source_id for source_id in source_ids if source_id not in names_by_flow_id]+ batch_job_to_flow = {+ str(batch_job_id): str(flow_id)+ for batch_job_id, flow_id in HogFlowBatchJob.objects.filter(team_id=team_id, id__in=unmatched_ids).values_list(+ "id", "hog_flow_id"+ )+ }+ missing_flow_ids = set(batch_job_to_flow.values()) - set(names_by_flow_id)+ names_by_flow_id.update(+ {str(flow_id): name or "" for flow_id, name in flows.filter(id__in=missing_flow_ids).values_list("id", "name")}+ )++ counts_by_flow: dict[str, EmailSendingCounts] = {}+ for source_id, counts in totals_by_source.items():+ flow_id = source_id if source_id in names_by_flow_id else batch_job_to_flow.get(source_id)+ if flow_id is None or flow_id not in names_by_flow_id:+ continue+ counts_by_flow[flow_id] = counts_by_flow.get(flow_id, EmailSendingCounts()).plus(counts)++ return FlowEmailTotals(counts_by_flow=counts_by_flow, names_by_flow_id=names_by_flow_id)diff --git a/products/workflows/backend/services/workflow_email_health.py b/products/workflows/backend/services/workflow_email_health.pynew file mode 100644index 000000000000..7ea9759b8f05--- /dev/null+++ b/products/workflows/backend/services/workflow_email_health.py@@ -0,0 +1,608 @@+from dataclasses import replace+from datetime import datetime, timedelta+from typing import Final, Literal++from django.conf import settings+from django.db import transaction+from django.db.models import Q+from django.utils import timezone++import structlog+from prometheus_client import Counter++from posthog.api.app_metrics2 import fetch_app_metric_totals_by_source, fetch_app_metric_totals_by_team_and_source+from posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.dataclasses import frozen+from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers+from posthog.schema_enums import ProductKey+from posthog.tasks.email import send_workflow_email_sending_paused, send_workflow_email_sending_warning++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.services.email_sending_attribution import (+ COMPLAINT_METRIC,+ EMAIL_HEALTH_METRIC_NAMES,+ HARD_BOUNCE_METRIC,+ SENT_METRIC,+ EmailSendingCounts,+ fold_email_totals_by_flow,+)++logger = structlog.get_logger(__name__)++APP_SOURCE: Final[str] = "hog_flow"++PAUSED_BY_AUTO: Final[str] = "auto"+PAUSED_BY_STAFF: Final[str] = "staff"+++class StaffPausedError(Exception):+ """A customer tried to resume a pause staff placed. Only staff may clear it."""+++Signal = Literal["complaint", "bounce"]++workflow_email_auto_pause_total = Counter(+ "workflow_email_auto_pause_total",+ "Workflows whose email the deliverability detector paused, or would have paused while it runs "+ "with enforcement off.",+ labelnames=["signal", "window", "mode"],+)++workflow_email_warning_total = Counter(+ "workflow_email_warning_total",+ "Workflows whose admins the deliverability detector warned about rates approaching the pause "+ "thresholds, or would have warned while it runs with enforcement off.",+ labelnames=["signal", "window", "mode"],+)+++@frozen+class DetectorThreshold:+ """One breach rule. Either signal firing over either window is enough to pause a workflow."""++ signal: Signal+ metric_name: str+ window: timedelta+ # Used in the log record, the metric label and the customer-facing reason.+ window_label: str+ window_description: str+ min_sent: int+ min_events: int+ rate: float+++def build_thresholds() -> list[DetectorThreshold]:+ """The live threshold table, read from settings on every sweep so a region can retune it+ without a deploy."""+ return [+ DetectorThreshold(+ signal="complaint",+ metric_name=COMPLAINT_METRIC,+ window=timedelta(hours=1),+ window_label="1h",+ window_description="the last hour",+ min_sent=settings.WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_1H,+ min_events=settings.WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_1H,+ rate=settings.WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_1H,+ ),+ DetectorThreshold(+ signal="complaint",+ metric_name=COMPLAINT_METRIC,+ window=timedelta(hours=24),+ window_label="24h",+ window_description="the last 24 hours",+ min_sent=settings.WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_24H,+ min_events=settings.WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_MIN_EVENTS_24H,+ rate=settings.WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_24H,+ ),+ DetectorThreshold(+ signal="bounce",+ metric_name=HARD_BOUNCE_METRIC,+ window=timedelta(hours=1),+ window_label="1h",+ window_description="the last hour",+ min_sent=settings.WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_1H,+ min_events=settings.WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_1H,+ rate=settings.WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_1H,+ ),+ DetectorThreshold(+ signal="bounce",+ metric_name=HARD_BOUNCE_METRIC,+ window=timedelta(hours=24),+ window_label="24h",+ window_description="the last 24 hours",+ min_sent=settings.WORKFLOW_EMAIL_AUTO_PAUSE_MIN_SENT_24H,+ min_events=settings.WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_MIN_EVENTS_24H,+ rate=settings.WORKFLOW_EMAIL_AUTO_PAUSE_BOUNCE_RATE_24H,+ ),+ ]+++def build_warn_thresholds() -> list[DetectorThreshold]:+ """The warning band's lower edge: the pause table with lower rates and the same volume gates.+ A workflow between a warn rate and its pause rate gets a heads-up email instead of a pause."""+ warn_rates = {+ ("complaint", "1h"): settings.WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_1H,+ ("complaint", "24h"): settings.WORKFLOW_EMAIL_WARN_COMPLAINT_RATE_24H,+ ("bounce", "1h"): settings.WORKFLOW_EMAIL_WARN_BOUNCE_RATE_1H,+ ("bounce", "24h"): settings.WORKFLOW_EMAIL_WARN_BOUNCE_RATE_24H,+ }+ return [+ replace(threshold, rate=warn_rates[(threshold.signal, threshold.window_label)])+ for threshold in build_thresholds()+ ]+++@frozen+class PauseDecision:+ team_id: int+ hog_flow_id: str+ hog_flow_name: str+ threshold: DetectorThreshold+ sent: int+ events: int+ rate: float++ @property+ def reason(self) -> str:+ """What the customer is told, in the pause email, the workflow banner and the API."""+ signal_text = (+ "Spam complaints" if self.threshold.signal == "complaint" else "Emails to addresses that do not exist"+ )+ return (+ f"{signal_text} reached {_format_rate(self.rate)} of the {self.sent:,} emails this workflow "+ f"sent in {self.threshold.window_description}."+ )+++def _format_rate(rate: float) -> str:+ percent = rate * 100+ # Complaint thresholds live below 1%, so a whole-number percentage would round a 0.3% breach+ # to "0%". Two decimals keep every threshold in the table readable.+ return f"{percent:.2f}".rstrip("0").rstrip(".") + "%"+++def _hour_floor(value: datetime) -> datetime:+ return value.replace(minute=0, second=0, microsecond=0)+++def _hour_ceil(value: datetime) -> datetime:+ floored = _hour_floor(value)+ return floored if floored == value else floored + timedelta(hours=1)+++def _rate(events: int, sent: int) -> float:+ # Sends are counted at send time but feedback when it arrives, so feedback landing just inside+ # the window for sends just outside it can push the ratio past 1. Clamp to 100%, matching the+ # reputation endpoint: past 100% the number stops meaning anything.+ return min(1.0, events / sent) if sent else 0.0+++def _discover_candidate_team_ids(*, now: datetime, thresholds: list[DetectorThreshold]) -> set[int]:+ """Find the teams worth looking at, with the volume gates pushed into ClickHouse.++ One pass per window across the whole fleet, never a query per team. The gates are applied at+ the team level, so a workflow whose feedback is spread across many batch jobs (none of them+ individually over a gate) still surfaces its team. Batch sends are the detector's main case,+ so per-source gating would let exactly that shape escape. Over-selection is fine: the second+ pass computes exact per-workflow totals before any decision.+ """+ candidate_team_ids: set[int] = set()+ before = _hour_floor(now)+ for window, group in _thresholds_by_window(thresholds).items():+ totals = fetch_app_metric_totals_by_team_and_source(+ app_source=APP_SOURCE,+ name=EMAIL_HEALTH_METRIC_NAMES,+ after=before - window,+ before=before,+ hour_aligned=True,+ per_source=False,+ min_totals={SENT_METRIC: min(threshold.min_sent for threshold in group)},+ any_min_totals={threshold.metric_name: threshold.min_events for threshold in group},+ )+ candidate_team_ids.update(totals)+ return candidate_team_ids+++def _thresholds_by_window(thresholds: list[DetectorThreshold]) -> dict[timedelta, list[DetectorThreshold]]:+ by_window: dict[timedelta, list[DetectorThreshold]] = {}+ for threshold in thresholds:+ by_window.setdefault(threshold.window, []).append(threshold)+ return by_window+++def _counts_by_flow(+ *, team_ids: list[int], after: datetime, before: datetime+) -> dict[int, tuple[dict[str, EmailSendingCounts], dict[str, str]]]:+ """Exact per-workflow totals for the candidate teams, with batch-job counts folded in.++ The discovery pass gates per `app_source_id`, so its rows alone would undercount a workflow's+ clean sends and read as a worse rate than the workflow really has. This second pass keeps no+ `HAVING`, so every source row for these teams is counted, which is what makes the rate the+ detector acts on the same number the Reputation tab shows.+ """+ totals_by_team = fetch_app_metric_totals_by_team_and_source(+ app_source=APP_SOURCE,+ name=EMAIL_HEALTH_METRIC_NAMES,+ after=after,+ before=before,+ hour_aligned=True,+ team_ids=team_ids,+ )+ folded: dict[int, tuple[dict[str, EmailSendingCounts], dict[str, str]]] = {}+ for team_id, totals_by_source in totals_by_team.items():+ result = fold_email_totals_by_flow(+ team_id=team_id, totals_by_source=totals_by_source, flows=HogFlow.objects.filter(team_id=team_id)+ )+ folded[team_id] = (result.counts_by_flow, result.names_by_flow_id)+ return folded+++def _clamped_counts_for_flow(*, flow: HogFlow, after: datetime, before: datetime) -> EmailSendingCounts:+ """Totals for one workflow over a window that starts after its last resume."""+ if after >= before:+ # No complete hour has passed since the resume, so there is nothing judgeable yet.+ return EmailSendingCounts()+ totals_by_source = fetch_app_metric_totals_by_source(+ team_id=flow.team_id,+ app_source=APP_SOURCE,+ after=after,+ before=before,+ hour_aligned=True,+ name=EMAIL_HEALTH_METRIC_NAMES,+ )+ result = fold_email_totals_by_flow(+ team_id=flow.team_id,+ totals_by_source=totals_by_source,+ flows=HogFlow.objects.filter(id=flow.id),+ )+ return result.counts_by_flow.get(str(flow.id), EmailSendingCounts())+++def _events_for_signal(counts: EmailSendingCounts, signal: Signal) -> int:+ return counts.complained if signal == "complaint" else counts.bounced_hard+++def _breach(+ *,+ flow: HogFlow,+ flow_name: str,+ counts: EmailSendingCounts,+ threshold: DetectorThreshold,+) -> PauseDecision | None:+ events = _events_for_signal(counts, threshold.signal)+ # Both volume gates first: 1 complaint out of 12 sends is a 8% rate and no information.+ if counts.sent < threshold.min_sent or events < threshold.min_events:+ return None+ rate = _rate(events, counts.sent)+ if rate < threshold.rate:+ return None+ return PauseDecision(+ team_id=flow.team_id,+ hog_flow_id=str(flow.id),+ hog_flow_name=flow_name,+ threshold=threshold,+ sent=counts.sent,+ events=events,+ rate=rate,+ )+++@frozen+class DetectorDecisions:+ pauses: list[PauseDecision]+ # Workflows inside the warning band: over a warn rate, under every pause rate, and not warned+ # within the cooldown. A workflow never appears in both lists; the pause wins.+ warnings: list[PauseDecision]+++def find_workflow_email_pauses(*, now: datetime | None = None) -> list[PauseDecision]:+ """Decide which workflows have earned an email pause. Reads only; writes nothing."""+ return find_workflow_email_decisions(now=now).pauses+++def find_workflow_email_decisions(*, now: datetime | None = None) -> DetectorDecisions:+ """Decide which workflows have earned an email pause, and which are approaching one and get a+ warning instead. Reads only; writes nothing."""+ now = now or timezone.now()+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.ENRICHMENT)+ thresholds = build_thresholds()+ warn_thresholds = build_warn_thresholds()++ candidate_team_ids = _discover_candidate_team_ids(now=now, thresholds=thresholds)+ if not candidate_team_ids:+ return DetectorDecisions(pauses=[], warnings=[])++ # Already-paused workflows are skipped: the pause is in force and a second decision would only+ # re-notify. Resuming is what puts a workflow back in scope.+ flows_by_id = {+ str(flow.id): flow+ for flow in HogFlow.objects.filter(team_id__in=candidate_team_ids, email_sending_paused_at__isnull=True).only(+ "id", "team_id", "name", "email_sending_resumed_at", "email_sending_warned_at"+ )+ }+ if not flows_by_id:+ return DetectorDecisions(pauses=[], warnings=[])++ warn_cutoff = now - timedelta(days=settings.WORKFLOW_EMAIL_WARN_COOLDOWN_DAYS)+ pauses: list[PauseDecision] = []+ warnings_by_flow: dict[str, PauseDecision] = {}+ paused_flow_ids: set[str] = set()+ # Whole hours only: the metrics table collapses rows per clock hour with an arbitrary surviving+ # raw timestamp, so a mid-hour bound would include or exclude a whole collapsed hour by merge+ # luck, and the two sides of a rate could disagree about the edge hour. The current partial+ # hour is excluded, which adds up to an hour of detection lag on top of the hourly cadence.+ window_end = _hour_floor(now)+ for window, group in sorted(_thresholds_by_window(thresholds).items()):+ window_start = window_end - window+ warn_group = [threshold for threshold in warn_thresholds if threshold.window == window]+ counts_by_team = _counts_by_flow(team_ids=sorted(candidate_team_ids), after=window_start, before=window_end)+ for team_id, (counts_by_flow, names_by_flow_id) in counts_by_team.items():+ for flow_id, counts in counts_by_flow.items():+ flow = flows_by_id.get(flow_id)+ # One pause per workflow per sweep. The first breach is the one reported, and the+ # windows are walked shortest first so the reason names the tightest signal.+ if flow is None or flow.team_id != team_id or flow_id in paused_flow_ids:+ continue+ effective_counts = counts+ resumed_at = flow.email_sending_resumed_at+ if resumed_at is not None and _hour_ceil(resumed_at) > window_start:+ # Re-arm after a resume. Without this, feedback that arrived before the pause+ # is still inside the window, so resuming would immediately re-trip on it.+ # The clamp starts at the first full hour after the resume: the resume hour's+ # rows can hold pre-resume feedback merged with post-resume feedback, so that+ # partial hour is not judgeable either way.+ effective_counts = _clamped_counts_for_flow(+ flow=flow, after=_hour_ceil(resumed_at), before=window_end+ )+ flow_name = names_by_flow_id.get(flow_id, "")+ for threshold in group:+ decision = _breach(flow=flow, flow_name=flow_name, counts=effective_counts, threshold=threshold)+ if decision is not None:+ pauses.append(decision)+ paused_flow_ids.add(flow_id)+ break+ if flow_id in paused_flow_ids or flow_id in warnings_by_flow:+ continue+ warned_at = flow.email_sending_warned_at+ if warned_at is not None and warned_at > warn_cutoff:+ continue+ for threshold in warn_group:+ decision = _breach(flow=flow, flow_name=flow_name, counts=effective_counts, threshold=threshold)+ if decision is not None:+ warnings_by_flow[flow_id] = decision+ break+ # A pause found in a longer window outranks a warning found in a shorter one, so the warning+ # list is settled only after every window ran.+ warnings = [decision for flow_id, decision in warnings_by_flow.items() if flow_id not in paused_flow_ids]+ return DetectorDecisions(pauses=pauses, warnings=warnings)+++def pause_workflow_email_sending(+ *,+ team_id: int,+ hog_flow_id: str,+ hog_flow_name: str,+ reason: str,+ paused_by: str = PAUSED_BY_AUTO,+ now: datetime | None = None,+) -> bool:+ """Pause one workflow's email and tell the project's admins.++ Returns False if it was already paused, which is how two overlapping sweeps stay down to one+ notification. The row is locked for the read-compare-write so the loser sees the pause.+ """+ now = now or timezone.now()+ with transaction.atomic():+ flow = (+ HogFlow.objects.select_for_update()+ .filter(id=hog_flow_id, team_id=team_id)+ .only("id", "team_id", "email_sending_paused_at")+ .first()+ )+ if flow is None or flow.email_sending_paused_at is not None:+ return False+ # A queryset update rather than save: the post_save signal publishes the worker reload+ # immediately, and inside this transaction that is before the pause commits, so a worker+ # could reload, read the still-unpaused row, and cache it for minutes. The explicit publish+ # below waits for the commit; it is what stops in-flight runs and queued batch sends.+ HogFlow.objects.filter(id=hog_flow_id, team_id=team_id).update(+ email_sending_paused_at=now,+ email_sending_paused_reason=reason,+ email_sending_paused_by=paused_by,+ )+ # Robust: a failing reload publish must not stop the callbacks after it. Without this, the+ # pause commits but the admin email is never queued, and later runs skip the already-paused+ # workflow, so the notification is never retried. Workers still catch up on cache expiry.+ transaction.on_commit(+ lambda: reload_hog_flows_on_workers(team_id=team_id, hog_flow_ids=[hog_flow_id]), robust=True+ )+ # Dispatch after commit so a rollback can't leave an email claiming a pause that was never+ # persisted.+ transaction.on_commit(+ lambda: send_workflow_email_sending_paused.delay(+ team_id=team_id,+ hog_flow_id=hog_flow_id,+ hog_flow_name=hog_flow_name,+ reason=reason,+ paused_at=now.isoformat(),+ resumable=paused_by != PAUSED_BY_STAFF,+ )+ )+ return True+++def apply_pause(decision: PauseDecision, *, now: datetime | None = None) -> bool:+ return pause_workflow_email_sending(+ team_id=decision.team_id,+ hog_flow_id=decision.hog_flow_id,+ hog_flow_name=decision.hog_flow_name,+ reason=decision.reason,+ now=now,+ )+++def apply_warning(decision: PauseDecision, *, now: datetime | None = None) -> bool:+ """Stamp the warning and email the project's admins. Returns False when another run got there+ first, or the workflow was paused or warned within the cooldown in the meantime.++ A filtered `update` rather than `save`: the compare-and-set keeps two overlapping runs down to+ one email, and skipping the model signal spares the workers a config reload for a field the+ send path never reads.+ """+ now = now or timezone.now()+ warn_cutoff = now - timedelta(days=settings.WORKFLOW_EMAIL_WARN_COOLDOWN_DAYS)+ with transaction.atomic():+ updated = (+ HogFlow.objects.filter(+ id=decision.hog_flow_id, team_id=decision.team_id, email_sending_paused_at__isnull=True+ )+ .filter(Q(email_sending_warned_at__isnull=True) | Q(email_sending_warned_at__lte=warn_cutoff))+ .update(email_sending_warned_at=now)+ )+ if not updated:+ return False+ pause_rate = _pause_rate_for(decision.threshold)+ transaction.on_commit(+ lambda: send_workflow_email_sending_warning.delay(+ team_id=decision.team_id,+ hog_flow_id=decision.hog_flow_id,+ hog_flow_name=decision.hog_flow_name,+ reason=decision.reason,+ pause_rate=_format_rate(pause_rate),+ warned_at=now.isoformat(),+ )+ )+ return True+++def _pause_rate_for(warn_threshold: DetectorThreshold) -> float:+ """The pause rate paired with a warn threshold, named in the warning email so the customer+ knows where the line is."""+ for threshold in build_thresholds():+ if threshold.signal == warn_threshold.signal and threshold.window_label == warn_threshold.window_label:+ return threshold.rate+ return warn_threshold.rate+++def sweep_workflow_email_health(*, now: datetime | None = None) -> list[PauseDecision]:+ """Find workflows breaching a complaint or hard bounce threshold and pause their email.++ All workflow email shares one SES account, so complaints and hard bounces from any one project+ degrade delivery for every customer. This pauses the offending workflow only, which is the+ enforcement step that sits between doing nothing and suspending a whole project by hand.++ Workflows approaching a threshold get a warning email instead, so their admins can clean up+ the audience before the pause. The same flag covers both: warnings and pauses turn on together.++ While `WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED` is off nothing is written. Each decision is still+ logged and counted, which is how the thresholds get calibrated before anything enforces.+ """+ now = now or timezone.now()+ decisions = find_workflow_email_decisions(now=now)+ enabled = settings.WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED+ applied: list[PauseDecision] = []+ failed = 0+ for decision in decisions.pauses:+ if not enabled:+ workflow_email_auto_pause_total.labels(+ signal=decision.threshold.signal, window=decision.threshold.window_label, mode="dry_run"+ ).inc()+ logger.info("would_pause_workflow_email_sending", **_decision_log_fields(decision))+ continue+ try:+ # One writer's Redis, database or broker error must not drop every later pause and+ # warning in this sweep. Isolate it so the remaining workflows are still processed; the+ # next hourly run retries the ones left at risk.+ paused = apply_pause(decision, now=now)+ except Exception:+ failed += 1+ logger.exception("pause_workflow_email_sending_failed", **_decision_log_fields(decision))+ continue+ if not paused:+ continue+ applied.append(decision)+ workflow_email_auto_pause_total.labels(+ signal=decision.threshold.signal, window=decision.threshold.window_label, mode="applied"+ ).inc()+ logger.warning("paused_workflow_email_sending", **_decision_log_fields(decision))+ for decision in decisions.warnings:+ if not enabled:+ workflow_email_warning_total.labels(+ signal=decision.threshold.signal, window=decision.threshold.window_label, mode="dry_run"+ ).inc()+ logger.info("would_warn_workflow_email_sending", **_decision_log_fields(decision))+ continue+ try:+ warned = apply_warning(decision, now=now)+ except Exception:+ failed += 1+ logger.exception("warn_workflow_email_sending_failed", **_decision_log_fields(decision))+ continue+ if not warned:+ continue+ workflow_email_warning_total.labels(+ signal=decision.threshold.signal, window=decision.threshold.window_label, mode="applied"+ ).inc()+ logger.warning("warned_workflow_email_sending", **_decision_log_fields(decision))+ if failed:+ logger.warning("workflow_email_health_sweep_partial_failure", failed=failed)+ return applied+++def _decision_log_fields(decision: PauseDecision) -> dict[str, str | int | float]:+ return {+ "team_id": decision.team_id,+ "hog_flow_id": decision.hog_flow_id,+ "hog_flow_name": decision.hog_flow_name,+ "signal": decision.threshold.signal,+ "window": decision.threshold.window_label,+ "emails_sent": decision.sent,+ "events": decision.events,+ "rate": decision.rate,+ "threshold_rate": decision.threshold.rate,+ }+++def resume_workflow_email_sending(flow: HogFlow, *, actor: str = "customer", now: datetime | None = None) -> bool:+ """Clear a workflow's pause. Returns False when it was not paused.++ A staff pause exists because the automatic thresholds could not see the problem, so a customer+ must not be able to clear it: only `actor="staff"` may. Raises StaffPausedError so the API can+ tell the customer to contact support instead of reporting "not paused". The row is locked and+ re-read inside the transaction: the caller's instance can be stale, and a customer resume that+ checked an automatic pause must not clear a staff pause that landed in between.++ `email_sending_resumed_at` is what re-arms the detector: every window is clamped to start at+ the first full hour after it, so a workflow that is still misbehaving trips again within a+ couple of hours on fresh feedback instead of on the feedback that caused the first pause.+ """+ now = now or timezone.now()+ with transaction.atomic():+ locked = (+ HogFlow.objects.select_for_update()+ .filter(id=flow.id, team_id=flow.team_id)+ .only("id", "team_id", "email_sending_paused_at", "email_sending_paused_by")+ .first()+ )+ if locked is None or locked.email_sending_paused_at is None:+ return False+ if actor != PAUSED_BY_STAFF and locked.email_sending_paused_by == PAUSED_BY_STAFF:+ raise StaffPausedError("Only PostHog staff can resume this pause.")+ # Queryset update for the same reason as the pause writer: the reload must publish only+ # once the resume is committed.+ HogFlow.objects.filter(id=flow.id, team_id=flow.team_id).update(+ email_sending_paused_at=None,+ email_sending_paused_reason="",+ email_sending_paused_by="",+ email_sending_resumed_at=now,+ )+ transaction.on_commit(+ lambda: reload_hog_flows_on_workers(team_id=flow.team_id, hog_flow_ids=[str(flow.id)]), robust=True+ )+ # The caller serializes these back to the customer, so mirror what was written.+ flow.email_sending_paused_at = None+ flow.email_sending_paused_reason = ""+ flow.email_sending_paused_by = ""+ flow.email_sending_resumed_at = now+ return Truediff --git a/products/workflows/backend/tasks/workflow_email_health.py b/products/workflows/backend/tasks/workflow_email_health.pynew file mode 100644index 000000000000..15e044e7d870--- /dev/null+++ b/products/workflows/backend/tasks/workflow_email_health.py@@ -0,0 +1,17 @@+from celery import shared_task+from structlog import get_logger++from posthog.tasks.utils import CeleryQueue++from products.workflows.backend.services.workflow_email_health import sweep_workflow_email_health++logger = get_logger(__name__)+++@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)+def sweep_workflow_email_deliverability() -> None:+ """Pause the email of any workflow whose spam complaint or hard bounce rate breaches a+ threshold. Off by default: see WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED."""+ applied = sweep_workflow_email_health()+ if applied:+ logger.warning("workflow_email_auto_pause_sweep_applied", paused=len(applied))diff --git a/products/workflows/backend/test/test_hog_flow_admin.py b/products/workflows/backend/test/test_hog_flow_admin.pynew file mode 100644index 000000000000..404ff0949418--- /dev/null+++ b/products/workflows/backend/test/test_hog_flow_admin.py@@ -0,0 +1,58 @@+from unittest.mock import patch++from django.contrib.admin.models import CHANGE, LogEntry+from django.contrib.admin.sites import AdminSite+from django.contrib.contenttypes.models import ContentType+from django.contrib.messages.storage.fallback import FallbackStorage+from django.contrib.sessions.backends.db import SessionStore+from django.http import HttpRequest+from django.test import RequestFactory, TestCase+from django.utils import timezone++from posthog.models.user import User++from products.workflows.backend.admin.hog_flow_admin import HogFlowAdmin+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+++class TestHogFlowAdminEmailAudit(TestCase):+ def setUp(self) -> None:+ super().setUp()+ _, self.team, self.user = User.objects.bootstrap("Org", "[email protected]", None)+ self.admin = HogFlowAdmin(HogFlow, AdminSite())+ self.flow = HogFlow.objects.create(name="Welcome", team=self.team)++ def _request(self) -> HttpRequest:+ request = RequestFactory().post("/")+ request.user = self.user+ # Admin actions call message_user, which needs a message store on the request.+ request.session = SessionStore()+ # Set on the raw request only in tests; MessageMiddleware owns the attribute at runtime.+ request._messages = FallbackStorage(request) # type: ignore[attr-defined]+ return request++ def _admin_history(self) -> LogEntry:+ return LogEntry.objects.get(+ content_type=ContentType.objects.get_for_model(HogFlow),+ object_id=str(self.flow.pk),+ )++ @patch("products.workflows.backend.admin.hog_flow_admin.pause_workflow_email_sending", return_value=True)+ def test_manual_pause_records_admin_history(self, _mock_pause: object) -> None:+ self.admin.pause_email_sending(self._request(), HogFlow.objects.filter(pk=self.flow.pk))++ entry = self._admin_history()+ assert entry.user_id == self.user.pk+ assert entry.action_flag == CHANGE+ assert "Paused" in entry.change_message++ @patch("products.workflows.backend.admin.hog_flow_admin.resume_workflow_email_sending", return_value=True)+ def test_manual_resume_records_admin_history(self, _mock_resume: object) -> None:+ self.flow.email_sending_paused_at = timezone.now()+ self.flow.save(update_fields=["email_sending_paused_at"])++ self.admin.resume_email_sending(self._request(), HogFlow.objects.filter(pk=self.flow.pk))++ entry = self._admin_history()+ assert entry.user_id == self.user.pk+ assert "Resumed" in entry.change_messagediff --git a/products/workflows/backend/test/test_workflow_email_health.py b/products/workflows/backend/test/test_workflow_email_health.pynew file mode 100644index 000000000000..c6b244097766--- /dev/null+++ b/products/workflows/backend/test/test_workflow_email_health.py@@ -0,0 +1,408 @@+from datetime import datetime, timedelta++from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.test import override_settings+from django.utils import timezone++from parameterized import parameterized++from posthog.test.fixtures import create_app_metric2++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.services.workflow_email_health import (+ PAUSED_BY_STAFF,+ StaffPausedError,+ find_workflow_email_pauses,+ pause_workflow_email_sending,+ resume_workflow_email_sending,+ sweep_workflow_email_health,+)++AUTO_PAUSE_ON = {"WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED": True}+++@override_settings(**AUTO_PAUSE_ON)+class TestWorkflowEmailHealthDetector(ClickhouseTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ # The detector reads whole clock hours and excludes the current partial hour, so seeds+ # default to the previous hour (see _seed). Pinned late in the hour so relative offsets in+ # individual tests stay inside the hour they aim for. Keeping the date today, rather than+ # an absolute one, avoids drifting out of any window.+ self.now = timezone.now().replace(minute=50, second=0, microsecond=0)+ self._seed_count = 0+ self.flow = HogFlow.objects.create(name="Welcome email", team=self.team)++ def _seed(+ self,+ *,+ source_id: str | None = None,+ sent: int = 0,+ complaints: int = 0,+ hard_bounces: int = 0,+ at: datetime | None = None,+ instance: str | None = None,+ ) -> None:+ # The previous hour by default: the detector reads complete hours only, so a seed in the+ # current (partial) hour is invisible to it.+ timestamp = at or self.now - timedelta(hours=1)+ # app_metrics2 keys rows on (…, instance_id, toStartOfHour(timestamp), …), so two seeds in+ # the same clock hour would collapse into one row and keep just one of the timestamps.+ # A distinct instance per call keeps them separate whatever time the suite runs at.+ self._seed_count += 1+ instance_id = instance or f"instance-{self._seed_count}"+ for metric_name, count in (+ ("email_sent", sent),+ ("email_blocked", complaints),+ ("email_bounced_hard", hard_bounces),+ ):+ if count:+ create_app_metric2(+ team_id=self.team.pk,+ app_source="hog_flow",+ app_source_id=source_id or str(self.flow.id),+ instance_id=instance_id,+ metric_kind="email",+ metric_name=metric_name,+ count=count,+ timestamp=timestamp,+ )++ def _sweep(self):+ with (+ patch(+ "products.workflows.backend.services.workflow_email_health.send_workflow_email_sending_paused"+ ) as paused_email,+ patch(+ "products.workflows.backend.services.workflow_email_health.send_workflow_email_sending_warning"+ ) as warning_email,+ self.captureOnCommitCallbacks(execute=True),+ ):+ applied = sweep_workflow_email_health(now=self.now)+ self.warning_email = warning_email.delay+ return applied, paused_email.delay++ def test_complaint_breach_pauses_the_workflow_and_notifies(self):+ self._seed(sent=400, complaints=8)++ applied, paused_email = self._sweep()++ assert [decision.hog_flow_id for decision in applied] == [str(self.flow.id)]+ assert applied[0].threshold.signal == "complaint"+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is not None+ assert "Spam complaints reached 2%" in self.flow.email_sending_paused_reason+ assert paused_email.call_count == 1+ # The rate is over the warn band too; the pause outranks the warning, so only one email.+ assert self.warning_email.call_count == 0++ def test_hard_bounce_breach_pauses_the_workflow(self):+ self._seed(sent=400, hard_bounces=60)++ applied, _ = self._sweep()++ assert [decision.threshold.signal for decision in applied] == ["bounce"]+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is not None+ assert "addresses that do not exist reached 15%" in self.flow.email_sending_paused_reason++ @parameterized.expand(+ [+ # Rate is over the 1h complaint threshold, but too few sends to mean anything.+ ("complaints below the send gate", {"sent": 100, "complaints": 8}),+ # Enough sends, but a single complaint is noise rather than a pattern.+ ("complaints below the event gate", {"sent": 5000, "complaints": 4}),+ ("hard bounces below the send gate", {"sent": 100, "hard_bounces": 60}),+ ("hard bounces below the event gate", {"sent": 5000, "hard_bounces": 19}),+ # Both gates met, but the rate stays under every threshold in the table.+ ("rate under the threshold", {"sent": 20000, "complaints": 20, "hard_bounces": 60}),+ ]+ )+ def test_does_not_pause_below_the_thresholds(self, _name: str, counts: dict[str, int]):+ self._seed(+ sent=counts.get("sent", 0),+ complaints=counts.get("complaints", 0),+ hard_bounces=counts.get("hard_bounces", 0),+ )++ applied, paused_email = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None+ assert paused_email.call_count == 0+ assert self.warning_email.call_count == 0++ # Creating a HogFlowBatchJob fires a post_save signal that dispatches to the plugin server —+ # patched out like every other batch-job test, or the outbound HTTP attempt fails the test.+ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_batch_job_metrics_fold_into_the_parent_workflow(self, _mock_dispatch):+ # A batch send records its metrics under the batch job id, so without resolving the job back+ # to its parent this is the case the detector would miss entirely.+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.flow)+ self._seed(source_id=str(batch_job.id), sent=5000, complaints=60)++ applied, _ = self._sweep()++ assert [decision.hog_flow_id for decision in applied] == [str(self.flow.id)]+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is not None++ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_clean_batch_send_keeps_a_workflow_below_the_threshold(self, _mock_dispatch):+ # The discovery pass gates per source id, so counting only the rows it returns would read the+ # workflow-id row's 5% complaint rate and pause a workflow that is really at 0.1%.+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.flow)+ self._seed(sent=300, complaints=15)+ self._seed(source_id=str(batch_job.id), sent=20000, complaints=1)++ applied, _ = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None++ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_breach_split_across_batch_jobs_is_still_discovered(self, _mock_dispatch):+ # Each batch job sits under the per-source volume gates, so per-source discovery gating+ # would never surface the team even though the workflow's aggregate breaches the 1h rule.+ job_1 = HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.flow)+ job_2 = HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.flow)+ self._seed(source_id=str(job_1.id), sent=100, complaints=3)+ self._seed(source_id=str(job_2.id), sent=100, complaints=3)++ applied, _ = self._sweep()++ assert [decision.hog_flow_id for decision in applied] == [str(self.flow.id)]++ def test_a_failing_worker_reload_does_not_drop_the_admin_email(self):+ # The reload callback runs before the email callback. Without robust registration, its+ # failure stops the remaining callbacks: the pause commits, the admins are never told, and+ # later runs skip the paused workflow, so the email is never retried.+ self._seed(sent=400, complaints=8)+ with (+ patch(+ "products.workflows.backend.services.workflow_email_health.send_workflow_email_sending_paused"+ ) as paused_email,+ patch("products.workflows.backend.services.workflow_email_health.send_workflow_email_sending_warning"),+ patch(+ "products.workflows.backend.services.workflow_email_health.reload_hog_flows_on_workers",+ side_effect=Exception("redis down"),+ ),+ self.captureOnCommitCallbacks(execute=True),+ ):+ applied = sweep_workflow_email_health(now=self.now)++ assert len(applied) == 1+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is not None+ assert paused_email.delay.call_count == 1++ def test_window_starts_after_the_last_resume(self):+ # Breach feedback two hours back, resume a few minutes later in the same hour: the clamp+ # starts at the next full hour, so the pre-resume feedback is out of scope.+ self._seed(sent=400, complaints=8, at=self.now - timedelta(hours=2))+ self.flow.email_sending_resumed_at = self.now - timedelta(hours=2) + timedelta(minutes=5)+ self.flow.save(update_fields=["email_sending_resumed_at"])++ applied, _ = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None++ def test_feedback_after_a_resume_still_trips(self):+ self._seed(sent=400, complaints=8, at=self.now - timedelta(hours=2))+ self._seed(sent=400, complaints=8, at=self.now - timedelta(hours=1))+ self.flow.email_sending_resumed_at = self.now - timedelta(hours=2) + timedelta(minutes=5)+ self.flow.save(update_fields=["email_sending_resumed_at"])++ applied, _ = self._sweep()++ assert [decision.hog_flow_id for decision in applied] == [str(self.flow.id)]++ def test_already_paused_workflow_is_not_paused_again(self):+ self._seed(sent=400, complaints=8)+ self.flow.email_sending_paused_at = self.now - timedelta(hours=2)+ self.flow.email_sending_paused_reason = "Earlier pause"+ self.flow.save(update_fields=["email_sending_paused_at", "email_sending_paused_reason"])++ applied, paused_email = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_reason == "Earlier pause"+ assert paused_email.call_count == 0++ def test_warn_band_warns_without_pausing(self):+ # 0.2% complaints over 24h: above the 0.15% warn rate, below the 0.3% pause rate.+ self._seed(sent=10000, complaints=20)++ applied, paused_email = self._sweep()++ assert applied == []+ assert paused_email.call_count == 0+ assert self.warning_email.call_count == 1+ assert self.warning_email.call_args.kwargs["hog_flow_id"] == str(self.flow.id)+ assert self.warning_email.call_args.kwargs["pause_rate"] == "0.3%"+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None+ assert self.flow.email_sending_warned_at is not None++ def test_warning_is_not_repeated_within_the_cooldown(self):+ self._seed(sent=10000, complaints=20)+ self.flow.email_sending_warned_at = self.now - timedelta(days=1)+ self.flow.save(update_fields=["email_sending_warned_at"])++ self._sweep()++ assert self.warning_email.call_count == 0++ def test_warning_repeats_once_the_cooldown_passed(self):+ self._seed(sent=10000, complaints=20)+ self.flow.email_sending_warned_at = self.now - timedelta(days=8)+ self.flow.save(update_fields=["email_sending_warned_at"])++ self._sweep()++ assert self.warning_email.call_count == 1++ def test_a_failing_writer_does_not_abort_the_other_decisions(self):+ # One workflow breaches (a pause) and another sits in the warn band. The pause loop runs+ # before the warning loop, so a raising pause writer that was not isolated would take the+ # warning down with it.+ self._seed(sent=400, complaints=8)+ other = HogFlow.objects.create(name="Newsletter", team=self.team)+ self._seed(source_id=str(other.id), sent=10000, complaints=20)++ with patch(+ "products.workflows.backend.services.workflow_email_health.apply_pause",+ side_effect=RuntimeError("worker reload publish failed"),+ ):+ applied, _ = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None+ assert self.warning_email.call_count == 1+ assert self.warning_email.call_args.kwargs["hog_flow_id"] == str(other.id)++ @override_settings(WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED=False)+ def test_dry_run_does_not_warn(self):+ self._seed(sent=10000, complaints=20)++ self._sweep()++ assert self.warning_email.call_count == 0+ self.flow.refresh_from_db()+ assert self.flow.email_sending_warned_at is None++ @override_settings(WORKFLOW_EMAIL_AUTO_PAUSE_ENABLED=False)+ def test_dry_run_finds_the_breach_but_writes_nothing(self):+ self._seed(sent=400, complaints=8)++ applied, paused_email = self._sweep()++ assert applied == []+ assert [decision.hog_flow_id for decision in find_workflow_email_pauses(now=self.now)] == [str(self.flow.id)]+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None+ assert self.flow.email_sending_paused_reason == ""+ assert paused_email.call_count == 0++ @override_settings(WORKFLOW_EMAIL_AUTO_PAUSE_COMPLAINT_RATE_1H=0.5)+ def test_thresholds_come_from_settings(self):+ self._seed(sent=400, complaints=8)++ applied, _ = self._sweep()++ assert applied == []++ def test_resume_clears_the_pause_and_stamps_the_resume_time(self):+ self.flow.email_sending_paused_at = self.now - timedelta(hours=1)+ self.flow.email_sending_paused_reason = "Spam complaints reached 2%."+ self.flow.save(update_fields=["email_sending_paused_at", "email_sending_paused_reason"])++ assert resume_workflow_email_sending(self.flow) is True++ # A fresh instance rather than refresh_from_db: mypy narrows the attribute to datetime at+ # the assignment above and treats the is-None assert on the same instance as unreachable.+ refreshed = HogFlow.objects.get(pk=self.flow.pk)+ assert refreshed.email_sending_paused_at is None+ assert refreshed.email_sending_paused_reason == ""+ assert refreshed.email_sending_resumed_at is not None++ def test_a_detector_pause_is_customer_resumable_and_a_staff_pause_is_not(self):+ self._seed(sent=400, complaints=8)+ self._sweep()+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_by == "auto"+ assert resume_workflow_email_sending(self.flow) is True++ with patch("products.workflows.backend.services.workflow_email_health.send_workflow_email_sending_paused"):+ with self.captureOnCommitCallbacks(execute=True):+ pause_workflow_email_sending(+ team_id=self.team.pk,+ hog_flow_id=str(self.flow.id),+ hog_flow_name=self.flow.name or "",+ reason="Staff pause",+ paused_by=PAUSED_BY_STAFF,+ )+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_by == "staff"+ try:+ resume_workflow_email_sending(self.flow)+ raise AssertionError("customer resume of a staff pause must raise")+ except StaffPausedError:+ pass+ assert resume_workflow_email_sending(self.flow, actor=PAUSED_BY_STAFF) is True+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_by == ""++ def test_a_stale_instance_cannot_clear_a_staff_pause_placed_in_between(self):+ # The API loads the workflow before calling resume. A staff pause landing between that read+ # and the write must win: the resume re-reads under lock, sees "staff", and refuses.+ self._seed(sent=400, complaints=8)+ self._sweep()+ stale = HogFlow.objects.get(pk=self.flow.pk)+ assert stale.email_sending_paused_by == "auto"+ HogFlow.objects.filter(pk=self.flow.pk).update(email_sending_paused_by=PAUSED_BY_STAFF)++ try:+ resume_workflow_email_sending(stale)+ raise AssertionError("stale customer resume must not clear a staff pause")+ except StaffPausedError:+ pass+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is not None++ def test_a_resume_hour_shared_with_old_feedback_is_not_judged(self):+ # Production stamps one instance id (the action id) on every row, so pre-resume and+ # post-resume feedback in the resume's own hour merge into a single hourly row. That mixed+ # hour is excluded by the clamp: the detector must not re-trip on it, and only a later full+ # hour of fresh feedback counts.+ hour = self.now - timedelta(hours=1)+ self._seed(sent=400, complaints=8, at=hour, instance="shared-action-id")+ self._seed(sent=400, complaints=8, at=hour + timedelta(minutes=8), instance="shared-action-id")+ self.flow.email_sending_resumed_at = hour + timedelta(minutes=4)+ self.flow.save(update_fields=["email_sending_resumed_at"])++ applied, _ = self._sweep()++ assert applied == []+ self.flow.refresh_from_db()+ assert self.flow.email_sending_paused_at is None++ def test_resume_is_a_no_op_when_not_paused(self):+ assert resume_workflow_email_sending(self.flow) is False+ self.flow.refresh_from_db()+ assert self.flow.email_sending_resumed_at is None