: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 per-second rate quotas in place (#68340)
Tom Owersf34afa5f0dc8
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 6afe4348169c..56dda3078446 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@@ -135,11 +135,31 @@ BIGQUERY_INVALID_IDENTIFIER_ERROR = (_BIGQUERY_JOB_RETRY_RECOMMENDED = "Retrying the job may solve the problem"+def _is_transient_rate_quota_exceeded(exc: Exception) -> bool:+ """True for BigQuery's per-second rate quotas, which are transient and recover on their own.++ BigQuery caps some operations by a per-second rate (e.g. "Quota exceeded: Your project ...+ exceeded quota for tabledata.list bytes per second per project."), surfaced from+ `jobs.getQueryResults` as a `Forbidden` (403, reason `quotaExceeded`). The quota window resets+ each second, so a query that trips one recovers within moments — but the library's own retry+ predicates only cover `rateLimitExceeded` / `backendError` / `internalError`, not+ `quotaExceeded`, so neither the API-call retry nor the job retry waits it out and the read/copy+ query crashes the whole sync. This is distinct from the administrator-set "Custom quota+ exceeded" daily cost cap (kept non-retryable in `get_non_retryable_errors`), which resets only+ on Google's daily schedule and must not be retried in place. Matched on the stable "per second"+ wording rather than the volatile project/quota id.+ """+ message = str(exc)+ return "per second" in message and "Custom quota exceeded" not in message++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)+ return (+ _BIGQUERY_JOB_RETRY_RECOMMENDED in str(exc) or _is_transient_rate_quota_exceeded(exc) or _job_should_retry(exc)+ )BIGQUERY_QUERY_JOB_RETRY = DEFAULT_JOB_RETRY.with_predicate(_query_job_should_retry)@@ -900,7 +920,7 @@ def _run_destination_query_with_job_retry(def _run() -> None:job = client.query(query, job_config=job_config, project=project)- job.result()+ job.result(job_retry=BIGQUERY_QUERY_JOB_RETRY)_with_job_not_found_retry(_run)@@ -923,7 +943,7 @@ def _query_result_with_job_retry(def _run() -> RowIterator:job = client.query(query, job_config=job_config, project=project)- return job.result(page_size=page_size)+ return job.result(page_size=page_size, job_retry=BIGQUERY_QUERY_JOB_RETRY)return _with_job_not_found_retry(_run)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 3c569f965c84..4266191c0195 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@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b_get_rows_to_sync,_has_duplicate_primary_keys,_is_transient_job_not_found,+ _query_result_with_job_retry,_resolve_dataset_id,_resolve_dataset_project_id,_resolve_project_id,@@ -1131,6 +1132,15 @@ def test_has_duplicate_primary_keys_captures_unexpected_errors():# 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"}]),+ # A per-second rate quota (reason `quotaExceeded`, which the library's own predicates don't+ # retry) is transient — the quota window resets each second — so it must be retried in place+ # rather than crashing the sync. Volatile project/job ids redacted.+ Forbidden(+ "GET https://bigquery.googleapis.com/bigquery/v2/projects/<redacted>/queries/<redacted>"+ "?maxResults=0&location=US&prettyPrint=false: Quota exceeded: Your project:<redacted> "+ "exceeded quota for tabledata.list bytes per second per project. For more information, "+ "see https://cloud.google.com/bigquery/docs/troubleshoot-quotas"+ ),],)def test_bigquery_query_job_retry_retries_transient_job_errors(exc):@@ -1143,6 +1153,12 @@ def test_bigquery_query_job_retry_retries_transient_job_errors(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"}]),+ # The administrator-set "Custom quota exceeded" daily cost cap resets only on Google's daily+ # schedule — the per-second rate-quota retry must not catch it and hammer the endpoint.+ Forbidden(+ "Custom quota exceeded: Your usage exceeded the custom quota for QueryUsagePerDay, "+ "which is set by your administrator.; reason: quotaExceeded"+ ),],)def test_bigquery_query_job_retry_does_not_retry_deterministic_errors(exc):@@ -1191,6 +1207,29 @@ 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+def test_run_destination_query_passes_job_retry():+ """The copy-into-temp-table query — where the production sync crashed on a transient per-second+ rate quota — must run under the extended job retry so it waits the rate limit out in place+ instead of aborting the import."""+ client = mock.MagicMock()++ _run_destination_query_with_job_retry(+ client, "SELECT 1", destination_table=mock.MagicMock(), query_parameters=[], project="prj"+ )++ assert client.query.return_value.result.call_args.kwargs["job_retry"] is BIGQUERY_QUERY_JOB_RETRY+++def test_query_result_passes_job_retry():+ """The read/count query must likewise run under the extended job retry so a transient per-second+ rate quota is retried in place rather than surfacing."""+ client = mock.MagicMock()++ _query_result_with_job_retry(client, "SELECT COUNT(*)", job_config=mock.MagicMock(), project="prj")++ assert client.query.return_value.result.call_args.kwargs["job_retry"] is BIGQUERY_QUERY_JOB_RETRY++@pytest.mark.parametrize("message",[