: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 transient job-not-found in temp-table copy query (#67709)
Tom Owers24fb1b0e87d0
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 28bcbb8f1542..5c1b53beda3d 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@@ -11,6 +11,7 @@ credentials.from __future__ import annotationsimport math+import timeimport typingimport contextlibimport collections@@ -770,6 +771,66 @@ def _get_query(return f"SELECT {select_clause} FROM {table_ref}", query_parameters+# BigQuery's job-metadata store is eventually consistent: `client.query()` inserts a job and then+# reads it straight back. When the auto-retried `jobs.insert` loses its first response, the retry+# hits a 409 whose recovery `get_job` momentarily 404s for the job it just created (surfacing as+# `NotFound: ... Not found: Job <project>:<id>`). The race clears within moments, so retry a few+# times before surfacing the error.+_JOB_NOT_FOUND_MAX_ATTEMPTS = 4+_JOB_NOT_FOUND_RETRY_BACKOFF_SECONDS = 0.5+++def _is_transient_job_not_found(error: NotFound) -> bool:+ """True for BigQuery's transient "Job ... not found" lookup race.++ Must be distinguished from a genuine `NotFound` — a missing dataset/table, or a dataset absent+ from the queried region — that no retry can fix (and which is deliberately treated as+ non-retryable elsewhere), so match only the job-lookup wording, never "Not found: Dataset" /+ "Not found: Table" / "was not found in location".+ """+ message = str(error)+ return "Not found: Job" in message or "Job not found" in message+++def _run_destination_query_with_job_retry(+ client: bigquery.Client,+ query: str,+ *,+ destination_table: bigquery.Table,+ query_parameters: list[bigquery.ScalarQueryParameter],+ project: str,+) -> None:+ """Run a copy-into-temp-table query, retrying BigQuery's transient job-metadata race.++ The 404 is raised from inside `client.query()` (its post-insert `get_job` reload), so recovering+ means creating a fresh job — retrying `job.result()` alone can't. Re-running writes the same+ temp table, so `WRITE_TRUNCATE` keeps a retry — or a stale table left behind by a lost first+ attempt — idempotent instead of tripping the default empty-table check.+ """+ job_config = QueryJobConfig(+ destination=destination_table,+ query_parameters=query_parameters,+ write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,+ )+ attempt = 0+ while True:+ try:+ job = client.query(query, job_config=job_config, project=project)+ _ = job.result()+ return+ except NotFound as e:+ attempt += 1+ if not _is_transient_job_not_found(e) or attempt >= _JOB_NOT_FOUND_MAX_ATTEMPTS:+ raise+ structlog.get_logger().warning(+ "Retrying BigQuery copy query after transient job-not-found (attempt %s/%s): %s",+ attempt,+ _JOB_NOT_FOUND_MAX_ATTEMPTS,+ e,+ )+ time.sleep(_JOB_NOT_FOUND_RETRY_BACKOFF_SECONDS * attempt)++class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquery.Client, Any]):"""BigQuery driver implementation paired with `BigQuerySource`.@@ -1142,9 +1203,13 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu)destination_table = bigquery.Table(bq_destination_table_id)- job_config = QueryJobConfig(destination=destination_table, query_parameters=query_parameters)- job = bq_client.query(query, job_config=job_config, project=bq_table.project)- _ = job.result()+ _run_destination_query_with_job_retry(+ bq_client,+ query,+ destination_table=destination_table,+ query_parameters=query_parameters,+ project=bq_table.project,+ )bq_table = bq_client.get_table(destination_table)@@ -1165,9 +1230,13 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu)destination_table = bigquery.Table(bq_destination_table_id)- job_config = QueryJobConfig(destination=destination_table, query_parameters=query_parameters)- job = bq_client.query(query, job_config=job_config, project=bq_table.project)- _ = job.result()+ _run_destination_query_with_job_retry(+ bq_client,+ query,+ destination_table=destination_table,+ query_parameters=query_parameters,+ project=bq_table.project,+ )bq_table = bq_client.get_table(destination_table)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 1564440939bd..cd307cd20467 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@@ -25,11 +25,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b_get_query,_get_rows_to_sync,_has_duplicate_primary_keys,+ _is_transient_job_not_found,_resolve_dataset_id,_resolve_dataset_project_id,_resolve_project_id,_resolve_query_project,_resolve_region,+ _run_destination_query_with_job_retry,delete_all_temp_destination_tables,validate_bigquery_credentials,)@@ -1021,6 +1023,88 @@ def test_bigquery_get_primary_keys_for_table_passes_job_retry():assert client.query.return_value.result.call_args.kwargs["job_retry"] is BIGQUERY_QUERY_JOB_RETRY+ "message",+ [+ "404 GET https://bigquery.googleapis.com/.../jobs/abc?projection=full: Not found: Job prj:US.abc",+ "Not found: Job prj:EU.job_xyz",+ "Job not found: job_xyz",+ ],+)+def test_is_transient_job_not_found_matches_job_race(message):+ assert _is_transient_job_not_found(NotFound(message)) is True+++ "message",+ [+ # A missing dataset/table (or a dataset absent from the queried region) is genuinely+ # non-retryable and must not be mistaken for the job race, even though the raw dataset 404+ # can carry a trailing "Job ID:".+ "404 Not found: Dataset prj:ds was not found in location US Job ID: b3abc342-16a7",+ "404 Not found: Table prj:ds.tbl",+ ],+)+def test_is_transient_job_not_found_ignores_other_not_found(message):+ assert _is_transient_job_not_found(NotFound(message)) is False++[email protected]("products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.time.sleep")+def test_run_destination_query_retries_transient_job_not_found(mock_sleep):+ """The copy-into-temp-table query is where the production sync crashed on BigQuery's job-metadata+ race; a transient job-not-found must be retried with a fresh job instead of aborting the import."""+ client = mock.MagicMock()+ ok_job = mock.MagicMock()+ client.query.side_effect = [NotFound("404 Not found: Job prj:US.abc"), ok_job]++ _run_destination_query_with_job_retry(+ client, "SELECT 1", destination_table=mock.MagicMock(), query_parameters=[], project="prj"+ )++ assert client.query.call_count == 2+ ok_job.result.assert_called_once()+ mock_sleep.assert_called_once()+ # WRITE_TRUNCATE keeps the re-run idempotent against a temp table a lost first attempt populated.+ assert client.query.call_args.kwargs["job_config"].write_disposition == "WRITE_TRUNCATE"++[email protected]("products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.time.sleep")+def test_run_destination_query_does_not_retry_genuine_not_found(mock_sleep):+ """A genuine `NotFound` (missing dataset/table) is not the job race, so it surfaces immediately+ rather than looping until the attempt cap."""+ client = mock.MagicMock()+ client.query.side_effect = NotFound("404 Not found: Table prj:ds.tbl")++ with pytest.raises(NotFound):+ _run_destination_query_with_job_retry(+ client, "SELECT 1", destination_table=mock.MagicMock(), query_parameters=[], project="prj"+ )++ assert client.query.call_count == 1+ mock_sleep.assert_not_called()+++ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery._JOB_NOT_FOUND_MAX_ATTEMPTS",+ 4,+)[email protected]("products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.time.sleep")+def test_run_destination_query_gives_up_after_max_attempts(mock_sleep):+ """The race almost always clears within moments, but a persistent job-not-found must still stop+ at the attempt cap and surface the error instead of retrying forever."""+ client = mock.MagicMock()+ client.query.side_effect = [NotFound("404 Not found: Job prj:US.abc") for _ in range(4)]++ with pytest.raises(NotFound):+ _run_destination_query_with_job_retry(+ client, "SELECT 1", destination_table=mock.MagicMock(), query_parameters=[], project="prj"+ )++ assert client.query.call_count == 4+ # No back-off after the final, failed attempt.+ assert mock_sleep.call_count == 3++@pytest.mark.parametrize("location",["US", "EU", "asia-northeast1"],