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): probe the merge key on incremental syncs (#116104)

Chris Shine5b8db7a84065
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 0e834056657d..c8f8829fa3cf 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
@@ -66,6 +66,10 @@ from posthog.models.integration.google_cloud import (
)
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ normalize_column_name,
+ normalize_table_column_names,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_TABLE_SIZE_BYTES
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
@@ -83,6 +87,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import resolve_merge_keys
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -105,7 +110,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigquery import (
BigQuerySourceConfig,
)
-from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings
+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncType, IncrementalFieldType, PartitionSettings
__all__ = [
"BIGQUERY_API_VERSION_V2",
@@ -1091,6 +1096,29 @@ def _get_primary_keys_for_table(table: bigquery.Table, client: bigquery.Client)
return primary_keys
+def _get_merge_keys(
+ stored_keys: list[str] | None,
+ detected_keys: list[str] | None,
+ table: bigquery.Table,
+ enabled_columns: list[str] | None,
+ incremental_field: str | None,
+) -> list[str] | None:
+ """The source columns an incremental merge matches rows on, or None when it has none.
+
+ The pipeline picks the key the same way (`resolve_primary_keys`). The Delta writer then keeps only the key
+ columns the read carries, under the names `normalize_table_column_names` gives them.
+ """
+ schema_columns = [field.name for field in table.schema]
+ merge_keys = resolve_merge_keys(stored_keys, detected_keys, schema_columns)
+ if not merge_keys:
+ return None
+ read_columns = compute_projected_columns(enabled_columns, detected_keys, incremental_field) or schema_columns
+ batch_columns = normalize_table_column_names(pa.table({name: pa.nulls(0) for name in read_columns}))
+ read_column_by_batch_name = dict(zip(batch_columns.column_names, read_columns))
+ merge_columns = (read_column_by_batch_name.get(normalize_column_name(key)) for key in merge_keys)
+ return list(dict.fromkeys(column for column in merge_columns if column is not None)) or None
+
+
# Stable wording BigQuery puts in a `resourcesExceeded` query failure's message. Shared between
# `_is_bigquery_resource_exceeded` and `BigQuerySource.get_non_retryable_errors` so the two sites
# stay in lockstep if BigQuery ever adjusts the phrasing.
@@ -1128,19 +1156,28 @@ def _is_bigquery_view_parse_failure(error: BadRequest) -> bool:
return "failed to parse view" in str(error)
-def _has_duplicate_primary_keys(table: bigquery.Table, client: bigquery.Client, primary_keys: list[str] | None) -> bool:
+def _has_duplicate_primary_keys(
+ table: bigquery.Table,
+ client: bigquery.Client,
+ primary_keys: list[str] | None,
+ row_filters: list[ValidatedRowFilter] | None = None,
+) -> bool:
if not primary_keys or len(primary_keys) == 0:
return False
try:
+ key_columns = ", ".join(_BQ_QUOTER.quote(key) for key in primary_keys)
+ filter_conditions, query_parameters = _bq_row_filter_conditions(row_filters, table)
+ where_clause = f"WHERE {' AND '.join(filter_conditions)}" if filter_conditions else ""
query = f"""
- SELECT {", ".join(primary_keys)}
+ SELECT {key_columns}
FROM `{table.dataset_id}`.`{table.table_id}`
- GROUP BY {", ".join(primary_keys)}
+ {where_clause}
+ GROUP BY {key_columns}
HAVING COUNT(*) > 1
"""
- job_config = QueryJobConfig()
+ job_config = QueryJobConfig(query_parameters=query_parameters)
job = client.query(query, job_config=job_config, project=table.project)
for _ in job.result():
@@ -1872,7 +1909,13 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
bq_table = bq_client.get_table(fully_qualified_table_name)
primary_keys = _get_primary_keys_for_table(bq_table, bq_client)
partition_settings = _get_partition_settings(bq_table, bq_client, partition_size_bytes=partition_size_bytes)
- has_duplicate_keys = _has_duplicate_primary_keys(bq_table, bq_client, primary_keys)
+ # Only an incremental sync merges, so it is the only sync that reads the probe result.
+ merge_keys = (
+ _get_merge_keys(inputs.primary_keys, primary_keys, bq_table, enabled_columns, incremental_field)
+ if inputs.sync_type == ExternalDataSchemaSyncType.INCREMENTAL
+ else None
+ )
+ has_duplicate_keys = _has_duplicate_primary_keys(bq_table, bq_client, merge_keys, row_filters)
rows_to_sync = _get_rows_to_sync(
bq_table,
bq_client,
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 1c565b4e93da..3b42938c68c5 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
@@ -1,7 +1,10 @@
+import re
import threading
+import contextlib
import concurrent.futures
+from collections.abc import Iterable
from types import SimpleNamespace
-from typing import cast
+from typing import Any, cast
import pytest
import time_machine
@@ -20,6 +23,7 @@ from google.api_core.exceptions import (
)
from google.auth.credentials import Credentials as GoogleAuthCredentials
from google.auth.exceptions import RefreshError
+from google.cloud.bigquery import SchemaField
from requests.adapters import HTTPAdapter
from posthog.models.integration import Integration
@@ -88,7 +92,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
BigQueryTemporaryDatasetConfig,
BigQueryUseCustomRegionConfig,
)
-from products.warehouse_sources.backend.types import IncrementalFieldType
+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncType, IncrementalFieldType
@pytest.fixture(autouse=True)
@@ -1221,6 +1225,121 @@ def test_has_duplicate_primary_keys_captures_unexpected_errors():
mock_capture.assert_called_once()
+def _probe_group_by(query: str) -> str | None:
+ match = re.search(r"GROUP BY (.+)\n", query)
+ return match.group(1) if match else None
+
+
+def _run_pipeline_against_fake_client(
+ *,
+ sync_type: ExternalDataSchemaSyncType,
+ stored_primary_keys: list[str] | None,
+ duplicated_key: str | None,
+ enabled_columns: list[str] | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
+):
+ queries: list[str] = []
+ probe_parameter_names: list[set[str]] = []
+
+ def fake_query(query, job_config=None, **_kwargs):
+ queries.append(query)
+ group_by = _probe_group_by(query)
+ if group_by is not None:
+ probe_parameter_names.append({parameter.name for parameter in job_config.query_parameters})
+ job = mock.MagicMock()
+ job.result.return_value = iter([("duplicated",)] if group_by is not None and group_by == duplicated_key else [])
+ return job
+
+ table = mock.MagicMock(
+ dataset_id="dataset-id", table_id="events", project="project-id", num_rows=None, num_bytes=None
+ )
+ table.schema = [
+ SchemaField("id", "STRING"),
+ SchemaField("_id", "STRING"),
+ SchemaField("orderId", "STRING"),
+ SchemaField("order_id", "STRING"),
+ SchemaField("seq", "INT64"),
+ ]
+ table.to_bqstorage.return_value = "projects/project-id/datasets/dataset-id/tables/events"
+ client = mock.MagicMock()
+ client.get_table.return_value = table
+ client.query.side_effect = fake_query
+ storage = mock.MagicMock()
+ storage.create_read_session.return_value.streams = []
+
+ inputs = _make_inputs(
+ sync_type=sync_type,
+ primary_keys=stored_primary_keys,
+ should_use_incremental_field=True,
+ incremental_field="seq",
+ incremental_field_type=IncrementalFieldType.Integer,
+ enabled_columns=enabled_columns,
+ row_filters=row_filters,
+ )
+ with (
+ mock.patch.object(bq_module, "bigquery_client", return_value=contextlib.nullcontext(client)),
+ mock.patch.object(bq_module, "bigquery_storage_read_client", return_value=contextlib.nullcontext(storage)),
+ mock.patch.object(bq_module, "delete_all_temp_destination_tables"),
+ mock.patch.object(bq_module, "delete_table"),
+ ):
+ response = BigQuerySource().source_for_pipeline(_make_config(), inputs)
+ list(cast(Iterable[Any], response.items()))
+ return response, queries, probe_parameter_names
+
+
+_SEQ_ABOVE_FIVE = ValidatedRowFilter(column="seq", operator=">", value=5, category=ColumnTypeCategory.INTEGER)
+_INCREMENTAL = ExternalDataSchemaSyncType.INCREMENTAL
+
+
+ "sync_type,stored_primary_keys,enabled_columns,row_filters,duplicated_key,expected_group_by,expected_blocked",
+ [
+ (_INCREMENTAL, ["_id"], None, None, "`id`", "`_id`", False),
+ (_INCREMENTAL, ["_id"], None, None, "`_id`", "`_id`", True),
+ (_INCREMENTAL, None, None, None, "`id`", "`id`", True),
+ (_INCREMENTAL, ["_id"], None, [_SEQ_ABOVE_FIVE], None, "`_id`", False),
+ (_INCREMENTAL, ["_id", "dropped_column"], None, None, None, "`_id`", False),
+ (_INCREMENTAL, ["orderId"], None, None, None, "`order_id`", False),
+ (_INCREMENTAL, ["orderId"], ["orderId", "seq"], None, None, "`orderId`", False),
+ (_INCREMENTAL, ["_id"], ["seq"], None, "`id`", None, False),
+ (ExternalDataSchemaSyncType.APPEND, ["_id"], None, None, "`_id`", None, False),
+ ],
+ ids=[
+ "unique_stored_key_passes_when_id_repeats",
+ "stored_key_duplicates_block",
+ "detected_key_without_stored_key",
+ "row_filters_bound_the_probe",
+ "stored_key_column_missing_from_table",
+ "stored_key_renamed_like_the_writer",
+ "camel_case_stored_key_with_column_selection",
+ "stored_key_not_in_the_read",
+ "append",
+ ],
+)
+def test_duplicate_probe_checks_the_merge_key(
+ sync_type, stored_primary_keys, enabled_columns, row_filters, duplicated_key, expected_group_by, expected_blocked
+):
+ response, queries, probe_parameter_names = _run_pipeline_against_fake_client(
+ sync_type=sync_type,
+ stored_primary_keys=stored_primary_keys,
+ duplicated_key=duplicated_key,
+ enabled_columns=enabled_columns,
+ row_filters=row_filters,
+ )
+
+ probe_queries = [query for query in queries if _probe_group_by(query) is not None]
+ if expected_group_by is None:
+ assert probe_queries == []
+ else:
+ assert [_probe_group_by(query) for query in probe_queries] == [expected_group_by]
+ assert ("WHERE" in probe_queries[0]) == bool(row_filters)
+ assert set(re.findall(r"@(\w+)", probe_queries[0])) == probe_parameter_names[0]
+ assert response.has_duplicate_primary_keys is expected_blocked
+ read_queries = [query for query in queries if query.startswith("SELECT ") and "COUNT(*)" not in query]
+ unselected_keys = [key for key in stored_primary_keys or [] if key not in (enabled_columns or [])]
+ assert all(f"`{key}`" not in query for key in unselected_keys for query in read_queries)
+
+
def test_bigquery_query_create_retry_retries_queued_jobs_quota():
"""The queued-jobs quota is rejected at `jobs.insert`, which `job_retry` never wraps — only the
`retry` on `client.query()` can wait it out — so the create retry must cover it while still