: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(warehouse-sources): keep an SES pool AWS refuses to describe (#100474)
posthog[bot]4f66698b63a2
diff --git a/docs/internal/aws-ses-pool-imports.md b/docs/internal/aws-ses-pool-imports.mdnew file mode 100644index 000000000000..bacdcb925231--- /dev/null+++ b/docs/internal/aws-ses-pool-imports.md@@ -0,0 +1,34 @@+# Amazon SES pool imports++The `dedicated_ip_pools` table lists pool names and adds details from `GetDedicatedIpPool`.+AWS reserves `ses-shared-pool` and `ses-default-dedicated-pool` for its shared and default dedicated pools.+See the [AWS pool documentation](https://docs.aws.amazon.com/ses/latest/dg/managing-ip-pools.html).++If AWS lists either reserved pool but rejects its detail request with `BadRequestException`, the connector keeps a row with `pool_name` only.+Missing details do not imply a scaling mode or ownership of dedicated IP addresses.+If AWS returns details for either pool, the connector keeps them.++Import and schema discovery use the same detail-fetch helper.+The endpoint configuration limits the fallback to exact names, and no other endpoint enables it.+The helper reuses the existing signed requests and tracked HTTP transport.+Pagination, retry handling, and row normalization remain unchanged.++A rejected list request, a rejected custom pool detail request, or a different detail error does not use this fallback.+Existing handling for deleted items, access failures, and transient errors remains unchanged.++## Tests++Run the connector tests:++```sh+hogli test products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py+```++Run the import workflow regression test with the local development services:++```sh+hogli test products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_aws_ses_source.py+```++The workflow test supplies controlled AWS HTTP responses and checks the imported warehouse data.+It does not test a live AWS account.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.pyindex 1349214e6a98..dc4501e6bef8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py@@ -221,6 +221,28 @@ def resolve_start_date(return watermark - INCREMENTAL_OVERLAP+def _get_item_detail(+ session: requests.Session,+ credentials: Credentials,+ region: str,+ endpoint_config: AwsSesEndpointConfig,+ name: str,+) -> dict[str, Any]:+ assert endpoint_config.detail_path is not None+ try:+ return send_request(+ session,+ credentials,+ region,+ endpoint_config.name,+ endpoint_config.detail_path.format(name=quote(name, safe="")),+ )+ except AwsSesError as error:+ if error.code == "BadRequestException" and name in endpoint_config.list_only_on_bad_request:+ return {}+ raise++def _fanout_page_rows(session: requests.Session,credentials: Credentials,@@ -229,7 +251,7 @@ def _fanout_page_rows(body: dict[str, Any],logger: FilteringBoundLogger,) -> list[dict[str, Any]]:- """One full row per listed item, fetched via the endpoint's detail operation."""+ """Combine each listed item with its available details."""assert endpoint_config.detail_path is not None and endpoint_config.name_column is not Nonerows: list[dict[str, Any]] = []@@ -239,13 +261,7 @@ def _fanout_page_rows(continuetry:- detail = send_request(- session,- credentials,- region,- endpoint_config.name,- endpoint_config.detail_path.format(name=quote(name, safe="")),- )+ detail = _get_item_detail(session, credentials, region, endpoint_config, name)except AwsSesError as error:if error.code == "NotFoundException":logger.debug(f"Skipping {endpoint_config.name} item deleted mid-sync. name={name}")@@ -388,13 +404,7 @@ def endpoint_permission_reason(for item in (body.get(endpoint_config.result_key or "") or [])[:1]:name = item.get(endpoint_config.item_name_key) if isinstance(item, dict) else itemif isinstance(name, str) and name:- send_request(- session,- credentials,- region,- endpoint_config.name,- endpoint_config.detail_path.format(name=quote(name, safe="")),- )+ _get_item_detail(session, credentials, region, endpoint_config, name)except AwsSesError as error:return _permission_reason(error)except Exception:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.pyindex 6ecafa9c1187..557194eec3a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.py@@ -33,6 +33,7 @@ class AwsSesEndpointConfig:# Fan-out: column carrying the item name. Set explicitly on every row because detail# responses (GetEmailIdentity) do not echo the name back.name_column: str | None = None+ list_only_on_bad_request: frozenset[str] = frozenset()# ListSuppressedDestinations accepts a server-side `StartDate` filter, which is what makes# that endpoint genuinely incremental.supports_start_date: bool = False@@ -88,6 +89,7 @@ AWS_SES_ENDPOINTS: dict[str, AwsSesEndpointConfig] = {page_size=100,detail_path="/v2/email/dedicated-ip-pools/{name}",name_column="pool_name",+ list_only_on_bad_request=frozenset({"ses-shared-pool", "ses-default-dedicated-pool"}),),"dedicated_ips": AwsSesEndpointConfig(name="dedicated_ips",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.pyindex 440530cbb5cc..de0470ea83e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py@@ -474,6 +474,74 @@ class TestGetRows:assert [row["identity_name"] for batch in batches for row in batch] == ["kept.example.com"]+ @pytest.mark.parametrize("pool_name", ["ses-shared-pool", "ses-default-dedicated-pool"])+ def test_an_item_aws_refuses_to_describe_is_reported_from_the_list_response_alone(self, pool_name: str) -> None:+ batches, _, _ = self._run(+ [+ {"DedicatedIpPools": [pool_name, "marketing-pool"]},+ AwsSesError("BadRequestException", "shared or default pool", "dedicated_ip_pools", "/path"),+ {"DedicatedIpPool": {"PoolName": "marketing-pool", "ScalingMode": "MANAGED"}},+ ],+ endpoint="dedicated_ip_pools",+ )++ assert batches == [+ [+ {"pool_name": pool_name},+ {+ "pool_name": "marketing-pool",+ "dedicated_ip_pool_pool_name": "marketing-pool",+ "dedicated_ip_pool_scaling_mode": "MANAGED",+ },+ ]+ ]++ @pytest.mark.parametrize("pool_name", ["ses-shared-pool", "ses-default-dedicated-pool"])+ def test_reserved_pool_details_are_kept_when_aws_returns_them(self, pool_name: str) -> None:+ batches, _, _ = self._run(+ [+ {"DedicatedIpPools": [pool_name]},+ {"DedicatedIpPool": {"PoolName": pool_name, "ScalingMode": "STANDARD"}},+ ],+ endpoint="dedicated_ip_pools",+ )++ assert batches == [+ [+ {+ "pool_name": pool_name,+ "dedicated_ip_pool_pool_name": pool_name,+ "dedicated_ip_pool_scaling_mode": "STANDARD",+ }+ ]+ ]++ @pytest.mark.parametrize(+ "endpoint,page,code",+ [+ ("dedicated_ip_pools", {"DedicatedIpPools": ["marketing-pool"]}, "TooManyRequestsException"),+ ("dedicated_ip_pools", {"DedicatedIpPools": ["marketing-pool"]}, "BadRequestException"),+ ("dedicated_ip_pools", {"DedicatedIpPools": ["ses-shared-pool-custom"]}, "BadRequestException"),+ ("dedicated_ip_pools", {"DedicatedIpPools": ["ses-shared-pool"]}, "AccessDeniedException"),+ ("dedicated_ip_pools", {"DedicatedIpPools": ["ses-default-dedicated-pool"]}, "TooManyRequestsException"),+ ("dedicated_ip_pools", {"DedicatedIpPools": ["ses-shared-pool"]}, "HTTP 503"),+ ("configuration_sets", {"ConfigurationSets": ["ses-shared-pool"]}, "BadRequestException"),+ ("contact_lists", {"ContactLists": [{"ContactListName": "ses-shared-pool"}]}, "BadRequestException"),+ (+ "custom_verification_email_templates",+ {"CustomVerificationEmailTemplates": [{"TemplateName": "ses-shared-pool"}]},+ "BadRequestException",+ ),+ ("email_identities", {"EmailIdentities": [{"IdentityName": "example.com"}]}, "BadRequestException"),+ ("email_templates", {"TemplatesMetadata": [{"TemplateName": "ses-shared-pool"}]}, "BadRequestException"),+ ],+ )+ def test_a_detail_failure_the_table_cannot_absorb_still_fails_the_job(+ self, endpoint: str, page: dict[str, Any], code: str+ ) -> None:+ with pytest.raises(AwsSesError, match=code):+ self._run([page, AwsSesError(code, "rejected", endpoint, "/path")], endpoint=endpoint)+def test_an_empty_page_yields_no_batch_but_still_completes_the_walk(self) -> None:batches, _, manager = self._run([suppression_page([])])@@ -775,3 +843,51 @@ class TestEndpointPermissions:reasons = probe_endpoint_permissions("key", "secret", None, "us-east-1", ["multi_region_endpoints"])assert reasons == {"multi_region_endpoints": aws_ses._BAD_REQUEST_EXPLANATION}++ @pytest.mark.parametrize(+ "pool_name,code,status_code,expected_reason",+ [+ ("ses-shared-pool", "BadRequestException", 400, None),+ ("ses-default-dedicated-pool", "BadRequestException", 400, None),+ ("marketing-pool", "BadRequestException", 400, aws_ses._BAD_REQUEST_EXPLANATION),+ ("ses-shared-pool-custom", "BadRequestException", 400, aws_ses._BAD_REQUEST_EXPLANATION),+ (+ "ses-shared-pool",+ "AccessDeniedException",+ 403,+ "The connected IAM user or role is not allowed to read this table",+ ),+ ],+ )+ def test_pool_discovery_and_validation_only_allow_known_detail_rejections(+ self, requests_mock: Any, pool_name: str, code: str, status_code: int, expected_reason: Optional[str]+ ) -> None:+ pool_url = "https://email.us-east-1.amazonaws.com/v2/email/dedicated-ip-pools"+ requests_mock.get(pool_url, json={"DedicatedIpPools": [pool_name]})+ requests_mock.get(+ f"{pool_url}/{pool_name}", status_code=status_code, headers={"x-amzn-ErrorType": code}, json={}+ )++ assert probe_endpoint_permissions("key", "secret", None, "us-east-1", ["dedicated_ip_pools"]) == {+ "dedicated_ip_pools": expected_reason+ }+ assert validate_credentials("key", "secret", None, "us-east-1", schema_name="dedicated_ip_pools") == (+ expected_reason is None,+ expected_reason,+ )++ def test_a_rejected_pool_list_still_blocks_discovery_and_validation(self, requests_mock: Any) -> None:+ requests_mock.get(+ "https://email.us-east-1.amazonaws.com/v2/email/dedicated-ip-pools",+ status_code=400,+ headers={"x-amzn-ErrorType": "BadRequestException"},+ json={},+ )++ assert probe_endpoint_permissions("key", "secret", None, "us-east-1", ["dedicated_ip_pools"]) == {+ "dedicated_ip_pools": aws_ses._BAD_REQUEST_EXPLANATION+ }+ assert validate_credentials("key", "secret", None, "us-east-1", schema_name="dedicated_ip_pools") == (+ False,+ aws_ses._BAD_REQUEST_EXPLANATION,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_aws_ses_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_aws_ses_source.pynew file mode 100644index 000000000000..224879cd3412--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_aws_ses_source.py@@ -0,0 +1,100 @@+import uuid++import pytest++from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.conftest import run_external_data_job_workflow++pytestmark = pytest.mark.usefixtures("minio_client")+++def external_data_source(team):+ return ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ team=team,+ status="running",+ source_type=ExternalDataSourceType.AWSSES,+ job_inputs={+ "aws_access_key_id": "test-access-key",+ "aws_secret_access_key": "test-secret-key",+ "aws_region": "us-east-1",+ },+ )+++def external_data_schema_full_refresh(external_data_source, team):+ return ExternalDataSchema.objects.create(+ name="dedicated_ip_pools",+ team_id=team.pk,+ source_id=external_data_source.pk,+ sync_type="full_refresh",+ sync_type_config={},+ )++[email protected]_db(transaction=True)[email protected]("include_normal_pools", [True, False], ids=["mixed-pools", "reserved-pools-only"])+async def test_aws_ses_reserved_pools_full_refresh(+ team, requests_mock, external_data_source, external_data_schema_full_refresh, include_normal_pools+):+ pools_url = "https://email.us-east-1.amazonaws.com/v2/email/dedicated-ip-pools"+ first_page = ["ses-shared-pool"]+ second_page = ["ses-default-dedicated-pool"]+ expected_rows: list[tuple[str | None, ...]] = [+ ("ses-shared-pool", None, None),+ ("ses-default-dedicated-pool", None, None),+ ]+ expected_columns = ["pool_name", "dedicated_ip_pool_pool_name", "dedicated_ip_pool_scaling_mode"]++ if include_normal_pools:+ first_page.insert(0, "marketing-pool")+ second_page.append("transactional-pool")+ for pool_name, scaling_mode in [("marketing-pool", "MANAGED"), ("transactional-pool", "STANDARD")]:+ requests_mock.get(+ f"{pools_url}/{pool_name}",+ json={"DedicatedIpPool": {"PoolName": pool_name, "ScalingMode": scaling_mode}},+ )+ expected_rows.append((pool_name, pool_name, scaling_mode))+ else:+ expected_columns = ["pool_name"]+ expected_rows = [(row[0],) for row in expected_rows]++ requests_mock.get(+ f"{pools_url}?PageSize=100",+ complete_qs=True,+ json={"DedicatedIpPools": first_page, "NextToken": "second-page"},+ )+ requests_mock.get(+ f"{pools_url}?NextToken=second-page&PageSize=100",+ complete_qs=True,+ json={"DedicatedIpPools": second_page},+ )+ reserved_detail_requests = [+ requests_mock.get(+ f"{pools_url}/{pool_name}",+ status_code=400,+ headers={"x-amzn-ErrorType": "BadRequestException"},+ json={},+ )+ for pool_name in ["ses-shared-pool", "ses-default-dedicated-pool"]+ ]++ result = await run_external_data_job_workflow(+ team=team,+ external_data_source=external_data_source,+ external_data_schema=external_data_schema_full_refresh,+ table_name="awsses_dedicated_ip_pools",+ expected_rows_synced=len(expected_rows),+ expected_total_rows=len(expected_rows),+ expected_columns=expected_columns,+ )++ assert result.results is not None+ assert sorted(tuple(row) for row in result.results) == sorted(expected_rows)+ assert all(detail_request.called for detail_request in reserved_detail_requests)