: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(google_search_console): retry transient 5xx server errors inline (#66518)
Tom Owers586cce4cbe83
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.pyindex 81c6157a742b..c2e7f646561f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -233,6 +233,16 @@ def _is_daily_quota_error(response: requests.Response) -> bool:return any(e.get("reason") in DAILY_QUOTA_REASONS for e in errors)+def _is_server_error(response: requests.Response) -> bool:+ """Whether a failed response is a transient Google-side 5xx worth retrying.++ Search Analytics intermittently returns 500/503 for a property even on a well-formed+ request. These clear on their own, so retry inline like a quota error rather than+ failing the sync on the first blip.+ """+ return response.status_code >= 500++def _quota_backoff_seconds(response: requests.Response, attempt: int) -> float:"""Seconds to wait before retrying a quota error: honor `Retry-After`, else exponential."""retry_after = response.headers.get("Retry-After")@@ -283,18 +293,30 @@ def _query_search_analytics(f"Search Analytics daily quota for '{site_url}' exhausted; retrying at the activity level")- if not _is_quota_error(response):- # Permission / other errors are fatal — let the HTTPError bubble up so- # `get_non_retryable_errors` can match "403 Client Error" / "401 Client Error".+ # Quota (403 usageLimits / 429) and transient Google-side 5xx both clear on their own,+ # so retry inline with backoff. Permission / other client errors are fatal — let the+ # HTTPError bubble up so `get_non_retryable_errors` can match "403 Client Error" /+ # "401 Client Error".+ if not _is_quota_error(response) and not _is_server_error(response):response.raise_for_status()if attempt == QUOTA_MAX_RETRIES:+ if _is_server_error(response):+ # Still 5xx after the inline budget — surface the real HTTPError so Temporal+ # retries the activity (resuming from the last saved date).+ response.raise_for_status()raise GoogleSearchConsoleQuotaExceededError(f"Search Analytics quota for '{site_url}' still exhausted after {QUOTA_MAX_RETRIES} retries")wait = _quota_backoff_seconds(response, attempt)- logger.warning("GSC quota exceeded, backing off", site_url=site_url, attempt=attempt, wait_seconds=wait)+ logger.warning(+ "GSC request failed, backing off",+ site_url=site_url,+ status_code=response.status_code,+ attempt=attempt,+ wait_seconds=wait,+ )time.sleep(wait)# Unreachable: the loop either returns, raises for status, or raises the quota error.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.pyindex 9e4bc337e845..466d3042fc4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea_initial_start_date,_is_daily_quota_error,_is_quota_error,+ _is_server_error,_iter_dates,_query_search_analytics,_quota_backoff_seconds,@@ -350,6 +351,23 @@ def test_is_daily_quota_error(response, expected):assert _is_daily_quota_error(response) is expected+ "response,expected",+ [+ (_fake_response(500), True),+ (_fake_response(502), True),+ (_fake_response(503), True),+ (_fake_response(504), True),+ (_fake_response(429), False),+ (_fake_response(403, _QUOTA_BODY), False),+ (_fake_response(403, _PERMISSION_BODY), False),+ (_fake_response(200, {"rows": []}), False),+ ],+)+def test_is_server_error(response, expected):+ assert _is_server_error(response) is expected++def test_quota_backoff_prefers_retry_after_header():resp = _fake_response(403, _QUOTA_BODY, headers={"Retry-After": "30"})assert _quota_backoff_seconds(resp, attempt=0) == 30.0@@ -419,6 +437,38 @@ def test_query_permission_error_is_not_retried(monkeypatch):assert session.post.call_count == 1+def test_query_retries_server_error_then_succeeds(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.side_effect = [+ _fake_response(500),+ _fake_response(503),+ _fake_response(200, {"rows": [{"keys": ["2026-04-15"], "clicks": 1}]}),+ ]++ rows = _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ assert rows == [{"keys": ["2026-04-15"], "clicks": 1}]+ assert session.post.call_count == 3+++def test_query_server_error_bubbles_http_error_after_max_retries(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.return_value = _fake_response(500)++ # A persistent 5xx exhausts the inline budget and surfaces the real HTTPError (retryable+ # at the activity level), not the quota error.+ with pytest.raises(requests.HTTPError):+ _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ assert session.post.call_count == QUOTA_MAX_RETRIES + 1++def test_throttle_spaces_requests_per_site(monkeypatch):gsc._next_request_at.clear()fake_now = {"t": 100.0}