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(data-imports): retry connection errors in the shared REST client (#72853)

Tom Owers65fba8b6fb0f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index 1cf36919644b..fc93514d2384 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -10,6 +10,7 @@ from requests import Request, Response, Session
from requests.auth import AuthBase
from requests.exceptions import (
ChunkedEncodingError,
+ ConnectionError as RequestsConnectionError,
HTTPError,
JSONDecodeError as RequestsJSONDecodeError,
)
@@ -340,11 +341,26 @@ class RESTClient:
# retryable-error type so it propagates immediately rather than being retried.
self._check_allowed_host(prepared.url)
# `send` reads the body eagerly (stream=False), so a connection dropped mid-stream
- # surfaces here as ChunkedEncodingError. Reissue it like a truncated/partial body below.
+ # surfaces here as ChunkedEncodingError. A connection that never got established at all —
+ # egress proxy refusing/resetting the connection, a connect timeout — surfaces as
+ # ConnectionError (already retried a few times inside urllib3's own adapter-level policy,
+ # but that budget is short). Both are transient network failures, so reissue them like a
+ # truncated/partial body below rather than letting them skip this retry loop and fail the
+ # whole sync on one bad connection attempt.
try:
response = self.session.send(prepared, allow_redirects=self._allow_redirects)
except ChunkedEncodingError as e:
raise RESTClientRetryableError(self._redact(f"Connection broken while reading response: {e}")) from e
+ except RequestsConnectionError as e:
+ # Unlike ChunkedEncodingError, a ConnectionError's message (e.g. urllib3's "Max
+ # retries exceeded with url: ...") embeds the full request URL including the query
+ # string. `_redact` only replaces a secret's raw value, not the percent-encoded form
+ # a query-param API key takes there — so build the message from `_safe_url` (scheme/
+ # host/path only) rather than the raw exception text, the same way the 5xx path below
+ # avoids leaking an encoded credential into the persisted `latest_error`.
+ raise RESTClientRetryableError(
+ self._redact(f"Connection error ({type(e).__name__}) for {_safe_url(prepared.url or '')}")
+ ) from e
# With redirects disabled, a 3xx is not an error to `raise_for_status` and would fall
# through to JSON parsing; reject it explicitly so a redirect can't smuggle the request
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
index dd27ef3ded72..1b26eb463ecd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
@@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from requests import Response
+from requests.exceptions import ConnectionError as RequestsConnectionError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
@@ -47,6 +48,28 @@ def _make_client(secret: str, MockSession: MagicMock) -> MagicMock:
return mock_session
+def _make_client_with_credentialed_url(secret: str, MockSession: MagicMock) -> MagicMock:
+ # Unlike `_make_client`, the prepared URL itself carries the query-encoded credential — this
+ # is what a real `session.prepare_request()` produces once the auth hook injects the query
+ # param, and it's what `_send_request` sees when a connection error fires before any response.
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ prepared = MagicMock()
+ prepared.url = f"https://api.example.com/items?api_key={quote(secret, safe='')}"
+ mock_session.prepare_request.return_value = prepared
+ return mock_session
+
+
+def _make_connection_error(secret: str) -> RequestsConnectionError:
+ # Mirrors urllib3's real "Max retries exceeded with url: ..." message shape, which embeds the
+ # full request URL (query string included) in the exception text itself.
+ url = f"https://api.example.com/items?api_key={quote(secret, safe='')}"
+ return RequestsConnectionError(
+ f"HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: {url} "
+ "(Caused by ProxyError('Cannot connect to proxy.'))"
+ )
+
+
class TestExceptionRedaction:
@patch(f"{MODULE}.make_tracked_session")
def test_client_error_masks_secret_in_place(self, MockSession) -> None:
@@ -103,6 +126,25 @@ class TestExceptionRedaction:
assert quote(secret, safe="") not in message
assert "?" not in message
+ @parameterized.expand([("raw", SECRET), ("reserved_chars", SPECIAL_SECRET)])
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_connection_error_drops_query_so_no_secret_leaks(self, _name: str, secret: str, MockSession) -> None:
+ mock_session = _make_client_with_credentialed_url(secret, MockSession)
+ mock_session.send.side_effect = _make_connection_error(secret)
+ client = RESTClient(
+ base_url="https://api.example.com",
+ auth=APIKeyAuth(api_key=secret, name="api_key", location="query"),
+ max_retry_attempts=1,
+ )
+ with pytest.raises(RESTClientRetryableError) as excinfo:
+ list(client.paginate(path="/items"))
+ message = str(excinfo.value)
+ # Neither the raw nor the percent-encoded secret survives; the query is dropped entirely.
+ assert secret not in message
+ assert quote(secret, safe="") not in message
+ assert "?" not in message
+ assert "api.example.com/items" in message
+
@patch(f"{MODULE}.make_tracked_session")
def test_no_auth_still_reports_host_and_path(self, MockSession) -> None:
mock_session = _make_client(SECRET, MockSession)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
index a7a4df0c5cb1..68cdb272bbef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
@@ -6,7 +6,7 @@ import pytest
from unittest.mock import MagicMock, patch
from requests import Response
-from requests.exceptions import ChunkedEncodingError
+from requests.exceptions import ChunkedEncodingError, ProxyError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.exceptions import (
@@ -472,6 +472,47 @@ class TestRESTClient:
assert mock_session.send.call_count == 5
+ @patch("tenacity.nap.time.sleep")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_send_request_retries_connection_error_then_succeeds(self, MockSession, mock_sleep) -> None:
+ # A proxy refusing/resetting the connection before a request is ever sent surfaces as
+ # requests.exceptions.ProxyError (a ConnectionError subclass); it's transient, so reissue
+ # the request rather than letting it skip this retry loop and fail the import.
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock(url="https://api.example.com/items")
+
+ ok = _make_response({"results": [{"id": 1}]})
+ mock_session.send.side_effect = [
+ ProxyError("Cannot connect to proxy."),
+ ok,
+ ]
+
+ client = RESTClient(base_url="https://api.example.com")
+ pages = list(client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator()))
+
+ assert pages == [[{"id": 1}]]
+ assert mock_session.send.call_count == 2
+
+ @patch("tenacity.nap.time.sleep")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_send_request_raises_retryable_after_persistent_connection_error(self, MockSession, mock_sleep) -> None:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock(url="https://api.example.com/items")
+
+ mock_session.send.side_effect = ProxyError("Cannot connect to proxy.")
+
+ client = RESTClient(base_url="https://api.example.com")
+ with pytest.raises(RESTClientRetryableError):
+ list(client.paginate(path="/items", paginator=SinglePagePaginator()))
+
+ assert mock_session.send.call_count == 5
+
@patch("tenacity.nap.time.sleep")
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"