Skip to content

: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.

fix(bigquery): retry transient job-internal-error in primary-key probe (#66697)

Tom Owersa9b0371696f4
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.py
index a33a70ec86f5..903531b9d6cb 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
@@ -28,6 +28,7 @@ from google.auth.exceptions import RefreshError
from google.auth.transport.requests import AuthorizedSession
from google.cloud import bigquery, bigquery_storage
from google.cloud.bigquery.job import QueryJobConfig
+from google.cloud.bigquery.retry import DEFAULT_JOB_RETRY, _job_should_retry
from google.cloud.bigquery_storage_v1.services.big_query_read.transports.grpc import BigQueryReadGrpcTransport
from google.oauth2 import service_account
from structlog.types import FilteringBoundLogger
@@ -106,6 +107,24 @@ BIGQUERY_DATASET_NOT_FOUND_ERROR = (
"region in your source configuration if it isn't in the US."
)
+# BigQuery occasionally fails a query job with a transient `jobInternalError`, surfaced from the
+# `jobs.getQueryResults` REST call as a 400 BadRequest whose message ends "The job encountered an
+# error during execution. Retrying the job may solve the problem.". The client's default job-retry
+# predicate retries backendError / internalError / rateLimitExceeded but not this reason, so it
+# escapes `QueryJob.result()` and crashes the import. BigQuery itself recommends retrying, so re-run
+# the job in place — matched on its stable retry-recommendation wording, not the volatile job id/URL.
+_BIGQUERY_JOB_RETRY_RECOMMENDED = "Retrying the job may solve the problem"
+
+
+def _query_job_should_retry(exc: Exception) -> bool:
+ # Defer to the library's own default predicate for the reasons it already covers; importing it
+ # directly (rather than reading the private `Retry._predicate`) means a library rename fails
+ # loudly at import instead of silently dropping that default coverage.
+ return _BIGQUERY_JOB_RETRY_RECOMMENDED in str(exc) or _job_should_retry(exc)
+
+
+BIGQUERY_QUERY_JOB_RETRY = DEFAULT_JOB_RETRY.with_predicate(_query_job_should_retry)
+
class BigQueryDatasetNotFoundError(Exception):
"""Raised when schema discovery queries a dataset/table that doesn't exist in the queried region.
@@ -469,7 +488,7 @@ def _get_primary_keys_for_table(table: bigquery.Table, client: bigquery.Client)
job = client.query(query, job_config=job_config, project=table.project)
primary_keys = []
- for row in job.result():
+ for row in job.result(job_retry=BIGQUERY_QUERY_JOB_RETRY):
field_name = row["column_name"].removeprefix(f"{table.table_id}.")
if field_name not in existing_fields:
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.py
index 34726b4264c2..2f10ccd7c3c9 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
@@ -12,12 +12,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery import bigquery as bq_module
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (
BIGQUERY_DATASET_NOT_FOUND_ERROR,
+ BIGQUERY_QUERY_JOB_RETRY,
BIGQUERY_TOKEN_RESPONSE_ERROR,
BigQueryCredentialsRejectedError,
BigQueryDatasetNotFoundError,
BigQueryImplementation,
BigQueryTokenRefreshError,
_bq_select_clause,
+ _get_primary_keys_for_table,
_get_query,
_get_rows_to_sync,
_has_duplicate_primary_keys,
@@ -939,6 +941,53 @@ def test_has_duplicate_primary_keys_captures_unexpected_errors():
mock_capture.assert_called_once()
+ "exc",
+ [
+ # The transient `jobInternalError` from `jobs.getQueryResults` (volatile project/job id redacted).
+ BadRequest(
+ "GET https://bigquery.googleapis.com/bigquery/v2/projects/<redacted>/queries/<redacted>"
+ "?maxResults=0&location=US&prettyPrint=false: The job encountered an error during execution. "
+ "Retrying the job may solve the problem."
+ ),
+ # The library default's own retryable reasons must still be honoured.
+ BadRequest("query failed", errors=[{"reason": "backendError", "message": "internal error"}]),
+ BadRequest("query failed", errors=[{"reason": "rateLimitExceeded", "message": "slow down"}]),
+ ],
+)
+def test_bigquery_query_job_retry_retries_transient_job_errors(exc):
+ assert BIGQUERY_QUERY_JOB_RETRY._predicate(exc) is True
+
+
+ "exc",
+ [
+ # A genuinely malformed query is deterministic — retrying never helps, so it must surface.
+ BadRequest("Syntax error: Unexpected keyword SELECT"),
+ BadRequest("query failed", errors=[{"reason": "invalidQuery", "message": "bad SQL"}]),
+ ],
+)
+def test_bigquery_query_job_retry_does_not_retry_deterministic_errors(exc):
+ assert BIGQUERY_QUERY_JOB_RETRY._predicate(exc) is False
+
+
+def test_bigquery_get_primary_keys_for_table_passes_job_retry():
+ """The primary-key probe must run under the extended job retry so a transient BigQuery job
+ error is re-tried in place instead of crashing the import."""
+ table = mock.MagicMock()
+ table.schema = []
+ table.dataset_id = "dataset"
+ table.table_id = "table"
+ table.project = "project"
+
+ client = mock.MagicMock()
+ client.query.return_value.result.return_value = []
+
+ _get_primary_keys_for_table(table, client)
+
+ assert client.query.return_value.result.call_args.kwargs["job_retry"] is BIGQUERY_QUERY_JOB_RETRY
+
+
@pytest.mark.parametrize(
"location",
["US", "EU", "asia-northeast1"],