: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(bigquery): retry a transient 502/503/504 during OAuth token refresh (#96147)
Tom Owers16fc43f2e02a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.pyindex 3c34b0cf85f0..6e2203a2115a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py@@ -35,7 +35,10 @@ from google.api_core.exceptions import ()from google.api_core.retry import Retry, if_exception_typefrom google.auth.exceptions import RefreshError-from google.auth.transport.requests import AuthorizedSession+from google.auth.transport.requests import (+ AuthorizedSession,+ Request as GoogleAuthRequest,+)from google.cloud import bigquery, bigquery_storagefrom google.cloud.bigquery.job import QueryJobConfigfrom google.cloud.bigquery.retry import DEFAULT_JOB_RETRY, _job_should_retry@@ -60,7 +63,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.grpfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (DEFAULT_RETRY,TrackedHTTPAdapter,+ make_tracked_session,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_openfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (ColumnTypeCategory,@@ -290,6 +295,23 @@ BIGQUERY_CREATE_READ_SESSION_RETRY = Retry()+# `AuthorizedSession` builds its own internal session for refreshing the service-account OAuth+# access token, and its default adapter only retries connection errors, not HTTP error responses.+# Google's OAuth token endpoint can fail the refresh POST with a transient 502/503/504 (a Google-side+# infrastructure blip on accounts.google.com / oauth2.googleapis.com — the same condition already+# tolerated as a non-fatal cleanup hiccup in `build_pipeline`'s `finally` block), which otherwise+# escapes every call site as an opaque `RefreshError` and crashes the whole import activity. POST is+# normally excluded from urllib3's retryable methods since it's often non-idempotent, but a failed+# token request mints no token, so retrying it here duplicates no side effect.+BIGQUERY_TOKEN_REFRESH_RETRY = BoundedRetry(+ total=3,+ backoff_factor=0.5,+ status_forcelist=(502, 503, 504),+ allowed_methods=frozenset(["POST"]),+ raise_on_status=False,+)++class BigQueryDatasetNotFoundError(Exception):"""Raised when schema discovery queries a dataset/table that doesn't exist in the queried region.@@ -413,10 +435,15 @@ def bigquery_client(},scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],)+ # See `BIGQUERY_TOKEN_REFRESH_RETRY`: hand `AuthorizedSession` our own retrying session for+ # credential refresh, instead of the default one whose adapter never retries a 502/503/504.+ # `capture=False` keeps the OAuth response (it carries the minted bearer token) out of HTTP+ # sample capture.+ auth_request_session = make_tracked_session(retry=BIGQUERY_TOKEN_REFRESH_RETRY, capture=False)# AuthorizedSession is a `requests.Session` subclass that injects the OAuth2# bearer token. Mount our TrackedHTTPAdapter on it so every BigQuery REST# call is logged and metered alongside the other warehouse sources.- authed_session = AuthorizedSession(credentials)+ authed_session = AuthorizedSession(credentials, auth_request=GoogleAuthRequest(auth_request_session))tracked_adapter = TrackedHTTPAdapter(max_retries=DEFAULT_RETRY)authed_session.mount("https://", tracked_adapter)authed_session.mount("http://", tracked_adapter)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.pyindex a8a8194bca1e..5a796b9709bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py@@ -1,4 +1,5 @@from types import SimpleNamespace+from typing import castimport pytestfrom freezegun import freeze_time@@ -15,7 +16,9 @@ from google.api_core.exceptions import (PermissionDenied,ServiceUnavailable,)+from google.auth.credentials import Credentials as GoogleAuthCredentialsfrom google.auth.exceptions import RefreshError+from requests.adapters import HTTPAdapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.bigquery import bigquery as bq_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (@@ -28,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bBIGQUERY_QUERY_CREATE_RETRY,BIGQUERY_QUERY_JOB_RETRY,BIGQUERY_READ_ROWS_RETRY,+ BIGQUERY_TOKEN_REFRESH_RETRY,BIGQUERY_TOKEN_RESPONSE_ERROR,BIGQUERY_VALIDATION_GENERIC_ERROR,BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR,@@ -1946,6 +1950,34 @@ def test_bigquery_storage_read_client_disables_grpc_message_size_limit():assert options["grpc.max_send_message_length"] == -1+def test_bigquery_client_retries_transient_token_refresh_failures():+ """Regression: `AuthorizedSession`'s default token-refresh session only retries connection+ errors, not HTTP error responses, so a transient 502/503/504 from Google's OAuth token+ endpoint escaped every `bigquery_client` call site as an opaque `RefreshError` instead of+ being retried. `bigquery_client` must hand `AuthorizedSession` an `auth_request` built from+ a session carrying `BIGQUERY_TOKEN_REFRESH_RETRY`."""+ with mock.patch.object(+ bq_module.service_account.Credentials,+ "from_service_account_info",+ return_value=mock.Mock(spec=GoogleAuthCredentials),+ ):+ with bq_module.bigquery_client(+ project_id="project-id",+ location=None,+ private_key="private-key",+ private_key_id="private-key-id",+ client_email="client-email",+ token_uri="token-uri",+ ) as client:+ auth_request_session = client._http._auth_request.session+ adapter = cast(HTTPAdapter, auth_request_session.get_adapter("https://oauth2.googleapis.com"))+ retry = adapter.max_retries++ assert retry is BIGQUERY_TOKEN_REFRESH_RETRY+ assert retry.allowed_methods and "POST" in retry.allowed_methods+ assert retry.status_forcelist and {502, 503, 504} <= set(retry.status_forcelist)++def test_bigquery_billing_not_enabled_is_non_retryable():# A `billingNotEnabled` Forbidden 403 is a customer config issue — retrying never helps.# Representative message from a real failed job (the `reason: billingNotEnabled` 403 raised