: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(mailgun): skip un-queryable domains in fan-out instead of failing the sync (#63430)
Tom Owers9154ab839113
diff --git a/posthog/temporal/data_imports/sources/mailgun/mailgun.py b/posthog/temporal/data_imports/sources/mailgun/mailgun.pyindex 291541dfc790..7f4e9000c397 100644--- a/posthog/temporal/data_imports/sources/mailgun/mailgun.py+++ b/posthog/temporal/data_imports/sources/mailgun/mailgun.py@@ -209,6 +209,19 @@ def _fetch_page(url: str, api_key: str, logger: FilteringBoundLogger) -> dict[streturn response.json()+def _is_skippable_domain_error(config: MailgunEndpointConfig, domain: Optional[str], error: requests.HTTPError) -> bool:+ """Whether a failed domain-scoped request should skip that domain instead of failing the sync.++ The domain fan-out lists every domain on the account (`/v4/domains`), including ones that+ can't be queried for events/suppressions — disabled, unverified, or sandbox-like domains.+ Those reject the domain-scoped request with a 400, so one bad domain would otherwise abort+ the whole fan-out and strand every other domain on the account."""+ if not config.domain_scoped or domain is None:+ return False+ response = error.response+ return response is not None and response.status_code == 400++def get_domain_names(api_key: str, base_url: str, logger: FilteringBoundLogger) -> list[str]:config = MAILGUN_ENDPOINTS["domains"]names: list[str] = []@@ -284,7 +297,21 @@ def get_rows(resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))continue- data = _fetch_page(current_url, api_key, logger)+ try:+ data = _fetch_page(current_url, api_key, logger)+ except requests.HTTPError as error:+ if not _is_skippable_domain_error(config, current_domain, error):+ raise+ logger.warning(+ f"Mailgun: skipping domain {current_domain} for {endpoint}; "+ f"request returned {error.response.status_code if error.response is not None else '?'}. "+ f"url={current_url}"+ )+ current_url = None+ current_domain = None+ resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))+ continue+items = data.get("items") or []if items:diff --git a/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.pyindex f07032baf1ec..2a40f97f53d4 100644--- a/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py+++ b/posthog/temporal/data_imports/sources/mailgun/tests/test_mailgun.py@@ -6,6 +6,8 @@ from urllib.parse import parse_qs, urlsplitimport pytestfrom unittest import mock+import requests+from posthog.temporal.data_imports.sources.mailgun.mailgun import (MAX_RETRY_AFTER_SECONDS,MailgunResumeConfig,@@ -45,6 +47,15 @@ def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMockreturn response+def _error_response(status_code: int, url: str) -> mock.MagicMock:+ response = _response({}, status_code)+ response.text = "Bad Request"+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: Bad Request for url: {url}", response=response+ )+ return response++def _paging_page(items: list[dict[str, Any]], next_url: str | None) -> dict[str, Any]:paging: dict[str, Any] = {"first": "f", "last": "l"}if next_url is not None:@@ -452,6 +463,52 @@ class TestGetRows:assert saved_states[-1].next_url is Noneassert saved_states[-1].pending_domains == []+ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_domain_scoped_400_skips_domain_and_continues_fan_out(self, mock_session):+ # The account lists a domain that can't be queried for events (disabled / unverified):+ # its 400 must skip the domain, not abort the whole fan-out, so b.com still imports.+ domains_page = {"items": [{"name": "a.com"}, {"name": "b.com"}]}+ a_bad = _error_response(400, f"{US_BASE}/v3/a.com/events")+ b_events = _paging_page([{"id": "e2", "timestamp": 1700000100.5}], None)+ mock_session.return_value.get.side_effect = [+ _response(domains_page),+ a_bad,+ _response(b_events),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", "us", "events", mock.MagicMock(), manager))++ rows = [row for batch in batches for row in batch]+ assert [(row["id"], row["domain"]) for row in rows] == [("e2", "b.com")]+ # The skipped domain leaves no in-flight chain behind, and the fan-out completes cleanly.+ saved_states = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved_states[0].current_domain is None+ assert saved_states[-1].next_url is None+ assert saved_states[-1].pending_domains == []++ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_account_level_400_still_raises(self, mock_session):+ # A 400 on a non-domain-scoped endpoint means our request is wrong, not a bad domain —+ # it must surface rather than be silently skipped.+ mock_session.return_value.get.return_value = _error_response(400, f"{US_BASE}/v3/lists/pages")++ manager = _make_manager()+ with pytest.raises(requests.HTTPError, match="400 Client Error"):+ list(get_rows("key", "us", "mailing_lists", mock.MagicMock(), manager))++ @mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_domain_scoped_500_still_raises(self, mock_session):+ # Server errors are transient and retryable — they must not be swallowed as a skip.+ domains_page = {"items": [{"name": "a.com"}]}+ server_error = _response({}, 500)+ mock_session.return_value.get.side_effect = [_response(domains_page), *([server_error] * 10)]++ manager = _make_manager()+ with pytest.raises(MailgunRetryableError):+ with mock.patch("tenacity.nap.time.sleep", return_value=None):+ list(get_rows("key", "us", "events", mock.MagicMock(), manager))+@mock.patch("posthog.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")def test_non_ok_response_raises(self, mock_session):response = _response({}, 401)