: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(mailchimp): retry 429/5xx in bespoke pagination loops (#80794)
Tom Owers965b795748f0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.pyindex c086240b6c63..f0699655ee49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py@@ -4,7 +4,8 @@ from datetime import date, datetimefrom typing import Any, Optionalfrom requests import Request, Response, Session-from requests.exceptions import RequestException+from requests.exceptions import HTTPError, RequestException+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -24,6 +25,38 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.)REQUEST_TIMEOUT_SECONDS = 120+MAX_RETRY_ATTEMPTS = 5+++class MailchimpRetryableError(Exception):+ pass+++@retry(+ retry=retry_if_exception_type(MailchimpRetryableError),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+)+def _get_with_retry(+ session: Session, url: str, params: dict[str, Any] | None = None, timeout: int = REQUEST_TIMEOUT_SECONDS+) -> Response:+ # Mailchimp's account-level rate limit windows can outlast the transport-level retry+ # already in `make_tracked_session`, so back off further here on 429/5xx.+ response = session.get(url, params=params, timeout=timeout)++ try:+ response.raise_for_status()+ except HTTPError as e:+ # Reraise 429/5xx under a retryable type but keep `raise_for_status`'s wording verbatim:+ # a failure that outlives this retry budget is classified downstream by message+ # (`import_data_sync` matching `MailchimpSource.get_retryable_errors`), so rephrasing it+ # here would make those "429 Client Error"/"Server Error" prefixes stop matching.+ if response.status_code == 429 or response.status_code >= 500:+ raise MailchimpRetryableError(str(e)) from e+ raise++ return response@dataclasses.dataclass@@ -217,12 +250,12 @@ def _fetch_all_lists(api_key: str, dc: str) -> list[dict[str, Any]]:session = _mailchimp_session(api_key)while True:- response = session.get(+ response = _get_with_retry(+ session,f"https://{dc}.api.mailchimp.com/3.0/lists",params={"count": page_size, "offset": offset},timeout=120,)- response.raise_for_status()data = response.json()lists.extend(data.get("lists", []))@@ -259,12 +292,12 @@ def _fetch_contacts_for_list(if since_last_changed:params["since_last_changed"] = since_last_changed- response = session.get(+ response = _get_with_retry(+ session,f"https://{dc}.api.mailchimp.com/3.0/lists/{list_id}/members",params=params,timeout=120,)- response.raise_for_status()data = response.json()contacts = data.get("members", [])@@ -368,8 +401,7 @@ def _iter_pages(if pagination == "offset":params["offset"] = offset- response = session.get(f"{base_url}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)- response.raise_for_status()+ response = _get_with_retry(session, f"{base_url}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)data = response.json()records = data.get(data_selector) or []@@ -432,8 +464,9 @@ def _fetch_endpoint_rows(parent_ids: Optional[list[str]],) -> Iterator[dict[str, Any]]:if config.single_object:- response = session.get(f"{base_url}{path}", params=dict(extra_params), timeout=REQUEST_TIMEOUT_SECONDS)- response.raise_for_status()+ response = _get_with_retry(+ session, f"{base_url}{path}", params=dict(extra_params), timeout=REQUEST_TIMEOUT_SECONDS+ )record = response.json()if isinstance(record, dict):yield {**record, **id_map}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.pyindex de8531c76807..093adefc93db 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py@@ -8,16 +8,19 @@ import pytestfrom unittest.mock import MagicMock, patchfrom requests import Request, Response-from requests.exceptions import ProxyError, RequestException+from requests.exceptions import HTTPError, ProxyError, RequestExceptionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.mailchimp import (+ MAX_RETRY_ATTEMPTS,MailchimpPaginator,MailchimpResumeConfig,+ MailchimpRetryableError,_fetch_contacts_for_list,_format_incremental_value,_get_contacts_iterator,_get_endpoint_iterator,+ _get_with_retry,_incremental_query_params,extract_data_center,mailchimp_source,@@ -102,6 +105,59 @@ class TestFormatIncrementalValue:assert _format_incremental_value("2024-01-15") == "2024-01-15"+class TestGetWithRetry:+ @pytest.mark.parametrize(+ ("status_code", "expected_error", "expected_call_count"),+ [+ # `MAX_RETRY_ATTEMPTS` is baked into the decorator at import time (it wraps a+ # top-level function, unlike the per-call nested functions other sources use), so+ # a retryable status is retried the full budget rather than a patched-down count.+ (429, MailchimpRetryableError, MAX_RETRY_ATTEMPTS),+ (500, MailchimpRetryableError, MAX_RETRY_ATTEMPTS),+ (401, HTTPError, 1),+ ],+ )+ def test_errors_are_classified(self, status_code, expected_error, expected_call_count):+ session = MagicMock()+ session.get.return_value = _make_http_response({}, status_code=status_code)++ with pytest.raises(expected_error):+ _get_with_retry(session, "https://us6.api.mailchimp.com/3.0/automations")++ assert session.get.call_count == expected_call_count++ @pytest.mark.parametrize(+ ("status_code", "reason", "expected_prefix"),+ [+ (429, "Too Many Requests", "429 Client Error"),+ (503, "Service Unavailable", "503 Server Error"),+ ],+ )+ def test_retryable_error_keeps_raise_for_status_wording(self, status_code, reason, expected_prefix):+ # A failure that outlives the retry budget is classified by message in `import_data_sync`+ # (via `MailchimpSource.get_retryable_errors`), so the wrapper must reraise the wording+ # `raise_for_status` produced rather than a phrasing of its own.+ url = "https://us6.api.mailchimp.com/3.0/automations"+ response = _make_http_response({}, status_code=status_code)+ response.reason = reason+ response.url = url+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(MailchimpRetryableError) as excinfo:+ _get_with_retry(session, url)++ assert str(excinfo.value).startswith(expected_prefix)+ assert url in str(excinfo.value)++ def test_success_returns_response_unchanged(self):+ session = MagicMock()+ response = _make_http_response({"total_items": 0}, status_code=200)+ session.get.return_value = response++ assert _get_with_retry(session, "https://us6.api.mailchimp.com/3.0/lists") is response++class TestMailchimpPaginator:def test_initial_state(self):paginator = MailchimpPaginator(page_size=100)@@ -176,6 +232,7 @@ def _fake_manager(*, can_resume: bool = False, load_state: MailchimpResumeConfigdef _build_response(members: list[dict[str, Any]], total_items: int) -> MagicMock:response = MagicMock()+ response.status_code = 200response.json.return_value = {"members": members, "total_items": total_items}response.raise_for_status.return_value = Nonereturn response@@ -529,6 +586,7 @@ def _routed_session(routes: dict[str, list[dict[str, Any]]]) -> tuple[Any, list[seen[path] = seen.get(path, 0) + 1response = MagicMock()+ response.status_code = 200response.json.return_value = bodies[index]response.raise_for_status.return_value = Nonereturn response