: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
chore(workflows): route email health reads and resume through the facade (#109399)
Harley Alexander04f7016035c0
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 9816618c5eb5..89763e4564ef 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -1,6 +1,7 @@+from collections.abc import Mappingfrom dataclasses import dataclassfrom datetime import datetime-from typing import TYPE_CHECKING, Any, Literal, NotRequired, Protocol, TypedDict+from typing import TYPE_CHECKING, Any, Final, Literal, NotRequired, Protocol, TypedDictfrom uuid import UUIDfrom posthog.dataclasses import frozen@@ -168,6 +169,54 @@ class EmailSendingSuspensionChange:previously_suspended_at: datetime | None = None+@frozen+class EmailSendingAllowance:+ """A project's sending tier, what it allows, and how much of that it has used."""++ tier: int+ max_tier: int+ emails_per_hour: int+ emails_per_day: int+ max_batch_audience: int+ emails_sent_last_hour: int+ emails_sent_last_day: int+ enforced: bool+++class StaffPausedError(Exception):+ """A customer tried to resume a pause only staff may clear."""+++# 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),+ )+++@frozen+class FlowEmailTotals:+ counts_by_flow: dict[str, EmailSendingCounts]+ names_by_flow_id: dict[str, str]++@frozenclass WorkflowTemplate:"""A workflow template stored in the database, owned by one team.diff --git a/products/workflows/backend/facade/email_health.py b/products/workflows/backend/facade/email_health.pynew file mode 100644index 000000000000..38cd5e5c9c3d--- /dev/null+++ b/products/workflows/backend/facade/email_health.py@@ -0,0 +1,23 @@+"""Email health: sending rates, the AWS SES tenant verdict, the per-ISP breakdown, the sending+allowance, the project-wide suspension and the per-workflow pause."""++from products.workflows.backend.services.email_health import (+ fetch_aws_tenant_reputation,+ fetch_email_totals_by_source,+ fetch_isp_metrics,+ fold_email_totals,+ team_email_sending_allowance,+)+from products.workflows.backend.services.email_sending_controls import get_email_sending_state+from products.workflows.backend.services.workflow_email_health import pause_requires_staff, resume_email_sending++__all__ = [+ "fetch_aws_tenant_reputation",+ "fetch_email_totals_by_source",+ "fetch_isp_metrics",+ "fold_email_totals",+ "get_email_sending_state",+ "pause_requires_staff",+ "resume_email_sending",+ "team_email_sending_allowance",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 509010288a05..8dd1c3d2c433 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -6,7 +6,7 @@ import hashlibimport dataclassesfrom collections.abc import Mapping, Sequencefrom copy import deepcopy-from datetime import datetime, timedelta+from datetime import timedeltafrom time import monotonicfrom typing import Any, Final, NamedTuple, Optional, castfrom zoneinfo import ZoneInfo, ZoneInfoNotFoundError@@ -56,7 +56,6 @@ from posthog.api.app_metrics2 import (AppMetricsTotalsResponseSerializer,fetch_app_metric_totals,fetch_app_metric_totals_by_source,- fetch_app_metric_totals_by_team_and_source,fetch_app_metrics_trends,)from posthog.api.documentation import _FallbackSerializer@@ -134,6 +133,17 @@ from products.workflows.backend.facade.blast_radius import (is_account_audience,parse_account_audience_filters,)+from products.workflows.backend.facade.contracts import StaffPausedError+from products.workflows.backend.facade.email_health import (+ fetch_aws_tenant_reputation,+ fetch_email_totals_by_source,+ fetch_isp_metrics,+ fold_email_totals,+ get_email_sending_state,+ pause_requires_staff,+ resume_email_sending,+ team_email_sending_allowance,+)from products.workflows.backend.facade.secrets import (TemplateCache,mask_derived_trigger,@@ -182,7 +192,6 @@ from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_optimization import HogFlowOptimizationfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule-from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfigfrom products.workflows.backend.models.workflow_proposal import WorkflowProposalfrom products.workflows.backend.presentation.views.action_redirects import compute_action_redirectsfrom products.workflows.backend.presentation.views.graph_operations import _deep_merge, apply_graph_operations@@ -204,22 +213,11 @@ from products.workflows.backend.presentation.views.message_assets import (fetch_message_assets,)from products.workflows.backend.presentation.views.publish_impact import build_publish_impact-from products.workflows.backend.providers.ses import SESProvider-from products.workflows.backend.services.email_sending_attribution import (- EMAIL_HEALTH_METRIC_NAMES,- fold_email_totals_by_flow,-)from products.workflows.backend.services.timing_reschedule import (get_all_timing_action_ids,get_timing_reschedule_action_ids,)-from products.workflows.backend.services.workflow_email_health import (- StaffPausedError,- pause_requires_staff,- resume_workflow_email_sending,-)from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timing-from products.workflows.backend.utils.email_sending_tiers import max_email_sending_tier, resolve_team_email_sending_tierfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrulelogger = structlog.get_logger(__name__)@@ -2087,122 +2085,6 @@ def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str,}-SENDING_ALLOWANCE_CACHE_SECONDS = 60---@frozen-class EmailSendingAllowance:- """A project's sending tier, what it allows, and how much of that it has used."""-- tier: int- max_tier: int- emails_per_hour: int- emails_per_day: int- max_batch_audience: int- emails_sent_last_hour: int- emails_sent_last_day: int- enforced: bool---def _team_email_sending_allowance(team_id: int) -> EmailSendingAllowance:- """- Usage comes from the send metrics rather than the worker's token buckets, so the numbers match- what the rest of this page reports. Cached briefly because the endpoint reloads on every search- keystroke while these two aggregations do not depend on the search.- """- cache_key = f"workflows_email_sending_allowance_{team_id}"- cached = cache.get(cache_key)- if cached is not None:- return cached-- resolved = resolve_team_email_sending_tier(team_id)- now = timezone.now()- allowance = EmailSendingAllowance(- tier=resolved.tier,- max_tier=max_email_sending_tier(),- emails_per_hour=resolved.limits.per_hour,- emails_per_day=resolved.limits.per_day,- max_batch_audience=resolved.limits.max_batch_audience,- emails_sent_last_hour=_team_email_sends_since(team_id, now - timedelta(hours=1)),- emails_sent_last_day=_team_email_sends_since(team_id, now - timedelta(days=1)),- enforced=resolved.enforced,- )- cache.set(cache_key, allowance, SENDING_ALLOWANCE_CACHE_SECONDS)- return allowance---def _team_email_sends_since(team_id: int, after: datetime) -> int:- totals = fetch_app_metric_totals_by_team_and_source(- app_source="hog_flow", name=["email_sent"], after=after, team_ids=[team_id]- )- return sum(counts.get("email_sent", 0) for counts in totals.get(team_id, {}).values())---AWS_TENANT_REPUTATION_CACHE_SECONDS = 5 * 60-# Failures cache too, but far shorter than successes: long enough that an unreachable SES isn't-# re-dialled on every request, short enough that a just-fixed config recovers within a minute.-AWS_TENANT_REPUTATION_ERROR_CACHE_SECONDS = 60---def _aws_tenant_health(sending_status: str, reputation_impact: str | None) -> str:- if sending_status == "DISABLED":- return "suspended"- if reputation_impact == "HIGH":- return "critical"- if reputation_impact == "LOW":- return "warning"- return "healthy"---def _fetch_aws_tenant_reputation(team_id: int) -> dict[str, Any] | None:- """- AWS-side tenant state for the reputation endpoint, cached briefly: the endpoint reloads on every- search keystroke and three SES API round-trips per keystroke would be slow and rate-limited.- Failures return None (the response field is nullable) so AWS being unreachable never breaks the- rates display; failures cache under a shorter TTL so a broken SES isn't re-dialled per request.-- Deliberately no SES_ACCESS_KEY_ID gate: cloud pods authenticate via their IAM role and leave- the key env vars unset, so a key check reads as "SES not configured" exactly where SES IS- configured. Environments truly without SES fail the call and land in the error path below.- """- cache_key = f"workflows_ses_tenant_reputation_{team_id}"- cached = cache.get(cache_key)- if cached is not None:- return cached["value"]- try:- raw = SESProvider().get_tenant_reputation(team_id)- except Exception:- logger.exception("Failed to fetch SES tenant reputation", team_id=team_id)- cache.set(cache_key, {"value": None}, AWS_TENANT_REPUTATION_ERROR_CACHE_SECONDS)- return None- value = (- {- "health": _aws_tenant_health(raw["sending_status"], raw["reputation_impact"]),- "sending_status": raw["sending_status"],- "findings": raw["findings"],- }- if raw is not None- else None- )- cache.set(cache_key, {"value": value}, AWS_TENANT_REPUTATION_CACHE_SECONDS)- return value---# VDM aggregates by whole day and the window ends at the last UTC midnight, so these numbers move-# at most once a day. A five-minute TTL bought nothing and cost a full fan-out on every expiry.-# One refresh of five domains is 150 queries across 15 sequential BatchGetMetricData calls, and the-# endpoint reloads on every search keystroke, so this is what keeps typing a workflow name from-# costing a fan-out per character.-ISP_METRICS_CACHE_SECONDS = 30 * 60-# A failure is cached too, briefly: without it an unreachable SES is retried in full per keystroke.-ISP_METRICS_ERROR_CACHE_SECONDS = 60-# Held while one request does the fan-out so a cold key admits one, not all of them. Typing races-# concurrent misses through the same key, and each miss can hold a worker for the whole query-# budget. Longer than that budget, so the holder always outlives its own work.-ISP_METRICS_REFRESH_LOCK_SECONDS = 30-# Bounds the BatchGetMetricData fan-out: every extra domain costs one query per provider per-# metric. A project with more sending domains gets a breakdown over its first few.-ISP_METRICS_MAX_DOMAINS = 5# Shared with FEATURE_FLAGS in frontend/src/lib/constants.tsx.ISP_SENDING_HEALTH_FLAG = "workflows-isp-sending-health"@@ -2293,55 +2175,6 @@ def _isp_domains(team: Team, user_access_control: UserAccessControl, user_permis)-def _fetch_isp_metrics(team_id: int, window_days: int, domains: list[str]) -> list[dict[str, Any]]:- """- Per-mailbox-provider sending health for the given sending domains, cached like the tenant- reputation above and for the same reason: the endpoint reloads on every search keystroke.-- Returns an empty list rather than raising when SES is unreachable or VDM is not collecting yet,- because the breakdown adds to the rates display and must not stop it loading.- """- if not domains:- return []- # The domain set depends on what the caller may see, so it belongs in the key: two members of- # one project can be entitled to different domains, and one must not be served the other's.- domain_key = hashlib.sha256("|".join(domains).encode()).hexdigest()[:12]- cache_key = f"workflows_ses_isp_metrics_{team_id}_{window_days}_{domain_key}"- cached = cache.get(cache_key)- if cached is not None:- return cached["value"]-- # Losers show no breakdown rather than queueing behind the holder: the rates above are what the- # page is for, and a second fan-out would buy a number the next reload gets from cache anyway.- if not cache.add(f"{cache_key}_refreshing", True, ISP_METRICS_REFRESH_LOCK_SECONDS):- return []-- try:- rows = SESProvider().get_identity_isp_metrics(- domains, window_days=window_days, max_domains=ISP_METRICS_MAX_DOMAINS- )- except Exception:- logger.exception("Failed to fetch SES per-ISP metrics", team_id=team_id)- cache.set(cache_key, {"value": []}, ISP_METRICS_ERROR_CACHE_SECONDS)- return []-- value = [- {- "isp": row.isp,- "emails_sent": row.emails_sent,- "delivery_rate": row.delivery_rate,- "bounce_rate": row.bounce_rate,- "transient_bounce_rate": row.transient_bounce_rate,- "complaint_rate": row.complaint_rate,- "complaint_base": row.complaint_base,- "unavailable": list(row.unavailable),- }- for row in rows- ]- cache.set(cache_key, {"value": value}, ISP_METRICS_CACHE_SECONDS)- return value--class EmailSendingRatesSerializer(serializers.Serializer):"""Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics."""@@ -6988,21 +6821,7 @@ class HogFlowViewSet(# Members holding just object-level grants still get their (filtered) per-workflow rows.can_read_all_workflows = self.user_access_control.check_access_level_for_resource("hog_flow", "viewer")- # Cached briefly: the UI reloads per search keystroke, but search filters in Python — the- # ClickHouse totals are search-independent. Session-authenticated requests bypass the- # default (personal-API-key-only) ClickHouse throttles, so without this a member could- # re-run the 30-day aggregation on every request.- totals_cache_key = f"workflows_email_reputation_totals_{self.team_id}"- totals_by_source = cache.get(totals_cache_key)- if totals_by_source is None:- after = timezone.now() - timedelta(days=self.REPUTATION_WINDOW_DAYS)- totals_by_source = fetch_app_metric_totals_by_source(- team_id=self.team_id,- app_source="hog_flow",- after=after,- name=EMAIL_HEALTH_METRIC_NAMES,- )- cache.set(totals_cache_key, totals_by_source, 60)+ totals_by_source = fetch_email_totals_by_source(self.team_id, self.REPUTATION_WINDOW_DAYS)# email_blocked is how SES complaint events are recorded (see the plugin server's SES# webhook handler), hence "complained".@@ -7015,24 +6834,24 @@ class HogFlowViewSet(else None)- # Sources matching neither a workflow nor a batch job (deleted workflows, non-UUID ids)- # still count toward the team aggregate above. Unnamed flows come back as "" to keep- # hog_flow_name a plain string in the generated types.- team_queryset = self.get_queryset()- folded_totals = fold_email_totals_by_flow(- team_id=self.team_id, totals_by_source=totals_by_source, flows=team_queryset- )- counts_by_flow = folded_totals.counts_by_flow- names_by_flow_id = folded_totals.names_by_flow_id-# Mirror metrics_global: only surface workflows the caller can see, so reputation doesn't# leak names/volumes of access-controlled workflows the list endpoint hides.+ team_queryset = self.get_queryset()accessible_ids = {str(flow_id)for flow_id in self.user_access_control.filter_queryset_by_access_level(team_queryset).values_list("id", flat=True)}++ # Sources matching neither a workflow nor a batch job (deleted workflows, non-UUID ids)+ # still count toward the team aggregate above. Unnamed flows come back as "" to keep+ # hog_flow_name a plain string in the generated types.+ folded_totals = fold_email_totals(+ team_id=self.team_id, totals_by_source=totals_by_source, flow_ids=accessible_ids+ )+ counts_by_flow = folded_totals.counts_by_flow+ names_by_flow_id = folded_totals.names_by_flow_id# Server-side by necessity: the response is capped to the worst 50 workflows, so filtering# client-side could never find a healthy workflow beyond the cap.search = (request.query_params.get("search") or "").strip().lower()@@ -7070,13 +6889,9 @@ class HogFlowViewSet(# Shown to every project member regardless of per-object grants: a suspension stops# everyone's email, so hiding it would just leave silent send failures unexplained.- suspension = (- TeamWorkflowsConfig.objects.filter(team_id=self.team_id)- .values("email_sending_suspended_at", "email_sending_suspension_reason")- .first()- )- suspended_at = suspension["email_sending_suspended_at"] if suspension else None- suspension_reason = suspension["email_sending_suspension_reason"] if suspension else ""+ suspension = get_email_sending_state(self.team_id)+ suspended_at = suspension.suspended_at if suspension else None+ suspension_reason = suspension.suspension_reason if suspension else ""# Same project-wide gate as `reputation`: the breakdown pools every workflow's email for a# sending domain, so object-level grants alone don't earn it.@@ -7091,12 +6906,12 @@ class HogFlowViewSet({# Same gate as `reputation`: the tenant verdict pools ALL workflows' email,# so members holding only object-level grants don't get it.- "aws": _fetch_aws_tenant_reputation(self.team_id) if can_read_all_workflows else None,+ "aws": fetch_aws_tenant_reputation(self.team_id) if can_read_all_workflows else None,"reputation": reputation,"workflows": workflow_rows,# Same project-wide gate as `reputation`: the breakdown pools every workflow's# email for a sending domain, so object-level grants alone don't earn it.- "isps": _fetch_isp_metrics(self.team_id, self.REPUTATION_WINDOW_DAYS, list(isp_domains.readable)),+ "isps": fetch_isp_metrics(self.team_id, self.REPUTATION_WINDOW_DAYS, list(isp_domains.readable)),"isp_shared_domains": list(isp_domains.shared),"isp_withheld_domains": list(isp_domains.withheld),"email_sending_suspended": suspended_at is not None,@@ -7104,9 +6919,7 @@ class HogFlowViewSet("email_sending_suspension_reason": suspension_reason if suspended_at is not None else "",# Same gate again: the allowance is project-wide, so an object-level grant is# not enough to read it.- "sending_allowance": _team_email_sending_allowance(self.team_id)- if can_read_all_workflows- else None,+ "sending_allowance": team_email_sending_allowance(self.team_id) if can_read_all_workflows else None,}).data)@@ -7128,19 +6941,15 @@ class HogFlowViewSet(with no reputation computation. Every project member sees this — a suspension stopseveryone's email, so hiding it would leave silent send failures unexplained."""- suspension = (- TeamWorkflowsConfig.objects.filter(team_id=self.team_id)- .values("email_sending_suspended_at", "email_sending_suspension_reason")- .first()- )- suspended_at = suspension["email_sending_suspended_at"] if suspension else None+ suspension = get_email_sending_state(self.team_id)+ suspended_at = suspension.suspended_at if suspension else Nonereturn Response(EmailSendingSuspensionStatusSerializer({"email_sending_suspended": suspended_at is not None,"email_sending_suspended_at": suspended_at,"email_sending_suspension_reason": (- suspension["email_sending_suspension_reason"] if suspension and suspended_at is not None else ""+ suspension.suspension_reason if suspension and suspended_at is not None else ""),}).data@@ -7163,13 +6972,21 @@ class HogFlowViewSet(hog_flow = self.get_object()before_update = HogFlow.objects.get(id=hog_flow.id)try:- resumed = resume_workflow_email_sending(hog_flow)+ resumed_at = resume_email_sending(team_id=hog_flow.team_id, hog_flow_id=hog_flow.id)except StaffPausedError:raise exceptions.PermissionDenied("This pause can only be lifted by PostHog. Contact support to get sending re-enabled.")- if not resumed:+ if resumed_at is None:raise exceptions.ValidationError({"detail": "Email sending is not paused for this workflow."})+ hog_flow.refresh_from_db(+ fields=[+ "email_sending_paused_at",+ "email_sending_paused_reason",+ "email_sending_paused_by",+ "email_sending_resumed_at",+ ]+ )log_activity_from_viewset(self, hog_flow, activity="email_sending_resumed", name=hog_flow.name, previous=before_update)diff --git a/products/workflows/backend/services/email_health.py b/products/workflows/backend/services/email_health.pynew file mode 100644index 000000000000..adca98c8fe4b--- /dev/null+++ b/products/workflows/backend/services/email_health.py@@ -0,0 +1,209 @@+"""The email reputation page: sending rates, the AWS SES tenant verdict, the per-ISP breakdown and+the sending allowance."""++import hashlib+from collections.abc import Collection, Mapping+from datetime import datetime, timedelta+from typing import Any++from django.core.cache import cache+from django.utils import timezone++import structlog++from posthog.api.app_metrics2 import fetch_app_metric_totals_by_source, fetch_app_metric_totals_by_team_and_source++from products.workflows.backend.facade.contracts import (+ EMAIL_HEALTH_METRIC_NAMES,+ EmailSendingAllowance,+ FlowEmailTotals,+)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.providers.ses import SESProvider+from products.workflows.backend.services.email_sending_attribution import fold_email_totals_by_flow+from products.workflows.backend.utils.email_sending_tiers import max_email_sending_tier, resolve_team_email_sending_tier++logger = structlog.get_logger(__name__)+++def fetch_email_totals_by_source(team_id: int, window_days: int) -> dict[str, dict[str, int]]:+ # Cached briefly: the UI reloads per search keystroke, but search filters in Python - the+ # ClickHouse totals are search-independent. Session-authenticated requests bypass the+ # default (personal-API-key-only) ClickHouse throttles, so without this a member could+ # re-run the 30-day aggregation on every request.+ totals_cache_key = f"workflows_email_reputation_totals_{team_id}"+ totals_by_source = cache.get(totals_cache_key)+ if totals_by_source is None:+ after = timezone.now() - timedelta(days=window_days)+ totals_by_source = fetch_app_metric_totals_by_source(+ team_id=team_id,+ app_source="hog_flow",+ after=after,+ name=EMAIL_HEALTH_METRIC_NAMES,+ )+ cache.set(totals_cache_key, totals_by_source, 60)+ return totals_by_source+++def fold_email_totals(+ *, team_id: int, totals_by_source: Mapping[str, Mapping[str, int]], flow_ids: Collection[str]+) -> FlowEmailTotals:+ return fold_email_totals_by_flow(+ team_id=team_id,+ totals_by_source=totals_by_source,+ flows=HogFlow.objects.filter(team_id=team_id, id__in=list(flow_ids)),+ )+++SENDING_ALLOWANCE_CACHE_SECONDS = 60+++def team_email_sending_allowance(team_id: int) -> EmailSendingAllowance:+ """+ Usage comes from the send metrics rather than the worker's token buckets, so the numbers match+ what the rest of this page reports. Cached briefly because the endpoint reloads on every search+ keystroke while these two aggregations do not depend on the search.+ """+ # Entries are pickles: bump the version when EmailSendingAllowance changes module or shape.+ cache_key = f"workflows_email_sending_allowance_v2_{team_id}"+ cached = cache.get(cache_key)+ if cached is not None:+ return cached++ resolved = resolve_team_email_sending_tier(team_id)+ now = timezone.now()+ allowance = EmailSendingAllowance(+ tier=resolved.tier,+ max_tier=max_email_sending_tier(),+ emails_per_hour=resolved.limits.per_hour,+ emails_per_day=resolved.limits.per_day,+ max_batch_audience=resolved.limits.max_batch_audience,+ emails_sent_last_hour=_team_email_sends_since(team_id, now - timedelta(hours=1)),+ emails_sent_last_day=_team_email_sends_since(team_id, now - timedelta(days=1)),+ enforced=resolved.enforced,+ )+ cache.set(cache_key, allowance, SENDING_ALLOWANCE_CACHE_SECONDS)+ return allowance+++def _team_email_sends_since(team_id: int, after: datetime) -> int:+ totals = fetch_app_metric_totals_by_team_and_source(+ app_source="hog_flow", name=["email_sent"], after=after, team_ids=[team_id]+ )+ return sum(counts.get("email_sent", 0) for counts in totals.get(team_id, {}).values())+++AWS_TENANT_REPUTATION_CACHE_SECONDS = 5 * 60+# Failures cache too, but far shorter than successes: long enough that an unreachable SES isn't+# re-dialled on every request, short enough that a just-fixed config recovers within a minute.+AWS_TENANT_REPUTATION_ERROR_CACHE_SECONDS = 60+++def _aws_tenant_health(sending_status: str, reputation_impact: str | None) -> str:+ if sending_status == "DISABLED":+ return "suspended"+ if reputation_impact == "HIGH":+ return "critical"+ if reputation_impact == "LOW":+ return "warning"+ return "healthy"+++def fetch_aws_tenant_reputation(team_id: int) -> dict[str, Any] | None:+ """+ AWS-side tenant state for the reputation endpoint, cached briefly: the endpoint reloads on every+ search keystroke and three SES API round-trips per keystroke would be slow and rate-limited.+ Failures return None (the response field is nullable) so AWS being unreachable never breaks the+ rates display; failures cache under a shorter TTL so a broken SES isn't re-dialled per request.++ Deliberately no SES_ACCESS_KEY_ID gate: cloud pods authenticate via their IAM role and leave+ the key env vars unset, so a key check reads as "SES not configured" exactly where SES IS+ configured. Environments truly without SES fail the call and land in the error path below.+ """+ cache_key = f"workflows_ses_tenant_reputation_{team_id}"+ cached = cache.get(cache_key)+ if cached is not None:+ return cached["value"]+ try:+ raw = SESProvider().get_tenant_reputation(team_id)+ except Exception:+ logger.exception("Failed to fetch SES tenant reputation", team_id=team_id)+ cache.set(cache_key, {"value": None}, AWS_TENANT_REPUTATION_ERROR_CACHE_SECONDS)+ return None+ value = (+ {+ "health": _aws_tenant_health(raw["sending_status"], raw["reputation_impact"]),+ "sending_status": raw["sending_status"],+ "findings": raw["findings"],+ }+ if raw is not None+ else None+ )+ cache.set(cache_key, {"value": value}, AWS_TENANT_REPUTATION_CACHE_SECONDS)+ return value+++# VDM aggregates by whole day and the window ends at the last UTC midnight, so these numbers move+# at most once a day. A five-minute TTL bought nothing and cost a full fan-out on every expiry.+# One refresh of five domains is 150 queries across 15 sequential BatchGetMetricData calls, and the+# endpoint reloads on every search keystroke, so this is what keeps typing a workflow name from+# costing a fan-out per character.+ISP_METRICS_CACHE_SECONDS = 30 * 60+# A failure is cached too, briefly: without it an unreachable SES is retried in full per keystroke.+ISP_METRICS_ERROR_CACHE_SECONDS = 60+# Held while one request does the fan-out so a cold key admits one, not all of them. Typing races+# concurrent misses through the same key, and each miss can hold a worker for the whole query+# budget. Longer than that budget, so the holder always outlives its own work.+ISP_METRICS_REFRESH_LOCK_SECONDS = 30+# Bounds the BatchGetMetricData fan-out: every extra domain costs one query per provider per+# metric. A project with more sending domains gets a breakdown over its first few.+ISP_METRICS_MAX_DOMAINS = 5+++def fetch_isp_metrics(team_id: int, window_days: int, domains: list[str]) -> list[dict[str, Any]]:+ """+ Per-mailbox-provider sending health for the given sending domains, cached like the tenant+ reputation above and for the same reason: the endpoint reloads on every search keystroke.++ Returns an empty list rather than raising when SES is unreachable or VDM is not collecting yet,+ because the breakdown adds to the rates display and must not stop it loading.+ """+ if not domains:+ return []+ # The domain set depends on what the caller may see, so it belongs in the key: two members of+ # one project can be entitled to different domains, and one must not be served the other's.+ domain_key = hashlib.sha256("|".join(domains).encode()).hexdigest()[:12]+ cache_key = f"workflows_ses_isp_metrics_{team_id}_{window_days}_{domain_key}"+ cached = cache.get(cache_key)+ if cached is not None:+ return cached["value"]++ # Losers show no breakdown rather than queueing behind the holder: the rates above are what the+ # page is for, and a second fan-out would buy a number the next reload gets from cache anyway.+ if not cache.add(f"{cache_key}_refreshing", True, ISP_METRICS_REFRESH_LOCK_SECONDS):+ return []++ try:+ rows = SESProvider().get_identity_isp_metrics(+ domains, window_days=window_days, max_domains=ISP_METRICS_MAX_DOMAINS+ )+ except Exception:+ logger.exception("Failed to fetch SES per-ISP metrics", team_id=team_id)+ cache.set(cache_key, {"value": []}, ISP_METRICS_ERROR_CACHE_SECONDS)+ return []++ value = [+ {+ "isp": row.isp,+ "emails_sent": row.emails_sent,+ "delivery_rate": row.delivery_rate,+ "bounce_rate": row.bounce_rate,+ "transient_bounce_rate": row.transient_bounce_rate,+ "complaint_rate": row.complaint_rate,+ "complaint_base": row.complaint_base,+ "unavailable": list(row.unavailable),+ }+ for row in rows+ ]+ cache.set(cache_key, {"value": value}, ISP_METRICS_CACHE_SECONDS)+ return valuediff --git a/products/workflows/backend/services/email_sending_attribution.py b/products/workflows/backend/services/email_sending_attribution.pyindex 6ecc520a8c7f..f21edc57fd4f 100644--- a/products/workflows/backend/services/email_sending_attribution.py+++ b/products/workflows/backend/services/email_sending_attribution.py@@ -1,37 +1,12 @@import uuid as uuid_modfrom collections.abc import Mapping-from typing import Finalfrom django.db.models import QuerySet-from posthog.dataclasses import frozen-+from products.workflows.backend.facade.contracts import EmailSendingCounts, FlowEmailTotalsfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom 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:@@ -41,12 +16,6 @@ def looks_like_uuid(value: str) -> bool: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,diff --git a/products/workflows/backend/services/workflow_email_health.py b/products/workflows/backend/services/workflow_email_health.pyindex e47c7223bea2..2015076411a0 100644--- a/products/workflows/backend/services/workflow_email_health.py+++ b/products/workflows/backend/services/workflow_email_health.py@@ -1,6 +1,7 @@from dataclasses import replacefrom datetime import datetime, timedeltafrom typing import Final, Literal+from uuid import UUIDfrom django.conf import settingsfrom django.db import transaction@@ -17,15 +18,16 @@ from posthog.plugins.plugin_server_api import reload_hog_flows_on_workersfrom posthog.schema_enums import ProductKeyfrom 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 (+from products.workflows.backend.facade.contracts import (COMPLAINT_METRIC,EMAIL_HEALTH_METRIC_NAMES,HARD_BOUNCE_METRIC,SENT_METRIC,EmailSendingCounts,- fold_email_totals_by_flow,+ StaffPausedError,)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.services.email_sending_attribution import fold_email_totals_by_flowlogger = structlog.get_logger(__name__)@@ -35,10 +37,6 @@ PAUSED_BY_AUTO: Final[str] = "auto"PAUSED_BY_STAFF: Final[str] = "staff"-class StaffPausedError(Exception):- """A customer tried to resume a pause only staff may clear."""--def pause_requires_staff(*, paused_at: datetime | None, paused_by: str, resumed_at: datetime | None) -> bool:"""Whether only staff can clear this pause.@@ -585,8 +583,10 @@ def _decision_log_fields(decision: PauseDecision) -> dict[str, str | int | float}-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.+def resume_email_sending(+ *, team_id: int, hog_flow_id: UUID, actor: str = "customer", now: datetime | None = None+) -> datetime | None:+ """Clear a workflow's pause. Returns the resume time, or None when it was not paused.A staff pause exists because the automatic thresholds could not see the problem, so a customermust not be able to clear it: only `actor="staff"` may. Raises StaffPausedError so the API can@@ -602,12 +602,12 @@ def resume_workflow_email_sending(flow: HogFlow, *, actor: str = "customer", nowwith transaction.atomic():locked = (HogFlow.objects.select_for_update()- .filter(id=flow.id, team_id=flow.team_id)+ .filter(id=hog_flow_id, team_id=team_id).only("id", "team_id", "email_sending_paused_at", "email_sending_paused_by", "email_sending_resumed_at").first())if locked is None or locked.email_sending_paused_at is None:- return False+ return Noneif actor != PAUSED_BY_STAFF and pause_requires_staff(paused_at=locked.email_sending_paused_at,paused_by=locked.email_sending_paused_by,@@ -616,18 +616,26 @@ def resume_workflow_email_sending(flow: HogFlow, *, actor: str = "customer", nowraise 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(+ HogFlow.objects.filter(id=hog_flow_id, team_id=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+ lambda: reload_hog_flows_on_workers(team_id=team_id, hog_flow_ids=[str(hog_flow_id)]), robust=True)+ return now+++def resume_workflow_email_sending(flow: HogFlow, *, actor: str = "customer", now: datetime | None = None) -> bool:+ """Clear a workflow's pause and mirror the write onto `flow`. Returns False when it was not paused."""+ resumed_at = resume_email_sending(team_id=flow.team_id, hog_flow_id=flow.id, actor=actor, now=now)+ if resumed_at is None:+ return False# The caller serializes these back to the customer, so mirror what was written.flow.email_sending_paused_at = Noneflow.email_sending_paused_reason = ""flow.email_sending_paused_by = ""- flow.email_sending_resumed_at = now+ flow.email_sending_resumed_at = resumed_atreturn Truediff --git a/products/workflows/backend/tests/api/test_email_reputation.py b/products/workflows/backend/tests/api/test_email_reputation.pyindex d33f69ad9355..6f4a65ffa139 100644--- a/products/workflows/backend/tests/api/test_email_reputation.py+++ b/products/workflows/backend/tests/api/test_email_reputation.py@@ -57,10 +57,10 @@ class TestEmailReputationAPI(APIBaseTest):provider.get_identity_isp_metrics.return_value = isp_metrics or []with (patch(- "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.services.email_health.fetch_app_metric_totals_by_source",return_value=totals_by_source,),- patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.services.email_health.SESProvider", return_value=provider),patch("products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled",return_value=isp_flag_enabled,@@ -145,10 +145,10 @@ class TestEmailReputationAPI(APIBaseTest):provider.get_tenant_reputation.side_effect = Exception("SES timeout")with (patch(- "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.services.email_health.fetch_app_metric_totals_by_source",return_value={},),- patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.services.email_health.SESProvider", return_value=provider),):url = f"/api/projects/{self.team.id}/hog_flows/reputation"first = self.client.get(url)@@ -459,12 +459,12 @@ class TestEmailReputationAPI(APIBaseTest):provider.get_tenant_reputation.return_value = Nonewith (patch(- "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.services.email_health.fetch_app_metric_totals_by_source",return_value={},),- patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.services.email_health.SESProvider", return_value=provider),patch("products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled", return_value=True),- patch("products.workflows.backend.presentation.views.hog_flow.cache.add", return_value=False),+ patch("products.workflows.backend.services.email_health.cache.add", return_value=False),):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")@@ -549,10 +549,10 @@ class TestEmailReputationAccessControl(APIBaseTest):]with (patch(- "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals_by_source",+ "products.workflows.backend.services.email_health.fetch_app_metric_totals_by_source",return_value={str(flow.id): {"email_sent": 100, "email_bounced_hard": 5}},),- patch("products.workflows.backend.presentation.views.hog_flow.SESProvider", return_value=provider),+ patch("products.workflows.backend.services.email_health.SESProvider", return_value=provider),# Enabled, so what the assertion below tests is the access-control gate, not the flag.patch("products.workflows.backend.presentation.views.hog_flow._isp_breakdown_enabled", return_value=True),):diff --git a/pyproject.toml b/pyproject.tomlindex 42e0903d5ddb..04e31e9c6b50 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -728,14 +728,9 @@ ignore_imports = ["products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_optimization","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_schedule",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.team_workflows_config","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.workflow_proposal",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.providers.ses",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.email_sending_attribution","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.workflow_email_health","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.tasks.hog_flows",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.email_sending_tiers","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.rrule_utils",# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM# access with them. Thin them to parse -> facade -> serialize and delete each entry.