: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(data-imports): retry connection broken mid-stream in REST source (#65728)
Tom Owers0319f5fc0450
diff --git a/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py b/posthog/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 41fab6e53c3d..63c740c4cefd 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -7,7 +7,10 @@ from typing import Any, Optionalfrom requests import Request, Response, Sessionfrom requests.auth import AuthBase-from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError+from requests.exceptions import (+ ChunkedEncodingError,+ JSONDecodeError as RequestsJSONDecodeError,+)from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attemptfrom posthog.temporal.data_imports.sources.common.http import make_tracked_session@@ -168,7 +171,12 @@ class RESTClient:)def _send_request(self, request: Request, hooks: Hooks) -> tuple[Response, Any]:prepared = self.session.prepare_request(request)- response = self.session.send(prepared)+ # `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.+ try:+ response = self.session.send(prepared)+ except ChunkedEncodingError as e:+ raise RESTClientRetryableError(f"Connection broken while reading response: {e}") from eif response.status_code == 429 or response.status_code >= 500:raise RESTClientRetryableError(diff --git a/posthog/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/posthog/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 4305519573c1..9412a8ee10f0 100644--- a/posthog/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/posthog/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -6,6 +6,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom requests import Response+from requests.exceptions import ChunkedEncodingErrorfrom posthog.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuthfrom posthog.temporal.data_imports.sources.common.rest_source.exceptions import IgnoreResponseException@@ -305,6 +306,46 @@ class TestRESTClient:assert mock_session.send.call_count == 5+ @patch("tenacity.nap.time.sleep")+ @patch("posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")+ def test_send_request_retries_chunked_encoding_error_then_succeeds(self, MockSession, mock_sleep) -> None:+ # A connection dropped mid-stream surfaces from `send` as ChunkedEncodingError; it's+ # transient, so reissue the request rather than letting it fail the import.+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock()++ ok = _make_response({"results": [{"id": 1}]})+ mock_session.send.side_effect = [+ ChunkedEncodingError("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)"),+ 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("posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")+ def test_send_request_raises_retryable_after_persistent_chunked_encoding_error(+ self, MockSession, mock_sleep+ ) -> None:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock()++ mock_session.send.side_effect = ChunkedEncodingError(+ "Connection broken: InvalidChunkLength(got length b'', 0 bytes read)"+ )++ 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("posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")def test_send_request_respects_retry_after_header(self, MockSession, mock_sleep) -> None: