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): auto-detect dataset region during schema discovery (#65759)

Tom Owers5fac9002c2d5
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index b80c8d351c3c..5317e60efcb9 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -274,6 +274,34 @@ def bigquery_storage_read_client(
transport.close()
+def _detect_dataset_region(config: BigQuerySourceConfig) -> str | None:
+ """Resolve the dataset's BigQuery location for schema-discovery queries.
+
+ Credentials validate with a region-agnostic table listing, but a query job created
+ without an explicit location defaults to the US multi-region — so a dataset that lives
+ in another region passes validation yet fails discovery with "... was not found in
+ location US". `get_dataset` is region-agnostic, so read the dataset's real location and
+ pin discovery to it. Returns None on any failure, leaving the original behaviour intact.
+ """
+ with bigquery_client(
+ _resolve_project_id(config),
+ None,
+ config.key_file.private_key,
+ config.key_file.private_key_id,
+ config.key_file.client_email,
+ config.key_file.token_uri,
+ ) as bq:
+ try:
+ dataset_ref = bq.dataset(_resolve_dataset_id(config), project=_resolve_query_project(config))
+ return bq.get_dataset(dataset_ref).location
+ except Exception as e:
+ # Best-effort: fall back to the default location so `get_columns` still surfaces the
+ # actionable not-found error. Log rather than capture, to keep the fallback visible
+ # without spamming error tracking.
+ structlog.get_logger().warning("Failed to auto-detect BigQuery dataset region", exc_info=e)
+ return None
+
+
def delete_table(
table_id: str,
project_id: str,
@@ -694,7 +722,10 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
@contextmanager
def connect(self, config: BigQuerySourceConfig) -> Iterator[bigquery.Client]:
- region = _resolve_region(config)
+ # Without a custom region the client is built with `location=None`, so discovery
+ # query jobs default to the US multi-region and miss datasets in other regions.
+ # Auto-detect the dataset's location so discovery runs where the data lives.
+ region = _resolve_region(config) or _detect_dataset_region(config)
with bigquery_client(
_resolve_project_id(config),
region,
diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
index 7fdf515e1a25..3a5f19f7f9fa 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -597,6 +597,65 @@ def test_bigquery_resolve_region_trims_and_treats_whitespace_as_unset():
assert _resolve_region(config) is None
+# Regression: credentials validate with a region-agnostic `list_tables`, but a discovery query
+# job created without a location defaults to the US multi-region — so a dataset in another region
+# passed validation yet failed schema discovery with "... was not found in location US". `connect`
+# auto-resolves the dataset's real location so discovery runs where the data lives.
+
+
+def _patch_bigquery_client(fake_bq):
+ client_cm = mock.MagicMock()
+ client_cm.__enter__.return_value = fake_bq
+ return mock.patch(
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.bigquery_client",
+ return_value=client_cm,
+ )
+
+
+def test_connect_auto_detects_dataset_region_when_unset():
+ """No custom region configured: connect must pin the discovery client to the dataset's real
+ location (read via the region-agnostic `get_dataset`) instead of defaulting to US."""
+ fake_bq = mock.MagicMock()
+ fake_bq.get_dataset.return_value.location = "europe-west1"
+
+ with _patch_bigquery_client(fake_bq) as mock_client:
+ with BigQueryImplementation().connect(_make_config()) as conn:
+ assert conn is fake_bq
+
+ # The region must come from an actual dataset-location lookup, not a hardcoded default.
+ fake_bq.get_dataset.assert_called_once()
+ # The last client built is the one discovery queries run on; its location is positional arg 1.
+ assert mock_client.call_args_list[-1][0][1] == "europe-west1"
+
+
+def test_connect_uses_configured_region_without_probing():
+ """A configured custom region is used as-is — no dataset-location probe is performed."""
+ config = _make_config()
+ config.use_custom_region = BigQueryUseCustomRegionConfig(region="us-east1", enabled=True)
+ fake_bq = mock.MagicMock()
+
+ with _patch_bigquery_client(fake_bq) as mock_client:
+ with BigQueryImplementation().connect(config):
+ pass
+
+ fake_bq.get_dataset.assert_not_called()
+ assert mock_client.call_count == 1
+ assert mock_client.call_args_list[-1][0][1] == "us-east1"
+
+
+def test_connect_falls_back_to_unset_location_when_detection_fails():
+ """If the dataset-location probe fails (e.g. the dataset really doesn't exist), connect leaves
+ the location unset so `get_columns` still surfaces the actionable not-found error."""
+ fake_bq = mock.MagicMock()
+ fake_bq.get_dataset.side_effect = NotFound("Not found: Dataset prj:ds")
+
+ with _patch_bigquery_client(fake_bq) as mock_client:
+ with BigQueryImplementation().connect(_make_config()):
+ pass
+
+ assert mock_client.call_args_list[-1][0][1] is None
+
+
def test_bigquery_resolve_dataset_project_id_trims_and_treats_whitespace_as_unset():
config = _make_config(
dataset_project=BigQueryDatasetProjectConfig(dataset_project_id=" other-project ", enabled=True)