: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): poll AWS SES account reputation for alerting (#78805)
Harley Alexandera598b4b5e0d6
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 44da5c60810b..779403062dbd 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -124,6 +124,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (reap_stale_prewarm_heatmaps,report_stuck_heatmap_screenshots,)+from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputationTWENTY_FOUR_HOURS = 24 * 60 * 60@@ -348,6 +349,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="reconcile loop trigger schedules",)+ # AWS SES account reputation → gauges for team-facing alerting (charts alerts/specs/ses.yaml)+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*/10"),+ poll_ses_account_reputation.s(),+ name="poll SES account reputation",+ expires_seconds=10 * 60,+ )+# Flags cache sync - hourlysender.add_periodic_task(crontab(hour="*", minute="15"),diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.pyindex 71f120fc5f4a..311e47c8a153 100644--- a/products/workflows/backend/providers/ses.py+++ b/products/workflows/backend/providers/ses.py@@ -1,6 +1,6 @@import reimport logging-from collections.abc import Iterable+from collections.abc import Iterable, Iteratorfrom functools import cached_propertyfrom typing import TYPE_CHECKING, Any@@ -15,6 +15,7 @@ from rest_framework import exceptionsif TYPE_CHECKING:from types_boto3_ses.client import SESClientfrom types_boto3_sesv2.client import SESV2Client+ from types_boto3_sesv2.type_defs import RecommendationTypeDeflogger = logging.getLogger(__name__)@@ -82,28 +83,16 @@ class SESProvider:sending_status = entity.get("SendingStatusAggregate", sending_status)# RESOURCE_ARN is the only filter key AWS documents as usable on its own with this- # scoping; STATUS is filtered locally because the documented two-key combinations- # (STATUS+IMPACT, STATUS+TYPE) don't include RESOURCE_ARN.- finding_filter: dict[Any, str] = {"RESOURCE_ARN": tenant_arn}- next_token: str | None = None- while True:- if next_token:- page = self.ses_v2_client.list_recommendations(Filter=finding_filter, NextToken=next_token)- else:- page = self.ses_v2_client.list_recommendations(Filter=finding_filter)- findings.extend(- {- "finding_type": recommendation.get("Type", ""),- "impact": recommendation.get("Impact", "LOW"),- "description": recommendation.get("Description", ""),- "last_updated_at": recommendation.get("LastUpdatedTimestamp"),- }- for recommendation in page.get("Recommendations", [])- if recommendation.get("Status") == "OPEN"- )- next_token = page.get("NextToken")- if not next_token:- break+ # scoping (see _iter_open_recommendations for why STATUS is filtered locally).+ findings.extend(+ {+ "finding_type": recommendation.get("Type", ""),+ "impact": recommendation.get("Impact", "LOW"),+ "description": recommendation.get("Description", ""),+ "last_updated_at": recommendation.get("LastUpdatedTimestamp"),+ }+ for recommendation in self._iter_open_recommendations({"RESOURCE_ARN": tenant_arn})+ )return {"sending_status": sending_status,@@ -111,6 +100,54 @@ class SESProvider:"findings": findings,}+ def _iter_open_recommendations(self, finding_filter: dict[Any, str] | None) -> Iterator["RecommendationTypeDef"]:+ """+ Walk every page of ListRecommendations, yielding only OPEN recommendations. The local+ STATUS check exists for RESOURCE_ARN-filtered calls: AWS documents STATUS as combinable+ only 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 {}+ while True:+ page = self.ses_v2_client.list_recommendations(**kwargs)+ for recommendation in page.get("Recommendations", []):+ if recommendation.get("Status") == "OPEN":+ yield recommendation+ next_token = page.get("NextToken")+ if not next_token:+ return+ kwargs["NextToken"] = next_token++ def get_account_reputation(self) -> dict[str, Any]:+ """+ 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.+ """+ # 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 = [+ {+ "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"})+ ]+ return {"enforcement_status": enforcement_status, "findings": findings}++ @staticmethod+ def _finding_scope(resource_arn: str) -> str:+ # Tenant and identity findings are a customer's sender health; anything else+ # (configuration sets, the account itself, an unrecognized or missing ARN) is+ # treated as shared infrastructure so classification errs toward alerting us.+ if ":tenant/" in resource_arn:+ return "tenant"+ if ":identity/" in resource_arn:+ return "identity"+ return "account"+@cached_propertydef _aws_account_id(self) -> str:return self.sts_client.get_caller_identity()["Account"]diff --git a/products/workflows/backend/tasks/__init__.py b/products/workflows/backend/tasks/__init__.pyindex 50b82e95f50b..919bab02c9ad 100644--- a/products/workflows/backend/tasks/__init__.py+++ b/products/workflows/backend/tasks/__init__.py@@ -1,3 +1,3 @@-from . import hog_flows+from . import hog_flows, ses_account_reputation-__all__ = ["hog_flows"]+__all__ = ["hog_flows", "ses_account_reputation"]diff --git a/products/workflows/backend/tasks/ses_account_reputation.py b/products/workflows/backend/tasks/ses_account_reputation.pynew file mode 100644index 000000000000..756933417023--- /dev/null+++ b/products/workflows/backend/tasks/ses_account_reputation.py@@ -0,0 +1,56 @@+import time+from collections import Counter++from celery import shared_task+from prometheus_client import Gauge+from structlog import get_logger++from posthog.metrics import pushed_metrics_registry+from posthog.tasks.utils import CeleryQueue++from products.workflows.backend.providers.ses import SESProvider++logger = get_logger(__name__)+++@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+def poll_ses_account_reputation() -> 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.+ """+ 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)+ return++ finding_counts = Counter(+ (finding["scope"], finding["finding_type"], finding["impact"]) for finding in reputation["findings"]+ )++ with pushed_metrics_registry("ses_account_reputation") as registry:+ Gauge(+ "posthog_ses_account_enforcement_healthy",+ "1 while AWS SES reports the account EnforcementStatus as HEALTHY, 0 otherwise.",+ registry=registry,+ ).set(1 if reputation["enforcement_status"] == "HEALTHY" else 0)++ findings_gauge = Gauge(+ "posthog_ses_open_reputation_findings",+ "Open AWS SES reputation findings (ListRecommendations), by referenced resource scope.",+ labelnames=["scope", "finding_type", "impact"],+ registry=registry,+ )+ for (scope, finding_type, impact), count in finding_counts.items():+ 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.",+ registry=registry,+ ).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.pynew file mode 100644index 000000000000..48d707319112--- /dev/null+++ b/products/workflows/backend/test/test_ses_account_reputation_task.py@@ -0,0 +1,74 @@+from unittest import TestCase+from unittest.mock import MagicMock, patch++from botocore.exceptions import ClientError+from parameterized import parameterized+from prometheus_client import CollectorRegistry++from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation+++class TestPollSesAccountReputation(TestCase):+ def setUp(self):+ self.registry = CollectorRegistry()+ registry_context = MagicMock()+ registry_context.__enter__ = MagicMock(return_value=self.registry)+ registry_context.__exit__ = MagicMock(return_value=False)+ self.registry_patcher = patch(+ "products.workflows.backend.tasks.ses_account_reputation.pushed_metrics_registry",+ return_value=registry_context,+ )+ self.mock_registry_factory = self.registry_patcher.start()+ self.addCleanup(self.registry_patcher.stop)++ provider_patcher = patch("products.workflows.backend.tasks.ses_account_reputation.SESProvider")+ self.mock_provider = provider_patcher.start().return_value+ self.addCleanup(provider_patcher.stop)++ @parameterized.expand(+ [+ ("HEALTHY", 1.0),+ ("PROBATION", 0.0),+ ("SHUTDOWN", 0.0),+ ]+ )+ def test_exports_enforcement_health_gauge(self, status, expected):+ self.mock_provider.get_account_reputation.return_value = {"enforcement_status": status, "findings": []}++ poll_ses_account_reputation()++ assert self.registry.get_sample_value("posthog_ses_account_enforcement_healthy") == expected++ @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"},+ ],+ }++ poll_ses_account_reputation()++ def finding_count(scope, finding_type, impact):+ return self.registry.get_sample_value(+ "posthog_ses_open_reputation_findings",+ {"scope": scope, "finding_type": finding_type, "impact": impact},+ )++ assert finding_count("tenant", "BOUNCE", "LOW") == 2+ assert finding_count("account", "COMPLAINT", "HIGH") == 1+ assert (+ self.registry.get_sample_value("posthog_ses_account_reputation_last_poll_timestamp_seconds") == 1700000000.0+ )++ def test_provider_failure_does_not_raise_and_pushes_nothing(self):+ self.mock_provider.get_account_reputation.side_effect = ClientError(+ {"Error": {"Code": "AccessDenied"}}, "GetAccount"+ )++ poll_ses_account_reputation()++ self.mock_registry_factory.assert_not_called()diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.pyindex a81f8285d610..efc7a71b2ccf 100644--- a/products/workflows/backend/test/test_ses_provider.py+++ b/products/workflows/backend/test/test_ses_provider.py@@ -387,6 +387,20 @@ class TestSESResponseShapeContract(TestCase):"AWS SES v2 ResourceTenantMetadata no longer exposes `TenantName`. ""Update _list_identity_tenants in products/workflows/backend/providers/ses.py.",),+ (+ "get_account_enforcement_status",+ "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.",+ ),+ (+ "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.",+ ),])def test_sdk_shape_exposes_field(self, _name, expected_key, get_members, message):@@ -506,3 +520,67 @@ class TestGetTenantReputation(TestCase):first_call, second_call = self.mock_client.list_recommendations.call_args_listassert first_call.kwargs["Filter"] == {"RESOURCE_ARN": self.TENANT_ARN}assert second_call.kwargs["NextToken"] == "page-2"+++class TestGetAccountReputation(TestCase):+ def setUp(self):+ patcher = patch("products.workflows.backend.providers.ses.boto3.client")+ mock_boto3_client = patcher.start()+ self.addCleanup(patcher.stop)+ self.mock_client = mock_boto3_client.return_value+ self.provider = SESProvider()++ def test_returns_enforcement_status_and_open_findings_across_pages(self):+ self.mock_client.get_account.return_value = {"EnforcementStatus": "PROBATION"}+ self.mock_client.list_recommendations.side_effect = [+ {+ "Recommendations": [+ {+ "Type": "BOUNCE",+ "Impact": "LOW",+ "Status": "OPEN",+ "ResourceArn": "arn:aws:ses:us-east-1:123:tenant/team-1/tn-abc",+ "Description": "Bounce rate exceeded 10%",+ },+ ],+ "NextToken": "page-2",+ },+ {+ "Recommendations": [+ {+ "Type": "DMARC",+ "Impact": "HIGH",+ "Status": "OPEN",+ "ResourceArn": "arn:aws:ses:us-east-1:123:identity/customer.example.com",+ "Description": "DMARC5",+ },+ {+ "Type": "COMPLAINT",+ "Impact": "HIGH",+ "Status": "OPEN",+ "ResourceArn": "arn:aws:ses:us-east-1:123:configuration-set/posthog-messaging",+ "Description": "Complaint rate elevated",+ },+ ]+ },+ ]++ result = self.provider.get_account_reputation()++ assert result["enforcement_status"] == "PROBATION"+ assert [(f["finding_type"], f["impact"], f["scope"]) for f in result["findings"]] == [+ ("BOUNCE", "LOW", "tenant"),+ ("DMARC", "HIGH", "identity"),+ ("COMPLAINT", "HIGH", "account"),+ ]+ # The listing must be account-wide with OPEN filtered server-side, and walk every page+ first_call, second_call = self.mock_client.list_recommendations.call_args_list+ assert first_call.kwargs["Filter"] == {"STATUS": "OPEN"}+ assert second_call.kwargs["NextToken"] == "page-2"++ 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()