: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): surface a clear error for an invalid dataset or project ID (#66945)
Tom Owers537a360b2e58
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 903531b9d6cb..f09ce773ee87 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@@ -76,10 +76,12 @@ from products.warehouse_sources.backend.types import IncrementalFieldType, Parti__all__ = ["BIGQUERY_DATASET_NOT_FOUND_ERROR",+ "BIGQUERY_INVALID_IDENTIFIER_ERROR","BIGQUERY_TOKEN_RESPONSE_ERROR","BigQueryCredentialsRejectedError","BigQueryDatasetNotFoundError","BigQueryImplementation",+ "BigQueryInvalidIdentifierError","BigQueryTokenRefreshError","bigquery_client","bigquery_storage_read_client",@@ -107,6 +109,18 @@ BIGQUERY_DATASET_NOT_FOUND_ERROR = ("region in your source configuration if it isn't in the US.")+# User-facing message for a syntactically invalid project/dataset ID (e.g. a value carrying+# parentheses or other characters BigQuery forbids). Raised below and matched in+# `BigQuerySource.get_non_retryable_errors`, so it must stay free of volatile data (the offending id).+# Kept generic across project vs dataset: the raw 400 can be either ("Invalid project ID" /+# "Invalid dataset ID"), and the two have different allowed character sets (dataset IDs allow+# underscores but not dashes; project IDs allow dashes but not underscores), so naming a specific+# allowlist or only one field would mislead half the cases.+BIGQUERY_INVALID_IDENTIFIER_ERROR = (+ "Your BigQuery Project ID or Dataset ID contains characters BigQuery doesn't allow. "+ "Please check the Project ID and Dataset ID in your source configuration."+)+# 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@@ -136,6 +150,17 @@ class BigQueryDatasetNotFoundError(Exception):"""+class BigQueryInvalidIdentifierError(Exception):+ """Raised when schema discovery is given a syntactically invalid project/dataset ID.++ `client.query()` raises a `google.api_core.exceptions.BadRequest` whose `str()` is a raw+ `400 Invalid dataset ID "..."` / `Invalid project ID "..."` carrying the offending value plus+ job internals (location, job id) — none of which the user can act on. A value like `(default)`+ fails because parentheses aren't allowed. We re-raise it with actionable wording instead of+ leaking the raw 400 to the create/validate response. Deterministic config error — non-retryable.+ """++class BigQueryTokenRefreshError(Exception):"""Raised when the service-account OAuth token endpoint returns a non-JSON-object 200.@@ -805,6 +830,16 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu"BigQuery dataset '%s' not found during schema discovery: %s", config.dataset_id, e)raise BigQueryDatasetNotFoundError(BIGQUERY_DATASET_NOT_FOUND_ERROR) from e+ except BadRequest as e:+ # A bad project/dataset ID surfaces as "400 Invalid project ID ..." / "Invalid dataset ID+ # ...". Convert it to an actionable message; anything else is a genuine BadRequest we leave+ # to propagate (including the transient job-internal-error the query retry predicate covers).+ if "Invalid dataset ID" not in str(e) and "Invalid project ID" not in str(e):+ raise+ structlog.get_logger().warning(+ "BigQuery rejected an invalid project/dataset ID during schema discovery: %s", e+ )+ raise BigQueryInvalidIdentifierError(BIGQUERY_INVALID_IDENTIFIER_ERROR) from eexcept TypeError as e:# See `BigQueryTokenRefreshError`: google-auth raises an opaque# `TypeError: string indices must be integers` when the OAuth token endpointdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.pyindex a146e25c3dad..af2e8a29dc58 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py@@ -13,6 +13,7 @@ from posthog.schema import (from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (BIGQUERY_DATASET_NOT_FOUND_ERROR,+ BIGQUERY_INVALID_IDENTIFIER_ERROR,BIGQUERY_TOKEN_RESPONSE_ERROR,BigQueryImplementation,build_destination_table_prefix,@@ -106,6 +107,14 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):# carrying this exact wording (so the create/validate path shows it instead of the raw# 404). Match it here too so the discovery activity treats it as non-retryable.BIGQUERY_DATASET_NOT_FOUND_ERROR: BIGQUERY_DATASET_NOT_FOUND_ERROR,+ # A syntactically invalid project/dataset ID (e.g. a value carrying parentheses like+ # "(default)") is rejected as a 400 "Invalid dataset ID ..." / "Invalid project ID ...".+ # Schema discovery re-raises it as `BigQueryInvalidIdentifierError` carrying the friendly+ # wording, so match that here, plus the raw 400 phrasings for occurrences elsewhere in the+ # sync. Deterministic config error — retrying never succeeds until the id is corrected.+ BIGQUERY_INVALID_IDENTIFIER_ERROR: BIGQUERY_INVALID_IDENTIFIER_ERROR,+ "Invalid dataset ID": BIGQUERY_INVALID_IDENTIFIER_ERROR,+ "Invalid project ID": BIGQUERY_INVALID_IDENTIFIER_ERROR,# Raised as a 400 BadRequest from job creation (POST .../jobs) when the location the# client runs in — the custom region from the source form, or the dataset's own location# auto-detected in `connect` — isn't a region BigQuery can run query jobs in, e.g.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 2f10ccd7c3c9..5e2bba6ae0e0 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,11 +12,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom 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 (BIGQUERY_DATASET_NOT_FOUND_ERROR,+ BIGQUERY_INVALID_IDENTIFIER_ERROR,BIGQUERY_QUERY_JOB_RETRY,BIGQUERY_TOKEN_RESPONSE_ERROR,BigQueryCredentialsRejectedError,BigQueryDatasetNotFoundError,BigQueryImplementation,+ BigQueryInvalidIdentifierError,BigQueryTokenRefreshError,_bq_select_clause,_get_primary_keys_for_table,@@ -160,6 +162,36 @@ def test_bigquery_get_columns_raises_friendly_error_when_dataset_not_found():assert BIGQUERY_DATASET_NOT_FOUND_ERROR in BigQuerySource().get_non_retryable_errors()[email protected]("phrase", ['Invalid dataset ID "(default)"', 'Invalid project ID "bad id"'])+def test_bigquery_get_columns_raises_friendly_error_for_invalid_identifier(phrase):+ """A syntactically invalid project/dataset ID surfaces as a raw 400 `BadRequest` from+ `client.query()`. Schema discovery must re-raise it with actionable wording instead of leaking+ the offending value and BigQuery job internals, and that wording must stay non-retryable."""+ fake_client = mock.MagicMock()+ fake_client.query.side_effect = BadRequest(+ f"400 {phrase}. Dataset IDs must be alphanumeric. Location: US Job ID: f2bf3ba8-4c4b"+ )++ with pytest.raises(BigQueryInvalidIdentifierError) as exc_info:+ BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)++ assert str(exc_info.value) == BIGQUERY_INVALID_IDENTIFIER_ERROR+ # The raw 400 (offending id, job id) must not survive into the message.+ assert "Job ID" not in str(exc_info.value)+ assert "(default)" not in str(exc_info.value)+ assert BIGQUERY_INVALID_IDENTIFIER_ERROR in BigQuerySource().get_non_retryable_errors()+++def test_bigquery_get_columns_propagates_unrelated_bad_request():+ """A BadRequest that isn't an invalid-identifier error (e.g. a malformed query) must propagate+ unchanged rather than being mislabeled as an invalid project/dataset ID."""+ fake_client = mock.MagicMock()+ fake_client.query.side_effect = BadRequest("400 Syntax error: Unexpected keyword SELECT")++ with pytest.raises(BadRequest):+ BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)++@pytest.mark.parametrize("error_message,expected_type,is_rejected",[