:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): split the ses reputation poll so throttling cannot stale enforcement (#112353)
Meikel Ratz9921d86dad07
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex edf1b68be639..f6eff910b7fe 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -152,7 +152,8 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import ()from products.wizard.backend.facade.tasks import reconcile_wizard_runsfrom products.workflows.backend.facade.tasks import (- poll_ses_account_reputation,+ poll_ses_account_enforcement,+ poll_ses_reputation_findings,recompute_workflows_email_sending_tiers,reconcile_ses_tenant_states,sweep_workflow_email_deliverability,@@ -498,11 +499,19 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:add_periodic_task_with_expiry(sender,crontab(minute="*/10"),- poll_ses_account_reputation.s(),- name="poll SES account reputation",+ poll_ses_account_enforcement.s(),+ name="poll SES account enforcement status",expires_seconds=10 * 60,)+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="20"),+ poll_ses_reputation_findings.s(),+ name="poll SES reputation findings",+ expires_seconds=30 * 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.diff --git a/products/workflows/backend/facade/tasks.py b/products/workflows/backend/facade/tasks.pyindex 558401eda9e4..f4258abea162 100644--- a/products/workflows/backend/facade/tasks.py+++ b/products/workflows/backend/facade/tasks.py@@ -1,11 +1,15 @@from products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiersfrom products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows-from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation+from products.workflows.backend.tasks.ses_account_reputation import (+ poll_ses_account_enforcement,+ poll_ses_reputation_findings,+)from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_statesfrom products.workflows.backend.tasks.workflow_email_health import sweep_workflow_email_deliverability__all__ = [- "poll_ses_account_reputation",+ "poll_ses_account_enforcement",+ "poll_ses_reputation_findings","recompute_workflows_email_sending_tiers","reconcile_ses_tenant_states","refresh_affected_hog_flows",diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.pyindex 065b6d4b603b..2b6a4371c9de 100644--- a/products/workflows/backend/providers/ses.py+++ b/products/workflows/backend/providers/ses.py@@ -70,6 +70,12 @@ METRIC_CALL_WORST_CASE_SECONDS = METRIC_CONNECT_TIMEOUT_SECONDS + METRIC_READ_TI# its worst case still inside it — so the ceiling holds even when SES answers slowly.METRIC_QUERY_BUDGET_SECONDS = 20+RECOMMENDATIONS_PAGE_SIZE = 100++# The account findings walk runs in a background task, so it can wait out SES throttling. Adaptive+# mode adds a client-side rate limiter that slows the following pages after a throttle response.+RECOMMENDATIONS_RETRY_CONFIG = Config(retries={"mode": "adaptive", "max_attempts": 8})+@frozenclass IspSendingMetrics:@@ -274,6 +280,7 @@ class SESProvider:ses_client: "SESClient"ses_v2_client: "SESV2Client"ses_v2_metrics_client: "SESV2Client"+ ses_v2_recommendations_client: "SESV2Client"def __init__(self):# Initialize the boto3 clients@@ -308,6 +315,13 @@ class SESProvider:retries={"max_attempts": 1},),)+ self.ses_v2_recommendations_client = boto3.client(+ "sesv2",+ aws_access_key_id=settings.SES_ACCESS_KEY_ID,+ aws_secret_access_key=settings.SES_SECRET_ACCESS_KEY,+ region_name=settings.SES_REGION,+ config=RECOMMENDATIONS_RETRY_CONFIG,+ )def _tenant_name_for_team(self, team_id: int) -> str:return f"team-{team_id}"@@ -364,15 +378,20 @@ class SESProvider:"findings": findings,}- def _iter_open_recommendations(self, finding_filter: dict[Any, str] | None) -> Iterator["RecommendationTypeDef"]:+ def _iter_open_recommendations(+ self, finding_filter: dict[Any, str] | None, client: "SESV2Client | None" = None+ ) -> Iterator["RecommendationTypeDef"]:"""Walk every page of ListRecommendations, yielding only OPEN recommendations. The localSTATUS check exists for RESOURCE_ARN-filtered calls: AWS documents STATUS as combinableonly with IMPACT or TYPE, so tenant-scoped listings must drop FIXED entries client-side."""- kwargs: dict[str, Any] = {"Filter": finding_filter} if finding_filter else {}+ client = client or self.ses_v2_client+ kwargs: dict[str, Any] = {"PageSize": RECOMMENDATIONS_PAGE_SIZE}+ if finding_filter:+ kwargs["Filter"] = finding_filterwhile True:- page = self.ses_v2_client.list_recommendations(**kwargs)+ page = client.list_recommendations(**kwargs)for recommendation in page.get("Recommendations", []):if recommendation.get("Status") == "OPEN":yield recommendation@@ -381,25 +400,32 @@ class SESProvider:returnkwargs["NextToken"] = next_token- def get_account_reputation(self) -> dict[str, Any]:+ def get_account_enforcement_status(self) -> str:"""- Account-level SES verdict: enforcement status plus every open reputation finding,- classified by the resource it references. AWS opens findings well before it enforces,- so this is the earliest account-scoped warning available.+ Account-level SES verdict from a single GetAccount call, so that it stays cheap enough+ to poll often and cannot fail because of the paged findings listing."""# Strict access on purpose: a response without EnforcementStatus must fail the poll# (surfacing via the staleness alert) rather than be reported as healthy.- enforcement_status: str = self.ses_v2_client.get_account()["EnforcementStatus"]- findings = [+ return self.ses_v2_client.get_account()["EnforcementStatus"]++ def get_account_reputation_findings(self) -> list[dict[str, str]]:+ """+ Every open reputation finding on the account, classified by the resource it references.+ AWS opens findings well before it enforces, so this is the earliest account-scoped+ warning available.+ """+ return [{"finding_type": recommendation.get("Type", ""),"impact": recommendation.get("Impact", "LOW"),"scope": self._finding_scope(recommendation.get("ResourceArn", "")),"description": recommendation.get("Description", ""),}- for recommendation in self._iter_open_recommendations({"STATUS": "OPEN"})+ for recommendation in self._iter_open_recommendations(+ {"STATUS": "OPEN"}, client=self.ses_v2_recommendations_client+ )]- return {"enforcement_status": enforcement_status, "findings": findings}@staticmethoddef _finding_scope(resource_arn: str) -> str:diff --git a/products/workflows/backend/tasks/ses_account_reputation.py b/products/workflows/backend/tasks/ses_account_reputation.pyindex 3d8047c260e6..c344d53e2c6e 100644--- a/products/workflows/backend/tasks/ses_account_reputation.py+++ b/products/workflows/backend/tasks/ses_account_reputation.py@@ -1,6 +1,7 @@import timefrom collections import Counter+from botocore.exceptions import ClientErrorfrom celery import shared_taskfrom prometheus_client import Gaugefrom structlog import get_logger@@ -12,39 +13,91 @@ from products.workflows.backend.providers.ses import SESProviderlogger = get_logger(__name__)+# Each push replaces every metric previously pushed under its job name, so each poll and its+# failure marker get their own job. The enforcement poll keeps the original job name: pushgateway+# never expires a group, so a renamed job would leave the old timestamp frozen and alerting forever.+ENFORCEMENT_JOB = "ses_account_reputation"+FINDINGS_JOB = "ses_reputation_findings"++THROTTLE_ERROR_CODES = frozenset({"TooManyRequestsException", "Throttling", "ThrottlingException"})+++def _failure_reason(error: Exception) -> str:+ if isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in THROTTLE_ERROR_CODES:+ return "throttled"+ return "error"+++def _record_poll_failure(poll: str, job_name: str, error: Exception) -> None:+ """+ Push when and why the last poll failed, so the staleness alert can tell AWS throttling apart+ from a broken poller. Regions without SES access (self-hosted, dev) land here every tick, and+ those regions have no pushgateway, so the push is a no-op there.+ """+ reason = _failure_reason(error)+ logger.warning("SES reputation poll failed", poll=poll, reason=reason, exc_info=error)+ with pushed_metrics_registry(f"{job_name}_failure") as registry:+ Gauge(+ "posthog_ses_reputation_poll_last_failure_timestamp_seconds",+ "Unix timestamp of the last failed SES reputation poll, by poll and failure reason.",+ labelnames=["poll", "reason"],+ registry=registry,+ multiprocess_mode="mostrecent",+ ).labels(poll=poll, reason=reason).set(time.time())+++# multiprocess_mode="mostrecent" everywhere: the celery workers run prometheus_client in+# multiprocess mode, which re-exports these gauges on the pod's own /metrics regardless of+# the private registry. Without it, every worker process exposes its own copy frozen at the+# last value that pid set, and alerts evaluating those fossil series flap.+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)-def poll_ses_account_reputation() -> None:+def poll_ses_account_enforcement() -> None:"""- Export AWS's account-level SES verdict as gauges for alerting: enforcement status, open- reputation findings, and a poll timestamp. The timestamp exists because pushgateway- gauges never expire — without it, a dead poller freezes the last "healthy" values- forever and nothing would fire.+ Export AWS's account-level SES enforcement status as a gauge for alerting, plus a poll+ timestamp. The timestamp exists because pushgateway gauges never expire. Without it, a dead+ poller freezes the last "healthy" value forever and nothing would fire."""try:- reputation = SESProvider().get_account_reputation()- except Exception:- # Regions without SES access (self-hosted, dev) land here every tick; a stale- # last_poll_timestamp is the alertable signal for genuine poller breakage in cloud.- logger.warning("SES account reputation poll failed", exc_info=True)+ enforcement_status = SESProvider().get_account_enforcement_status()+ except Exception as error:+ _record_poll_failure("enforcement", ENFORCEMENT_JOB, error)return- finding_counts = Counter(- (finding["scope"], finding["finding_type"], finding["impact"]) for finding in reputation["findings"]- )-- # multiprocess_mode="mostrecent" everywhere: the celery workers run prometheus_client in- # multiprocess mode, which re-exports these gauges on the pod's own /metrics regardless of- # the private registry. Without it, every worker process exposes its own copy frozen at the- # last value that pid set, and alerts evaluating those fossil series flap.- with pushed_metrics_registry("ses_account_reputation") as registry:+ with pushed_metrics_registry(ENFORCEMENT_JOB) as registry:Gauge("posthog_ses_account_enforcement_healthy","1 while AWS SES reports the account EnforcementStatus as HEALTHY, 0 otherwise.",registry=registry,multiprocess_mode="mostrecent",- ).set(1 if reputation["enforcement_status"] == "HEALTHY" else 0)+ ).set(1 if enforcement_status == "HEALTHY" else 0)+ Gauge(+ "posthog_ses_account_reputation_last_poll_timestamp_seconds",+ "Unix timestamp of the last successful SES account enforcement status poll.",+ registry=registry,+ multiprocess_mode="mostrecent",+ ).set(time.time())+++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+def poll_ses_reputation_findings() -> None:+ """+ Export the open AWS SES reputation findings, counted by the resource scope they reference,+ plus a poll timestamp. This walk pages through every tenant's findings, so it runs less often+ than the enforcement poll and has its own timestamp, which keeps a throttled walk from making+ the enforcement signal look stale.+ """+ try:+ findings = SESProvider().get_account_reputation_findings()+ except Exception as error:+ _record_poll_failure("findings", FINDINGS_JOB, error)+ return++ finding_counts = Counter((finding["scope"], finding["finding_type"], finding["impact"]) for finding in findings)++ with pushed_metrics_registry(FINDINGS_JOB) as registry:findings_gauge = Gauge("posthog_ses_open_reputation_findings","Open AWS SES reputation findings (ListRecommendations), by referenced resource scope.",@@ -56,8 +109,8 @@ def poll_ses_account_reputation() -> None:findings_gauge.labels(scope=scope, finding_type=finding_type, impact=impact).set(count)Gauge(- "posthog_ses_account_reputation_last_poll_timestamp_seconds",- "Unix timestamp of the last successful SES account reputation poll.",+ "posthog_ses_reputation_findings_last_poll_timestamp_seconds",+ "Unix timestamp of the last successful SES reputation findings poll.",registry=registry,multiprocess_mode="mostrecent",).set(time.time())diff --git a/products/workflows/backend/test/test_ses_account_reputation_task.py b/products/workflows/backend/test/test_ses_account_reputation_task.pyindex 48d707319112..1ea2da7c2e09 100644--- a/products/workflows/backend/test/test_ses_account_reputation_task.py+++ b/products/workflows/backend/test/test_ses_account_reputation_task.py@@ -1,11 +1,14 @@from unittest import TestCase-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom botocore.exceptions import ClientErrorfrom parameterized import parameterizedfrom prometheus_client import CollectorRegistry-from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation+from products.workflows.backend.tasks.ses_account_reputation import (+ poll_ses_account_enforcement,+ poll_ses_reputation_findings,+)class TestPollSesAccountReputation(TestCase):@@ -25,6 +28,12 @@ class TestPollSesAccountReputation(TestCase):self.mock_provider = provider_patcher.start().return_valueself.addCleanup(provider_patcher.stop)+ time_patcher = patch(+ "products.workflows.backend.tasks.ses_account_reputation.time.time", return_value=1700000000.0+ )+ time_patcher.start()+ self.addCleanup(time_patcher.stop)+@parameterized.expand([("HEALTHY", 1.0),@@ -32,25 +41,26 @@ class TestPollSesAccountReputation(TestCase):("SHUTDOWN", 0.0),])- def test_exports_enforcement_health_gauge(self, status, expected):- self.mock_provider.get_account_reputation.return_value = {"enforcement_status": status, "findings": []}+ def test_enforcement_poll_exports_health_gauge_and_timestamp(self, status, expected):+ self.mock_provider.get_account_enforcement_status.return_value = status- poll_ses_account_reputation()+ poll_ses_account_enforcement()assert self.registry.get_sample_value("posthog_ses_account_enforcement_healthy") == expected+ assert (+ self.registry.get_sample_value("posthog_ses_account_reputation_last_poll_timestamp_seconds") == 1700000000.0+ )+ self.mock_registry_factory.assert_called_once_with("ses_account_reputation")+ self.mock_provider.get_account_reputation_findings.assert_not_called()- @patch("products.workflows.backend.tasks.ses_account_reputation.time.time", return_value=1700000000.0)- def test_exports_finding_counts_and_poll_timestamp(self, _mock_time):- self.mock_provider.get_account_reputation.return_value = {- "enforcement_status": "HEALTHY",- "findings": [- {"finding_type": "BOUNCE", "impact": "LOW", "scope": "tenant"},- {"finding_type": "BOUNCE", "impact": "LOW", "scope": "tenant"},- {"finding_type": "COMPLAINT", "impact": "HIGH", "scope": "account"},- ],- }+ def test_findings_poll_exports_counts_and_its_own_timestamp(self):+ self.mock_provider.get_account_reputation_findings.return_value = [+ {"finding_type": "BOUNCE", "impact": "LOW", "scope": "tenant"},+ {"finding_type": "BOUNCE", "impact": "LOW", "scope": "tenant"},+ {"finding_type": "COMPLAINT", "impact": "HIGH", "scope": "account"},+ ]- poll_ses_account_reputation()+ poll_ses_reputation_findings()def finding_count(scope, finding_type, impact):return self.registry.get_sample_value(@@ -61,14 +71,72 @@ class TestPollSesAccountReputation(TestCase):assert finding_count("tenant", "BOUNCE", "LOW") == 2assert finding_count("account", "COMPLAINT", "HIGH") == 1assert (- self.registry.get_sample_value("posthog_ses_account_reputation_last_poll_timestamp_seconds") == 1700000000.0+ self.registry.get_sample_value("posthog_ses_reputation_findings_last_poll_timestamp_seconds")+ == 1700000000.0)+ assert self.registry.get_sample_value("posthog_ses_account_reputation_last_poll_timestamp_seconds") is None+ self.mock_registry_factory.assert_called_once_with("ses_reputation_findings")- def test_provider_failure_does_not_raise_and_pushes_nothing(self):- self.mock_provider.get_account_reputation.side_effect = ClientError(- {"Error": {"Code": "AccessDenied"}}, "GetAccount"- )+ @parameterized.expand(+ [+ (+ "enforcement_throttled",+ poll_ses_account_enforcement,+ "get_account_enforcement_status",+ ClientError({"Error": {"Code": "TooManyRequestsException"}}, "ListRecommendations"),+ "enforcement",+ "throttled",+ "ses_account_reputation_failure",+ ),+ (+ "enforcement_access_denied",+ poll_ses_account_enforcement,+ "get_account_enforcement_status",+ ClientError({"Error": {"Code": "AccessDenied"}}, "GetAccount"),+ "enforcement",+ "error",+ "ses_account_reputation_failure",+ ),+ (+ "enforcement_missing_status_field",+ poll_ses_account_enforcement,+ "get_account_enforcement_status",+ KeyError("EnforcementStatus"),+ "enforcement",+ "error",+ "ses_account_reputation_failure",+ ),+ (+ "findings_throttled",+ poll_ses_reputation_findings,+ "get_account_reputation_findings",+ ClientError({"Error": {"Code": "TooManyRequestsException"}}, "ListRecommendations"),+ "findings",+ "throttled",+ "ses_reputation_findings_failure",+ ),+ (+ "findings_access_denied",+ poll_ses_reputation_findings,+ "get_account_reputation_findings",+ ClientError({"Error": {"Code": "AccessDenied"}}, "GetAccount"),+ "findings",+ "error",+ "ses_reputation_findings_failure",+ ),+ ]+ )+ def test_poll_failure_pushes_only_a_failure_marker(+ self, _name, task, provider_method, error, poll, reason, failure_job+ ):+ getattr(self.mock_provider, provider_method).side_effect = error- poll_ses_account_reputation()+ task()- self.mock_registry_factory.assert_not_called()+ assert self.mock_registry_factory.call_args_list == [call(failure_job)]+ assert (+ self.registry.get_sample_value(+ "posthog_ses_reputation_poll_last_failure_timestamp_seconds", {"poll": poll, "reason": reason}+ )+ == 1700000000.0+ )diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.pyindex 7ed89b38ede0..af87522ef152 100644--- a/products/workflows/backend/test/test_ses_provider.py+++ b/products/workflows/backend/test/test_ses_provider.py@@ -399,14 +399,14 @@ class TestSESResponseShapeContract(TestCase):"EnforcementStatus",lambda m: m.operation_model("GetAccount").output_shape.members.keys(),"AWS SES v2 GetAccount response no longer exposes `EnforcementStatus`. "- "Update get_account_reputation in products/workflows/backend/providers/ses.py.",+ "Update get_account_enforcement_status in products/workflows/backend/providers/ses.py.",),("recommendation_resource_arn","ResourceArn",lambda m: m.shape_for("Recommendation").members.keys(),"AWS SES v2 Recommendation no longer exposes `ResourceArn`. "- "Update get_account_reputation in products/workflows/backend/providers/ses.py.",+ "Update get_account_reputation_findings in products/workflows/backend/providers/ses.py.",),])@@ -537,8 +537,7 @@ class TestGetAccountReputation(TestCase):self.mock_client = mock_boto3_client.return_valueself.provider = SESProvider()- def test_returns_enforcement_status_and_open_findings_across_pages(self):- self.mock_client.get_account.return_value = {"EnforcementStatus": "PROBATION"}+ def test_returns_open_findings_across_pages(self):self.mock_client.list_recommendations.side_effect = [{"Recommendations": [@@ -572,10 +571,9 @@ class TestGetAccountReputation(TestCase):},]- result = self.provider.get_account_reputation()+ findings = self.provider.get_account_reputation_findings()- assert result["enforcement_status"] == "PROBATION"- assert [(f["finding_type"], f["impact"], f["scope"]) for f in result["findings"]] == [+ assert [(f["finding_type"], f["impact"], f["scope"]) for f in findings] == [("BOUNCE", "LOW", "tenant"),("DMARC", "HIGH", "identity"),("COMPLAINT", "HIGH", "account"),@@ -583,14 +581,15 @@ class TestGetAccountReputation(TestCase):# The listing must be account-wide with OPEN filtered server-side, and walk every pagefirst_call, second_call = self.mock_client.list_recommendations.call_args_listassert first_call.kwargs["Filter"] == {"STATUS": "OPEN"}+ assert first_call.kwargs["PageSize"] == 100assert second_call.kwargs["NextToken"] == "page-2"+ self.mock_client.get_account.assert_not_called()def test_missing_enforcement_status_fails_the_poll(self):self.mock_client.get_account.return_value = {}- self.mock_client.list_recommendations.return_value = {"Recommendations": []}with pytest.raises(KeyError):- self.provider.get_account_reputation()+ self.provider.get_account_enforcement_status()def _isp_of(query) -> str: