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): trim whitespace from project and dataset identifiers (#63803)

Tom Owersaa5fdfb90535
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index 92c3ebfcd72f..6f47bcb30f90 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -70,14 +70,34 @@ def build_destination_table_prefix(schema_id: str | None) -> str:
return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"
+def _normalize_identifier(value: str) -> str:
+ """Trim whitespace from a user-supplied BigQuery identifier.
+
+ Project and dataset IDs are pasted into the source form by hand, so a stray
+ leading or trailing space slips in easily. BigQuery then rejects every
+ request with an opaque `BadRequest: Invalid project ID ' ...'` /
+ `Invalid dataset ID ' ...'` that no amount of retrying can fix. Trimming
+ here keeps the sync working instead of failing on a copy-paste artifact.
+ """
+ return value.strip()
+
+
+def _resolve_project_id(config: BigQuerySourceConfig) -> str:
+ return _normalize_identifier(config.key_file.project_id)
+
+
+def _resolve_dataset_id(config: BigQuerySourceConfig) -> str:
+ return _normalize_identifier(config.dataset_id)
+
+
def _resolve_region(config: BigQuerySourceConfig) -> str | None:
if (
config.use_custom_region
and config.use_custom_region.enabled
and config.use_custom_region.region is not None
- and config.use_custom_region.region != ""
+ and _normalize_identifier(config.use_custom_region.region) != ""
):
- return config.use_custom_region.region
+ return _normalize_identifier(config.use_custom_region.region)
return None
@@ -86,12 +106,22 @@ def _resolve_dataset_project_id(config: BigQuerySourceConfig) -> str | None:
config.dataset_project
and config.dataset_project.enabled
and config.dataset_project.dataset_project_id is not None
- and config.dataset_project.dataset_project_id != ""
+ and _normalize_identifier(config.dataset_project.dataset_project_id) != ""
):
- return config.dataset_project.dataset_project_id
+ return _normalize_identifier(config.dataset_project.dataset_project_id)
return None
+def _resolve_query_project(config: BigQuerySourceConfig) -> str:
+ """Project used to run INFORMATION_SCHEMA discovery queries.
+
+ Prefers the (optional) dataset project over the service account project,
+ mirroring the routing the rest of the source uses.
+ """
+ dataset_project_id = _resolve_dataset_project_id(config)
+ return dataset_project_id if dataset_project_id is not None else _resolve_project_id(config)
+
+
@contextlib.contextmanager
def bigquery_client(
project_id: str,
@@ -102,6 +132,7 @@ def bigquery_client(
token_uri: str,
) -> typing.Iterator[bigquery.Client]:
"""Manage a BigQuery client."""
+ project_id = _normalize_identifier(project_id)
credentials = service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
@@ -137,6 +168,7 @@ def bigquery_storage_read_client(
project_id: str, private_key: str, private_key_id: str, client_email: str, token_uri: str
):
"""Manage a BigQuery Storage client."""
+ project_id = _normalize_identifier(project_id)
credentials = service_account.Credentials.from_service_account_info(
{
"private_key": private_key,
@@ -252,6 +284,13 @@ def validate_bigquery_credentials(
if not project_id or not private_key or not private_key_id or not client_email or not token_uri:
return False
+ # Trim copy-paste whitespace from the identifiers before they reach BigQuery,
+ # which otherwise rejects them with an opaque `Invalid project ID`/`Invalid dataset ID`.
+ project_id = _normalize_identifier(project_id)
+ dataset_id = _normalize_identifier(dataset_id)
+ 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:
bq.list_tables(
@@ -462,7 +501,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
def connect(self, config: BigQuerySourceConfig) -> Iterator[bigquery.Client]:
region = _resolve_region(config)
with bigquery_client(
- config.key_file.project_id,
+ _resolve_project_id(config),
region,
config.key_file.private_key,
config.key_file.private_key_id,
@@ -484,10 +523,8 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
query = conn.query(
- f"SELECT table_name, column_name, data_type, is_nullable FROM `{config.dataset_id}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
- project=config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id,
+ f"SELECT table_name, column_name, data_type, is_nullable FROM `{_resolve_dataset_id(config)}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
+ project=_resolve_query_project(config),
)
try:
rows = query.result()
@@ -523,11 +560,8 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
if not tables:
return {}
- project = (
- config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id
- )
+ project = _resolve_query_project(config)
+ dataset_id = _resolve_dataset_id(config)
# Join against INFORMATION_SCHEMA.COLUMNS so a PK constraint that
# references a column already dropped (stale metadata between
@@ -541,10 +575,10 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# half the rows get dropped.
query = f"""
SELECT tc.table_name, kcu.column_name
- FROM `{config.dataset_id}`.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
- JOIN `{config.dataset_id}`.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
+ FROM `{dataset_id}`.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
+ JOIN `{dataset_id}`.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON tc.constraint_name = kcu.constraint_name
- JOIN `{config.dataset_id}`.INFORMATION_SCHEMA.COLUMNS c
+ JOIN `{dataset_id}`.INFORMATION_SCHEMA.COLUMNS c
ON kcu.table_name = c.table_name
AND (
kcu.column_name = c.column_name
@@ -591,15 +625,11 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
try:
result: dict[str, set[str]] = {table: set() for table in tables}
- project = (
- config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id
- )
+ project = _resolve_query_project(config)
query = f"""
SELECT table_name, column_name
- FROM `{config.dataset_id}`.INFORMATION_SCHEMA.COLUMNS
+ FROM `{_resolve_dataset_id(config)}`.INFORMATION_SCHEMA.COLUMNS
WHERE is_partitioning_column = 'YES'
OR clustering_ordinal_position = 1
"""
@@ -628,15 +658,16 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
region = _resolve_region(config)
dataset_project_id = _resolve_dataset_project_id(config)
- destination_table_dataset_id = config.dataset_id
+ project_id = _resolve_project_id(config)
+ destination_table_dataset_id = _resolve_dataset_id(config)
if (
config.temporary_dataset
and config.temporary_dataset.enabled
and config.temporary_dataset.temporary_dataset_id is not None
- and config.temporary_dataset.temporary_dataset_id != ""
+ and _normalize_identifier(config.temporary_dataset.temporary_dataset_id) != ""
):
- destination_table_dataset_id = config.temporary_dataset.temporary_dataset_id
+ destination_table_dataset_id = _normalize_identifier(config.temporary_dataset.temporary_dataset_id)
# Including the schema ID in table prefix ensures we only delete tables
# from this schema, and that if we fail we will clean up any previous
@@ -645,12 +676,12 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# relaxed with using a relatively long UUID as part of the prefix.
destination_table_prefix = build_destination_table_prefix(inputs.schema_id)
- destination_table = f"{config.key_file.project_id}.{destination_table_dataset_id}.{destination_table_prefix}_{inputs.job_id.replace('-', '_')}_{str(datetime.now().timestamp()).replace('.', '')}"
+ destination_table = f"{project_id}.{destination_table_dataset_id}.{destination_table_prefix}_{inputs.job_id.replace('-', '_')}_{str(datetime.now().timestamp()).replace('.', '')}"
delete_all_temp_destination_tables(
dataset_id=destination_table_dataset_id,
table_prefix=destination_table_prefix,
- project_id=config.key_file.project_id,
+ project_id=project_id,
location=region,
dataset_project_id=dataset_project_id,
private_key=config.key_file.private_key,
@@ -672,7 +703,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# Delete the destination table (if it exists) after we're done with it
delete_table(
table_id=destination_table,
- project_id=config.key_file.project_id,
+ project_id=project_id,
location=region,
private_key=config.key_file.private_key,
private_key_id=config.key_file.private_key_id,
@@ -708,7 +739,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
enabled_columns = inputs.enabled_columns
logger = inputs.logger
- project_id = config.key_file.project_id
+ project_id = _resolve_project_id(config)
location = region
private_key = config.key_file.private_key
private_key_id = config.key_file.private_key_id
@@ -717,7 +748,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
project_id_for_dataset = dataset_project_id or project_id
name = NamingConvention.normalize_identifier(table_name)
- fully_qualified_table_name = f"{project_id_for_dataset}.{config.dataset_id}.{table_name}"
+ fully_qualified_table_name = f"{project_id_for_dataset}.{_resolve_dataset_id(config)}.{table_name}"
with bigquery_client(
project_id=project_id,
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 95f4f86f69bc..91c044acb25e 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -10,7 +10,13 @@ from posthog.temporal.data_imports.sources.bigquery.bigquery import (
BigQueryImplementation,
_bq_select_clause,
_get_query,
+ _resolve_dataset_id,
+ _resolve_dataset_project_id,
+ _resolve_project_id,
+ _resolve_query_project,
+ _resolve_region,
delete_all_temp_destination_tables,
+ validate_bigquery_credentials,
)
from posthog.temporal.data_imports.sources.bigquery.source import BigQuerySource
from posthog.temporal.data_imports.sources.common.sql.identifiers import InvalidIdentifierError
@@ -19,6 +25,7 @@ from posthog.temporal.data_imports.sources.generated_configs import (
BigQueryKeyFileConfig,
BigQuerySourceConfig,
BigQueryTemporaryDatasetConfig,
+ BigQueryUseCustomRegionConfig,
)
from products.data_warehouse.backend.types import IncrementalFieldType
@@ -45,18 +52,20 @@ def _make_inputs(**overrides) -> SourceInputs:
def _make_config(
*,
+ project_id: str = "project-id",
+ dataset_id: str = "dataset-id",
dataset_project: BigQueryDatasetProjectConfig | None = None,
temporary_dataset: BigQueryTemporaryDatasetConfig | None = None,
) -> BigQuerySourceConfig:
return BigQuerySourceConfig(
key_file=BigQueryKeyFileConfig(
- project_id="project-id",
+ project_id=project_id,
private_key="private-key",
private_key_id="private-key-id",
client_email="client-email",
token_uri="token-uri",
),
- dataset_id="dataset-id",
+ dataset_id=dataset_id,
dataset_project=dataset_project,
temporary_dataset=temporary_dataset,
)
@@ -243,3 +252,135 @@ def test_delete_all_temp_destination_tables_captures_unexpected_errors():
mock_capture = _run_delete_all_temp_destination_tables(RuntimeError("boom"), logger)
mock_capture.assert_called_once()
+
+
+# Regression: a stray leading/trailing space in a hand-entered project or dataset ID made
+# every BigQuery request fail with an opaque `BadRequest: Invalid project ID ' ...'` /
+# `Invalid dataset ID ' ...'`. The identifiers must be trimmed before reaching BigQuery.
+
+
+ "resolver,field,raw,expected",
+ [
+ (_resolve_project_id, "project_id", " 524098457564", "524098457564"),
+ (_resolve_project_id, "project_id", "project-id\n", "project-id"),
+ (_resolve_dataset_id, "dataset_id", " bigquery_aloalo ", "bigquery_aloalo"),
+ (_resolve_dataset_id, "dataset_id", "\tdataset-id", "dataset-id"),
+ ],
+)
+def test_bigquery_resolvers_trim_whitespace(resolver, field, raw, expected):
+ config = _make_config(**{field: raw})
+ assert resolver(config) == expected
+
+
+def test_bigquery_resolve_region_trims_and_treats_whitespace_as_unset():
+ assert (
+ _resolve_region(_make_config(dataset_project=None)) is None # no custom region configured
+ )
+
+ config = _make_config()
+ config.use_custom_region = BigQueryUseCustomRegionConfig(region=" us-east1 ", enabled=True)
+ assert _resolve_region(config) == "us-east1"
+
+ config.use_custom_region = BigQueryUseCustomRegionConfig(region=" ", enabled=True)
+ assert _resolve_region(config) 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)
+ )
+ assert _resolve_dataset_project_id(config) == "other-project"
+
+ config = _make_config(dataset_project=BigQueryDatasetProjectConfig(dataset_project_id=" ", enabled=True))
+ assert _resolve_dataset_project_id(config) is None
+
+
+def test_bigquery_resolve_query_project_prefers_dataset_project():
+ config = _make_config(
+ project_id=" service-account-project ",
+ dataset_project=BigQueryDatasetProjectConfig(dataset_project_id=" dataset-project ", enabled=True),
+ )
+ assert _resolve_query_project(config) == "dataset-project"
+
+ config = _make_config(project_id=" service-account-project ")
+ assert _resolve_query_project(config) == "service-account-project"
+
+
+def test_bigquery_get_columns_trims_whitespace_in_identifiers():
+ """`get_columns` must not embed a leading space into the INFORMATION_SCHEMA query
+ or the `project` it runs against."""
+ fake_client = mock.MagicMock()
+ fake_client.query.return_value.result.return_value = []
+
+ config = _make_config(project_id=" 524098457564", dataset_id=" bigquery_aloalo ")
+ BigQueryImplementation().get_columns(fake_client, config, names=None)
+
+ sql = fake_client.query.call_args.args[0]
+ assert "`bigquery_aloalo.INFORMATION_SCHEMA.COLUMNS`" in sql
+ assert " bigquery_aloalo" not in sql
+ assert fake_client.query.call_args.kwargs["project"] == "524098457564"
+
+
+def test_bigquery_get_primary_keys_trims_whitespace_in_identifiers():
+ fake_client = mock.MagicMock()
+ fake_client.query.return_value.result.return_value = []
+
+ config = _make_config(project_id=" my-project ", dataset_id=" my_dataset ")
+ BigQueryImplementation().get_primary_keys(fake_client, config, tables=["t"])
+
+ sql = fake_client.query.call_args.args[0]
+ assert "`my_dataset`.INFORMATION_SCHEMA.TABLE_CONSTRAINTS" in sql
+ assert " my_dataset`" not in sql
+ assert fake_client.query.call_args.kwargs["project"] == "my-project"
+
+
+def test_bigquery_validate_credentials_trims_whitespace_before_calling_bigquery():
+ bq = mock.MagicMock()
+ client_cm = mock.MagicMock()
+ client_cm.__enter__.return_value = bq
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.bigquery_client", return_value=client_cm
+ ) as mock_client:
+ validate_bigquery_credentials(
+ dataset_id=" my_dataset ",
+ key_file={
+ "project_id": " 524098457564",
+ "private_key": "private-key",
+ "private_key_id": "private-key-id",
+ "client_email": "client-email",
+ "token_uri": "token-uri",
+ },
+ dataset_project_id=None,
+ location=None,
+ )
+
+ assert mock_client.call_args.args[0] == "524098457564"
+ bq.dataset.assert_called_once_with("my_dataset", project="524098457564")
+
+
+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."""
+ config = _make_config(project_id=" 524098457564", dataset_id=" bigquery_aloalo ")
+ expected_table_id = (
+ f"524098457564.bigquery_aloalo.__posthog_import_schema_id_job_id_"
+ f"{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}"
+ )
+
+ with (
+ freeze_time("2025-01-01T12:00:00.000Z"),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.delete_all_temp_destination_tables",
+ ) as mock_delete_all,
+ mock.patch.object(BigQueryImplementation, "_build_source_response", return_value=mock.MagicMock()),
+ mock.patch(
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.delete_table",
+ ) as mock_delete,
+ ):
+ BigQuerySource().source_for_pipeline(config, _make_inputs())
+
+ assert mock_delete_all.call_args.kwargs["project_id"] == "524098457564"
+ assert mock_delete_all.call_args.kwargs["dataset_id"] == "bigquery_aloalo"
+ assert mock_delete.call_args.kwargs["table_id"] == expected_table_id