: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 token-refresh 502 inline (#71716)
Tom Owersc95344802f0a
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 ee239fff0872..dac1afa00713 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@@ -11,6 +11,7 @@ from django.db import OperationalError, close_old_connectionsimport requestsimport structlog+from google.auth.exceptions import RefreshErrorfrom google.auth.transport.requests import AuthorizedSessionfrom google.oauth2.credentials import Credentials as OAuthCredentials@@ -272,6 +273,24 @@ def _is_server_error(response: requests.Response) -> bool:return response.status_code >= 500+def _is_transient_refresh_error(error: RefreshError) -> bool:+ """Whether an OAuth token-refresh failure is a transient server-side blip worth retrying.++ `AuthorizedSession` refreshes the access token before the Search Analytics request, so a+ failing token endpoint raises `RefreshError` from `session.post` before any response object+ exists — the 5xx handling on the response never sees it. google-auth flags 500/503/504/408/429+ (and JSON `server_error`/`temporarily_unavailable`) as retryable, but omits 502 from its+ retryable status codes, so a Bad Gateway from the token endpoint surfaces as a+ `RefreshError(retryable=False)` carrying an HTML error page. Treat those as transient too.+ Permanent failures (`invalid_grant`, `invalid_scope`) stay non-transient so they bubble up to+ `get_non_retryable_errors`.+ """+ if getattr(error, "retryable", False):+ return True+ message = str(error)+ return "502" in message and "Server Error" in message++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")@@ -323,6 +342,22 @@ def _query_search_analytics()time.sleep(wait)continue+ except 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 AuthorizedSession refreshes the access+ # token. It clears on its own, so retry inline like a 5xx; permanent failures+ # (invalid_grant / invalid_scope) bubble up so get_non_retryable_errors can stop the sync.+ if not _is_transient_refresh_error(e) or attempt == QUOTA_MAX_RETRIES:+ raise+ wait = QUOTA_BACKOFF_BASE_SECONDS * (2**attempt)+ logger.warning(+ "GSC token refresh transient error, backing off",+ site_url=site_url,+ attempt=attempt,+ wait_seconds=wait,+ )+ time.sleep(wait)+ continueif response.ok:return response.json().get("rows", [])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 4894e76494c4..4419f0d01b9f 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@@ -6,6 +6,7 @@ from unittest import mockfrom django.db import OperationalErrorimport requests+from google.auth.exceptions import RefreshErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (GoogleSearchConsoleSourceConfig,@@ -25,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_sea_is_daily_quota_error,_is_quota_error,_is_server_error,+ _is_transient_refresh_error,_iter_dates,_query_search_analytics,_quota_backoff_seconds,@@ -411,6 +413,30 @@ def test_is_server_error(response, expected):assert _is_server_error(response) is expected+# A Bad Gateway from Google's OAuth token endpoint arrives as an HTML page, not JSON.+_HTML_502_BODY = (+ "<!DOCTYPE html>\n<html lang=en>\n <title>Error 502 (Server Error)!!1</title>\n"+ " <p><b>502.</b> That's an error.\n <p>The server encountered a temporary error "+ "and could not complete your request."+)+++ "error,expected",+ [+ # 502 gateway page: google-auth omits 502 from its retryable status codes, but it's transient.+ (RefreshError(_HTML_502_BODY), True),+ # google-auth flags 500/503/504/408/429 (and JSON server errors) retryable itself.+ (RefreshError("temporarily_unavailable: try again later", retryable=True), True),+ # Revoked/expired refresh token — permanent, must not be retried inline.+ (RefreshError("invalid_grant: Token has been expired or revoked."), False),+ (RefreshError("invalid_scope: Bad Request"), False),+ ],+)+def test_is_transient_refresh_error(error, expected):+ assert _is_transient_refresh_error(error) 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@@ -544,6 +570,38 @@ def test_query_connection_error_bubbles_after_max_retries(monkeypatch):assert session.post.call_count == QUOTA_MAX_RETRIES + 1+def test_query_retries_transient_token_refresh_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 = [+ # AuthorizedSession raises RefreshError from post() when the token endpoint 502s mid-refresh.+ RefreshError(_HTML_502_BODY),+ _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 == 2+++def test_query_permanent_token_refresh_error_bubbles_without_retry(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.side_effect = RefreshError("invalid_grant: Token has been expired or revoked.")++ # A revoked/expired refresh token never recovers, so it must bubble on the first attempt+ # (matching get_non_retryable_errors' "invalid_grant") rather than burning the inline budget.+ with pytest.raises(RefreshError, match="invalid_grant"):+ _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ assert session.post.call_count == 1++def test_throttle_spaces_requests_per_site(monkeypatch):gsc._next_request_at.clear()fake_now = {"t": 100.0}