Skip to content

: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.

fix(meta_ads): retry transient connection resets during pagination (#72392)

Tom Owersb6a9b76302f4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
index 6cc15916bf9d..d1dd85d54439 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -10,7 +10,12 @@ from django.db import OperationalError, close_old_connections
import structlog
from requests import Response
-from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
+from requests.exceptions import (
+ ChunkedEncodingError,
+ ConnectionError as RequestsConnectionError,
+ JSONDecodeError as RequestsJSONDecodeError,
+ ReadTimeout,
+)
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, MetaAdsIntegration
@@ -307,25 +312,41 @@ def _is_transient_error(response: Response) -> bool:
return error.get("is_transient") is True
+# Meta's connection occasionally resets mid-response — `requests` raises these while decoding the
+# body, after urllib3's own connection-level retries have already returned headers, so there's no
+# `Response` object yet to inspect for `_is_transient_error`. Re-issuing the same request is safe:
+# nothing was yielded from the failed one yet.
+NETWORK_TRANSIENT_ERRORS = (ChunkedEncodingError, RequestsConnectionError, ReadTimeout)
+
+
def _get_with_transient_retry(issue: collections.abc.Callable[[], Response]) -> Response:
- """Issue a request, absorbing Meta's transient server errors with a short backoff.
+ """Issue a request, absorbing transient network failures and Meta's transient server errors.
Re-issuing the same request is safe: a transiently-failed request yielded no rows. Too-much-data
- timeouts are left for the caller's limit-shrinking path. If it stays transient past the bound the
- last response is returned unchanged, so the caller raises it as usual (staying retryable upstream).
+ timeouts are left for the caller's limit-shrinking path. If a failure persists past the bound, the
+ last response (or exception) propagates as usual, so the caller raises it, staying retryable upstream.
"""
- response = issue()
attempt = 1
- while (
- attempt < META_TRANSIENT_ERROR_MAX_ATTEMPTS
- and response.status_code != 200
- and _is_transient_error(response)
- and not _is_timeout_error(response)
- ):
+ while True:
+ try:
+ response = issue()
+ except NETWORK_TRANSIENT_ERRORS:
+ if attempt >= META_TRANSIENT_ERROR_MAX_ATTEMPTS:
+ raise
+ _backoff_sleep(attempt)
+ attempt += 1
+ continue
+
+ if (
+ attempt >= META_TRANSIENT_ERROR_MAX_ATTEMPTS
+ or response.status_code == 200
+ or not _is_transient_error(response)
+ or _is_timeout_error(response)
+ ):
+ return response
+
_backoff_sleep(attempt)
- response = issue()
attempt += 1
- return response
def _get_initial_request(url: str, params: dict) -> Response:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
index e7fe05f87a19..50bd10645eaa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
@@ -8,7 +8,10 @@ from unittest import mock
from django.db import OperationalError
-from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
+from requests.exceptions import (
+ ChunkedEncodingError,
+ JSONDecodeError as RequestsJSONDecodeError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
IntegrationAccountListingError,
@@ -456,6 +459,43 @@ class TestTransientErrorRetry:
assert mock_get.return_value.get.call_count == META_TRANSIENT_ERROR_MAX_ATTEMPTS
+class TestNetworkTransientRetry:
+ INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"
+ PARAMS: dict[str, Any] = {"fields": "id,name", "limit": 500, "access_token": "tok"}
+
+ def test_connection_reset_reissues_same_request_then_succeeds(self, monkeypatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ responses = [
+ ChunkedEncodingError("Connection broken: ConnectionResetError(104, 'Connection reset by peer')"),
+ _mock_response(200, {"data": [{"id": "1"}], "paging": {}}),
+ ]
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"
+ ) as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ batches = list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))
+
+ assert batches == [[{"id": "1"}]]
+ assert mock_get.return_value.get.call_count == 2
+
+ def test_persistent_connection_reset_raises_after_bounded_attempts(self, monkeypatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ responses = [ChunkedEncodingError("Connection broken") for _ in range(META_TRANSIENT_ERROR_MAX_ATTEMPTS)]
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"
+ ) as mock_get:
+ mock_get.return_value.get.side_effect = responses
+ # Still surfaces the raw failure so it stays retryable at the Temporal layer.
+ with pytest.raises(ChunkedEncodingError):
+ list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))
+
+ assert mock_get.return_value.get.call_count == META_TRANSIENT_ERROR_MAX_ATTEMPTS
+
+
class TestTimeRangePagination:
URL = "https://graph.facebook.com/v20/act_1/insights"
PARAMS: dict[str, Any] = {"fields": "ad_id", "limit": 500, "level": "ad", "access_token": "tok"}