: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 when the dataset is not found (#64996)
Tom Owers8d0a8f4fef3e
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.pyindex 956c0222f8b3..b80c8d351c3c 100644--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py@@ -58,8 +58,10 @@ from posthog.temporal.data_imports.sources.generated_configs import BigQuerySourfrom products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings__all__ = [+ "BIGQUERY_DATASET_NOT_FOUND_ERROR","BIGQUERY_TOKEN_RESPONSE_ERROR","BigQueryCredentialsRejectedError",+ "BigQueryDatasetNotFoundError","BigQueryImplementation","BigQueryTokenRefreshError","bigquery_client",@@ -80,6 +82,24 @@ BIGQUERY_STORAGE_HOST = "bigquerystorage.googleapis.com"# so it must stay free of volatile data (urls, ids, timestamps).BIGQUERY_TOKEN_RESPONSE_ERROR = "BigQuery OAuth token endpoint returned an unexpected response"+# User-facing message for a missing dataset/table during schema discovery. Raised below and matched+# in `BigQuerySource.get_non_retryable_errors`, so it must stay free of volatile data (ids, regions).+BIGQUERY_DATASET_NOT_FOUND_ERROR = (+ "BigQuery couldn't find the configured dataset or table. It may have been deleted or renamed, or "+ "it may live in a different region — verify your dataset and table names, and set the dataset "+ "region in your source configuration if it isn't in the US."+)+++class BigQueryDatasetNotFoundError(Exception):+ """Raised when schema discovery queries a dataset/table that doesn't exist in the queried region.++ `client.query()` raises a `google.api_core.exceptions.NotFound` whose `str()` is a raw+ "404 Not found: Dataset ... was not found in location US ... Job ID: ..." — BigQuery job+ internals the user can't act on, which would otherwise leak straight to the create/validate+ response. We re-raise it with the same actionable wording we map this condition to during syncs.+ """+class BigQueryTokenRefreshError(Exception):"""Raised when the service-account OAuth token endpoint returns a non-JSON-object 200.@@ -714,6 +734,11 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquconfig.dataset_id,)return {}+ except NotFound as e:+ structlog.get_logger().warning(+ "BigQuery dataset '%s' not found during schema discovery: %s", config.dataset_id, e+ )+ raise BigQueryDatasetNotFoundError(BIGQUERY_DATASET_NOT_FOUND_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/posthog/temporal/data_imports/sources/bigquery/source.py b/posthog/temporal/data_imports/sources/bigquery/source.pyindex 62319b2731d9..b872d6613971 100644--- a/posthog/temporal/data_imports/sources/bigquery/source.py+++ b/posthog/temporal/data_imports/sources/bigquery/source.py@@ -12,6 +12,7 @@ from posthog.schema import ()from posthog.temporal.data_imports.sources.bigquery.bigquery import (+ BIGQUERY_DATASET_NOT_FOUND_ERROR,BIGQUERY_TOKEN_RESPONSE_ERROR,BigQueryImplementation,build_destination_table_prefix,@@ -96,13 +97,16 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):# grant the missing permission (e.g. the BigQuery Read Session User role). Matched on the# stable permission name rather than the volatile project id."bigquery.readsessions.create": "BigQuery denied access to the Storage Read API: your service account is missing the bigquery.readsessions.create permission. Please grant it (for example via the BigQuery Read Session User role) on the project you're syncing, then reconnect the source.",- # Raised from schema discovery (`get_columns`) and query jobs when the configured- # dataset/table doesn't exist in the location we query — the dataset was deleted or- # renamed, or it lives in a different region than the one we run against. The google- # exception stringifies as "404 Not found: Dataset ... was not found in location US",- # so match the stable phrasing here. Retrying can't recover — the user must fix the- # dataset or set the correct region.- "was not found in location": "BigQuery couldn't find the configured dataset or table. It may have been deleted or renamed, or it may live in a different region — verify your dataset and table names, and set the dataset region in your source configuration if it isn't in the US.",+ # Raised from query jobs when the configured dataset/table doesn't exist in the location+ # we query — the dataset was deleted or renamed, or it lives in a different region than the+ # one we run against. The google exception stringifies as "404 Not found: Dataset ... was+ # not found in location US", so match the stable phrasing here. Retrying can't recover —+ # the user must fix the dataset or set the correct region.+ "was not found in location": BIGQUERY_DATASET_NOT_FOUND_ERROR,+ # Schema discovery (`get_columns`) re-raises the same 404 as `BigQueryDatasetNotFoundError`+ # 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,# Raised from `bq_client.get_table(...)` in `_build_source_response` when the table being# synced no longer exists at sync time — it was deleted or renamed in BigQuery (common with# dbt-managed datasets) after schema discovery selected it. The google exception stringifiesdiff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.pyindex 2ebb85bb6c46..7fdf515e1a25 100644--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py@@ -11,8 +11,10 @@ from google.auth.exceptions import RefreshErrorfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom posthog.temporal.data_imports.sources.bigquery import bigquery as bq_modulefrom posthog.temporal.data_imports.sources.bigquery.bigquery import (+ BIGQUERY_DATASET_NOT_FOUND_ERROR,BIGQUERY_TOKEN_RESPONSE_ERROR,BigQueryCredentialsRejectedError,+ BigQueryDatasetNotFoundError,BigQueryImplementation,BigQueryTokenRefreshError,_bq_select_clause,@@ -134,6 +136,24 @@ def test_bigquery_get_columns_typeerror_handling(error_message, expected_type, iassert error_message in str(exc_info.value)+def test_bigquery_get_columns_raises_friendly_error_when_dataset_not_found():+ """A missing dataset/table surfaces as a raw google `NotFound` from `client.query()`. Schema+ discovery must re-raise it with actionable wording instead of leaking BigQuery job internals,+ and that wording must stay registered as non-retryable."""+ fake_client = mock.MagicMock()+ fake_client.query.side_effect = NotFound(+ "404 Not found: Dataset prj:ds was not found in location US Job ID: b3abc342-16a7"+ )++ with pytest.raises(BigQueryDatasetNotFoundError) as exc_info:+ BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)++ assert str(exc_info.value) == BIGQUERY_DATASET_NOT_FOUND_ERROR+ # The raw 404 (job id, location internals) must not survive into the message.+ assert "Job ID" not in str(exc_info.value)+ assert BIGQUERY_DATASET_NOT_FOUND_ERROR in BigQuerySource().get_non_retryable_errors()++@pytest.mark.parametrize("error_message,expected_type,is_rejected",[