: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(warehouse_sources): retry GA4 runReport connection drops inline (#94734)
posthog[bot]f22d63efc48c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.pyindex 23c5c48907ac..7ab9104179b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -209,6 +209,29 @@ def _run_report(for attempt in range(RUNREPORT_MAX_RETRIES + 1):try:response = session.post(url, json=body)+ except (+ requests.exceptions.ChunkedEncodingError,+ requests.exceptions.ConnectionError,+ requests.exceptions.ReadTimeout,+ ) as e:+ # The connection can drop before the response headers (ConnectionError / ReadTimeout) or+ # part-way through the streamed body (ChunkedEncodingError). Neither leaves a status code+ # for the 5xx handling below, and the shared adapter's DEFAULT_RETRY only retries GET,+ # HEAD and OPTIONS, so this POST arrives here with no retry behind it. runReport is a+ # read, so re-sending it is safe; back off inline like a 5xx, then let Temporal retry the+ # activity and the resumable source restart from the last saved chunk.+ if attempt == RUNREPORT_MAX_RETRIES:+ raise+ wait = RUNREPORT_BACKOFF_BASE_SECONDS * (2**attempt)+ logger.warning(+ "GA4 runReport connection dropped, backing off",+ property_id=pid,+ attempt=attempt,+ wait_seconds=wait,+ error=str(e),+ )+ time.sleep(wait)+ continueexcept RefreshError as e:# A transient 5xx from Google's OAuth token endpoint (notably a 502, which# google-auth doesn't count as retryable) is raised here while AuthorizedSessiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.pyindex 4488c3ced51f..8e06547421fa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py@@ -81,11 +81,28 @@ class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleA# retry the activity without paging it as a bug.## "Connection aborted"/"Connection reset by peer"/"Read timed out" are transport-level blips- # from `requests` raised directly by `session.post()` in `_run_report`, outside its own retry- # loop (which only handles `RefreshError` and HTTP-level failures). The resumable source picks- # up from the last saved chunk on the next Temporal retry, same as ClickHouse's source+ # from `requests` raised by `session.post()` in `_run_report`, which now backs off on them+ # inline, so they reach here only once that budget is spent. The resumable source picks up+ # from the last saved chunk on the next Temporal retry, same as ClickHouse's source# classifies this text.- return {"(retryable)", "Connection aborted", "Connection reset by peer", "Read timed out"}+ #+ # "Connection broken" is the urllib3 `ProtocolError` prefix for a body cut off mid-stream.+ # It carries the underlying reason (an incomplete read, an invalid chunk length, or a reset),+ # so only the reset variant matches the text above — match the prefix to cover them all.+ #+ # "Max retries exceeded with url" is the urllib3 wrapper around a connect that never+ # succeeded (a DNS failure, a refused connection, or a connect timeout). `Retry.increment`+ # tests for a connection error before it tests the method allowlist, so the shared adapter+ # retries this POST too and wraps the exhausted failure in that text, which carries none of+ # the messages above. Google Sheets, Langfuse, Notion and SigNoz match the same prefix.+ return {+ "(retryable)",+ "Connection aborted",+ "Connection broken",+ "Connection reset by peer",+ "Max retries exceeded with url",+ "Read timed out",+ }def get_schemas(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.pyindex 615ab3febc04..13e6a16960aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py@@ -485,6 +485,56 @@ def test_run_report_permanent_token_refresh_error_bubbles_without_retry(monkeypaassert session.post.call_count == 1+_CONNECTION_DROPS = [+ requests.exceptions.ChunkedEncodingError("Connection broken: IncompleteRead(5398 bytes read, 4842 more expected)"),+ requests.exceptions.ConnectionError(+ "('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))"+ ),+ requests.exceptions.ReadTimeout("Read timed out."),+]++[email protected]("error", _CONNECTION_DROPS)+def test_run_report_retries_connection_drops_then_succeeds(monkeypatch, error):+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)+ payload = {"rows": [], "rowCount": 0}+ session = mock.MagicMock()+ session.post.side_effect = [error, _fake_response(200, payload)]++ result = _run_report(+ session=session,+ property_id="123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert result == payload+ assert session.post.call_count == 2++[email protected]("error", _CONNECTION_DROPS)+def test_run_report_raises_connection_drop_after_exhausting_retries(monkeypatch, error):+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)+ session = mock.MagicMock()+ session.post.side_effect = error++ with pytest.raises(type(error)):+ _run_report(+ session=session,+ property_id="123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert session.post.call_count == RUNREPORT_MAX_RETRIES + 1++def test_run_report_retries_server_errors_then_succeeds(monkeypatch):monkeypatch.setattr(ga.time, "sleep", lambda _: None)payload = {"rows": [], "rowCount": 0}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.pyindex 9688402c70a5..1bf5853dbcb4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py@@ -290,19 +290,24 @@ def test_retryable_errors_cover_exhausted_quota_retries():assert any(pattern in error_msg for pattern in patterns)-def test_retryable_errors_cover_connection_reset():- # `session.post()` in `_run_report` can raise this transport-level `requests.ConnectionError`- # directly, outside its own retry loop (which only handles `RefreshError` and HTTP-level- # failures) — must stay classified as retryable so it doesn't page as a bug.- error_msg = "('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))"- patterns = GoogleAnalyticsSource().get_retryable_errors()- assert error_message_matches(error_msg, patterns)---def test_retryable_errors_cover_read_timeout():- # A read timeout talking to the Data API surfaces as a `requests.ConnectionError` from- # `session.post()` in `_run_report`, same as the connection-reset case above — must stay- # classified as retryable so it doesn't page as a bug.- error_msg = "HTTPSConnectionPool(host='analyticsdata.googleapis.com', port=443): Read timed out."+ "error_msg",+ [+ "('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))",+ "HTTPSConnectionPool(host='analyticsdata.googleapis.com', port=443): Read timed out.",+ "HTTPSConnectionPool(host='analyticsdata.googleapis.com', port=443): Max retries exceeded with url: "+ "/v1beta/properties/123456789:runReport (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection "+ "object at 0x7f00>: Failed to establish a new connection: [Errno -2] Name or service not known'))",+ "('Connection broken: IncompleteRead(5398 bytes read, 4842 more expected)', IncompleteRead(...))",+ "(\"Connection broken: InvalidChunkLength(got length b'', 0 bytes read)\", InvalidChunkLength(...))",+ "(\"Connection broken: ConnectionResetError(104, 'Connection reset by peer')\", ConnectionResetError(104))",+ ],+)+def test_retryable_errors_cover_connection_drops(error_msg):+ # `_run_report` backs off on these inline, so they reach the activity only once that budget is+ # spent. The next Temporal retry restarts from the last saved chunk, so they must stay+ # classified as retryable and not page as a bug. The third is the wrapper urllib3 puts around a+ # connect that never succeeded, once the shared adapter's own retries are exhausted, and the last+ # three are the truncated-body shapes `requests` raises as `ChunkedEncodingError`.patterns = GoogleAnalyticsSource().get_retryable_errors()assert error_message_matches(error_msg, patterns)