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-not-found in row-count query (#67911)

Tom Owers29b2310fb05a
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 5c1b53beda3d..1ae1fe17bbdb 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
@@ -16,7 +16,7 @@ import typing
import contextlib
import collections
import collections.abc
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import date, datetime
from decimal import Decimal
@@ -30,6 +30,7 @@ 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.table import RowIterator
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
@@ -615,9 +616,7 @@ def _get_rows_to_sync(
query = f"SELECT COUNT(*) FROM ({inner_query}) as t"
job_config = QueryJobConfig(query_parameters=query_parameters)
- job = client.query(query, job_config=job_config, project=table.project)
-
- rows = job.result(page_size=1)
+ rows = _query_result_with_job_retry(client, query, job_config=job_config, project=table.project, page_size=1)
row = next(rows, None)
if row and len(row) > 0 and row[0] is not None:
@@ -779,6 +778,8 @@ def _get_query(
_JOB_NOT_FOUND_MAX_ATTEMPTS = 4
_JOB_NOT_FOUND_RETRY_BACKOFF_SECONDS = 0.5
+_T = typing.TypeVar("_T")
+
def _is_transient_job_not_found(error: NotFound) -> bool:
"""True for BigQuery's transient "Job ... not found" lookup race.
@@ -792,6 +793,31 @@ def _is_transient_job_not_found(error: NotFound) -> bool:
return "Not found: Job" in message or "Job not found" in message
+def _with_job_not_found_retry(operation: Callable[[], _T]) -> _T:
+ """Run `operation`, retrying BigQuery's transient job-metadata race.
+
+ `client.query()` inserts a job and reads it straight back (its post-insert `get_job` reload, or
+ the reload `job.result()` does while awaiting completion), and that read can momentarily 404 for
+ the job it just created. The race clears within moments, so retry a few times. A genuine
+ `NotFound` (missing dataset/table) is not the race and surfaces immediately.
+ """
+ attempt = 0
+ while True:
+ try:
+ return operation()
+ 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 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)
+
+
def _run_destination_query_with_job_retry(
client: bigquery.Client,
query: str,
@@ -812,23 +838,35 @@ def _run_destination_query_with_job_retry(
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)
+
+ def _run() -> None:
+ job = client.query(query, job_config=job_config, project=project)
+ job.result()
+
+ _with_job_not_found_retry(_run)
+
+
+def _query_result_with_job_retry(
+ client: bigquery.Client,
+ query: str,
+ *,
+ job_config: QueryJobConfig,
+ project: str,
+ page_size: int | None = None,
+) -> RowIterator:
+ """Run a read-only query and return its row iterator, retrying the transient job-metadata race.
+
+ The read-path counterpart to `_run_destination_query_with_job_retry`: the same post-insert
+ `get_job` 404 can hit any `client.query()`, so a plain COUNT can fail with `NotFound: ... Not
+ found: Job ...` the same way the copy queries do. Re-running a read-only query just inserts a
+ fresh job, so retrying is safe; row fetching on the returned iterator stays lazy.
+ """
+
+ def _run() -> RowIterator:
+ job = client.query(query, job_config=job_config, project=project)
+ return job.result(page_size=page_size)
+
+ return _with_job_not_found_retry(_run)
class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquery.Client, Any]):
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 60c5d68e2d6b..01031c38f938 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
@@ -384,6 +384,37 @@ def test_bigquery_get_rows_to_sync_runs_count_query_when_filtered():
assert [p.name for p in job_config.query_parameters] == ["row_filter_0_0", "row_filter_0_1"]
[email protected]("products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.time.sleep")
+def test_bigquery_get_rows_to_sync_retries_transient_job_not_found(mock_sleep):
+ # The COUNT query hits BigQuery's job-metadata race; it must be retried and yield the real
+ # count, not swallowed into the catch-all that returns 0 and captures error-tracking noise.
+ table = mock.MagicMock(project="proj", dataset_id="ds", table_id="t")
+ table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]
+ client = mock.MagicMock()
+ job = mock.MagicMock()
+ job.result.side_effect = [NotFound("404 Not found: Job proj:US.job_abc123"), iter([[123]])]
+ client.query.return_value = job
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.capture_exception"
+ ) as mock_capture:
+ result = _get_rows_to_sync(
+ table=table,
+ client=client,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ logger=mock.MagicMock(),
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+
+ assert result == 123
+ assert client.query.call_count == 2
+ mock_sleep.assert_called_once()
+ mock_capture.assert_not_called()
+
+
def test_bigquery_get_query_in_filter_expands_to_one_param_per_value():
bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
bq_table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]