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(data-warehouse): give actionable errors when BigQuery source validation fails (#71557)

Tom Owers025ff1e4e287
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 bf3218a6891c..2009c1df2233 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
@@ -126,6 +126,42 @@ BIGQUERY_INVALID_IDENTIFIER_ERROR = (
"Please check the Project ID and Dataset ID in your source configuration."
)
+# Google's token endpoint rejected the service account grant (rotated/revoked private key or a
+# deleted service account). Shared between onboarding credential validation and the sync-path
+# classifier in `BigQuerySource.get_non_retryable_errors`, so the two stay in lockstep. The wording
+# reads the same in both contexts ("upload a new key file"), so keep it free of context-specific
+# phrasing like "re-enable the sync".
+BIGQUERY_CREDENTIALS_REJECTED_ERROR = (
+ "Your BigQuery service account credentials were rejected by Google. The key may have been "
+ "rotated or revoked, or the service account deleted. Please upload a new Google Cloud JSON key file."
+)
+
+# The private key in the uploaded JSON key file couldn't be parsed (truncated/corrupted PEM body).
+# Shared with the sync-path classifier for lockstep; wording is context-neutral.
+BIGQUERY_INVALID_KEY_FILE_ERROR = (
+ "We couldn't read the private key in your Google Cloud JSON key file — it appears truncated or "
+ "corrupted. Please download a fresh service account key from Google Cloud and re-upload the JSON file."
+)
+
+# Onboarding-time messages. Unlike the sync-path classifier these are only reached during credential
+# validation, where the fix is to correct the input and try again rather than re-enable a sync.
+BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR = (
+ "Your Google Cloud JSON key file is missing required fields. Upload the full service account key "
+ "downloaded from Google Cloud. It must include project_id, private_key, private_key_id, "
+ "client_email, and token_uri."
+)
+
+BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR = (
+ "BigQuery denied access to the configured dataset or tables. Make sure your service account has "
+ "read access (for example the BigQuery Data Viewer role) on the dataset and the tables you want "
+ "to sync, then try again."
+)
+
+BIGQUERY_VALIDATION_GENERIC_ERROR = (
+ "Could not validate your BigQuery credentials. Please check your JSON key file, Project ID, "
+ "Dataset ID, and dataset region, then try again."
+)
+
# 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
@@ -490,7 +526,15 @@ def filter_bigquery_incremental_fields(
def validate_bigquery_credentials(
dataset_id: str, key_file: dict[str, str], dataset_project_id: str | None, location: str | None
-) -> bool:
+) -> tuple[bool, str | None]:
+ """Validate BigQuery credentials at onboarding time.
+
+ Returns ``(True, None)`` when the service account can list the configured dataset, or
+ ``(False, message)`` with an actionable reason. The common failure modes here (bad/rejected
+ key, missing dataset, wrong region, missing IAM read access) are expected user/config errors,
+ so they're mapped to a clear message instead of surfacing a bare "invalid credentials" and are
+ not reported to error tracking — only genuinely unexpected failures are captured.
+ """
project_id = key_file.get("project_id")
private_key = key_file.get("private_key")
private_key_id = key_file.get("private_key_id")
@@ -498,7 +542,7 @@ def validate_bigquery_credentials(
token_uri = key_file.get("token_uri")
if not project_id or not private_key or not private_key_id or not client_email or not token_uri:
- return False
+ return False, BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR
# Trim copy-paste whitespace from the identifiers before they reach BigQuery,
# which otherwise rejects them with an opaque `Invalid project ID`/`Invalid dataset ID`.
@@ -507,16 +551,32 @@ def validate_bigquery_credentials(
dataset_project_id = _normalize_identifier(dataset_project_id) if dataset_project_id else dataset_project_id
location = _normalize_identifier(location) if location else location
- with bigquery_client(project_id, location, private_key, private_key_id, client_email, token_uri) as bq:
- try:
+ try:
+ with bigquery_client(project_id, location, private_key, private_key_id, client_email, token_uri) as bq:
bq.list_tables(
bq.dataset(dataset_id, project=dataset_project_id or project_id),
retry=bigquery.DEFAULT_RETRY.with_timeout(5),
)
- return True
- except Exception as e:
- capture_exception(e)
- return False
+ return True, None
+ except Exception as e:
+ # Mirror the stable substrings the sync-path classifier keys off, so the wizard names the
+ # same root causes. Ordering matches `get_non_retryable_errors`: identifier/dataset before
+ # the generic access-denied so the more specific message wins.
+ message = str(e)
+ if "Unable to load PEM file" in message:
+ return False, BIGQUERY_INVALID_KEY_FILE_ERROR
+ if "invalid_grant" in message:
+ return False, BIGQUERY_CREDENTIALS_REJECTED_ERROR
+ if "Invalid project ID" in message or "Invalid dataset ID" in message:
+ return False, BIGQUERY_INVALID_IDENTIFIER_ERROR
+ if "was not found in location" in message or "Not found: Dataset" in message:
+ return False, BIGQUERY_DATASET_NOT_FOUND_ERROR
+ if "Access Denied" in message or "PermissionDenied" in message or "permission denied" in message:
+ return False, BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR
+ # Genuinely unexpected — keep the signal, and fall back to a generic message so no raw
+ # exception text (which can embed ids or tokens) reaches the user.
+ capture_exception(e)
+ return False, BIGQUERY_VALIDATION_GENERIC_ERROR
def _get_partition_settings(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
index 8a459a9732af..b8c835ab39d5 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
@@ -12,8 +12,10 @@ from posthog.schema import (
)
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (
+ BIGQUERY_CREDENTIALS_REJECTED_ERROR,
BIGQUERY_DATASET_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
+ BIGQUERY_INVALID_KEY_FILE_ERROR,
BIGQUERY_RESOURCES_EXCEEDED_ERROR,
BIGQUERY_TOKEN_RESPONSE_ERROR,
BigQueryImplementation,
@@ -53,14 +55,14 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
# can't recover invalid credentials; the user must upload a new key file. Matched on the
# stable `invalid_grant` code rather than `RefreshError`, which can also wrap transient
# token-endpoint failures that should stay retryable.
- "invalid_grant": "Your BigQuery service account credentials were rejected by Google. The key may have been rotated or revoked, or the service account deleted. Please upload a new Google Cloud JSON key file.",
+ "invalid_grant": BIGQUERY_CREDENTIALS_REJECTED_ERROR,
# Raised from `bigquery_client` when `service_account.Credentials.from_service_account_info`
# parses the uploaded key file's `private_key`. A truncated or corrupted PEM body (wrong
# padding, stray characters, copy-paste damage) makes the `cryptography` backend reject it
# as a `ValueError: Unable to load PEM file. ... InvalidData(InvalidPadding)`. The key can't
# be repaired by retrying — the user must re-upload an intact JSON key file. Matched on the
# stable "Unable to load PEM file" wording rather than the volatile InvalidData detail.
- "Unable to load PEM file": "We couldn't read the private key in your Google Cloud JSON key file — it appears truncated or corrupted. Please download a fresh service account key from Google Cloud and re-upload the JSON file.",
+ "Unable to load PEM file": BIGQUERY_INVALID_KEY_FILE_ERROR,
# Writing query results into the `__posthog_import_...` temp tables PostHog creates
# (`WRITE_TRUNCATE` in `_run_destination_query_with_job_retry`, on incremental / view /
# row-filtered reads) needs write access on the dataset those tables live in. When the
@@ -260,7 +262,7 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
and config.use_custom_region.region != ""
):
region = config.use_custom_region.region
- if validate_bigquery_credentials(
+ return validate_bigquery_credentials(
config.dataset_id,
{
"project_id": config.key_file.project_id,
@@ -271,10 +273,7 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
},
config.dataset_project.dataset_project_id if config.dataset_project else None,
region,
- ):
- return True, None
-
- return False, "Invalid BigQuery credentials"
+ )
@property
def get_source_config(self) -> SourceConfig:
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 20314bfe945e..77f382ae5228 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
@@ -19,11 +19,16 @@ from google.auth.exceptions import RefreshError
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
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_CREDENTIALS_REJECTED_ERROR,
BIGQUERY_DATASET_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
+ BIGQUERY_INVALID_KEY_FILE_ERROR,
+ BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
BIGQUERY_QUERY_JOB_RETRY,
BIGQUERY_READ_ROWS_RETRY,
BIGQUERY_TOKEN_RESPONSE_ERROR,
+ BIGQUERY_VALIDATION_GENERIC_ERROR,
+ BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR,
BigQueryCredentialsRejectedError,
BigQueryDatasetNotFoundError,
BigQueryImplementation,
@@ -88,6 +93,7 @@ def _make_config(
dataset_id: str = "dataset-id",
dataset_project: BigQueryDatasetProjectConfig | None = None,
temporary_dataset: BigQueryTemporaryDatasetConfig | None = None,
+ use_custom_region: BigQueryUseCustomRegionConfig | None = None,
) -> BigQuerySourceConfig:
return BigQuerySourceConfig(
key_file=BigQueryKeyFileConfig(
@@ -100,6 +106,7 @@ def _make_config(
dataset_id=dataset_id,
dataset_project=dataset_project,
temporary_dataset=temporary_dataset,
+ use_custom_region=use_custom_region,
)
@@ -951,6 +958,103 @@ def test_bigquery_validate_credentials_trims_whitespace_before_calling_bigquery(
bq.dataset.assert_called_once_with("my_dataset", project="524098457564")
+def _valid_key_file() -> dict[str, str]:
+ return {
+ "project_id": "my-project",
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "client_email": "client-email",
+ "token_uri": "token-uri",
+ }
+
+
+def test_bigquery_validate_credentials_missing_fields_reports_actionable_message():
+ key_file = _valid_key_file()
+ del key_file["private_key"]
+
+ with mock.patch.object(bq_module, "bigquery_client") as mock_client:
+ ok, message = validate_bigquery_credentials(
+ dataset_id="my_dataset", key_file=key_file, dataset_project_id=None, location=None
+ )
+
+ assert ok is False
+ assert message == BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR
+ # A malformed key file must be caught before we try to reach BigQuery.
+ mock_client.assert_not_called()
+
+
+ "exception,expected_message,should_capture",
+ [
+ (
+ ValueError("Unable to load PEM file. ... InvalidData(InvalidPadding)"),
+ BIGQUERY_INVALID_KEY_FILE_ERROR,
+ False,
+ ),
+ (RefreshError("('invalid_grant: Invalid JWT Signature.', {})"), BIGQUERY_CREDENTIALS_REJECTED_ERROR, False),
+ (BadRequest('Invalid dataset ID "(default)"'), BIGQUERY_INVALID_IDENTIFIER_ERROR, False),
+ (
+ NotFound("404 Not found: Dataset my-project:my_dataset was not found in location US"),
+ BIGQUERY_DATASET_NOT_FOUND_ERROR,
+ False,
+ ),
+ (
+ Forbidden("403 Access Denied: Table my-project:my_dataset.t"),
+ BIGQUERY_VALIDATION_PERMISSION_DENIED_ERROR,
+ False,
+ ),
+ (RuntimeError("something unexpected"), BIGQUERY_VALIDATION_GENERIC_ERROR, True),
+ ],
+)
+def test_bigquery_validate_credentials_maps_failures_to_actionable_messages(
+ exception, expected_message, should_capture
+):
+ client_cm = mock.MagicMock()
+ client_cm.__enter__.side_effect = exception
+
+ with (
+ mock.patch.object(bq_module, "bigquery_client", return_value=client_cm),
+ mock.patch.object(bq_module, "capture_exception") as mock_capture,
+ ):
+ ok, message = validate_bigquery_credentials(
+ dataset_id="my_dataset", key_file=_valid_key_file(), dataset_project_id=None, location=None
+ )
+
+ assert ok is False
+ assert message == expected_message
+ # Expected user/config errors must not be reported to error tracking as noise; only genuinely
+ # unexpected failures are captured.
+ assert mock_capture.called is should_capture
+
+
+ "use_custom_region,expected_region",
+ [
+ (None, None),
+ (BigQueryUseCustomRegionConfig(enabled=False, region="europe-west2"), None),
+ (BigQueryUseCustomRegionConfig(enabled=True, region=""), None),
+ (BigQueryUseCustomRegionConfig(enabled=True, region="europe-west2"), "europe-west2"),
+ ],
+)
+def test_bigquery_source_validate_credentials_wires_config_and_region(use_custom_region, expected_region):
+ config = _make_config(use_custom_region=use_custom_region)
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source.validate_bigquery_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ result = BigQuerySource().validate_credentials(config, team_id=1)
+
+ assert result == (True, None)
+ dataset_id, key_file, dataset_project_id, region = mock_validate.call_args.args
+ assert dataset_id == "dataset-id"
+ assert key_file["project_id"] == "project-id"
+ assert key_file["token_uri"] == "token-uri"
+ assert dataset_project_id is None
+ # A custom region only flows through when the toggle is enabled and non-empty.
+ assert region == expected_region
+
+
def test_bigquery_build_pipeline_trims_whitespace_in_destination_table():
"""Whitespace in project/dataset IDs must not leak into the fully-qualified
destination table name passed to BigQuery during a sync."""