: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(data-imports): handle missing partition key column during schema drift (#73129)
Tom Owerse0e47d97e243
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.pyindex 67c7c5aa9dcf..255f06c02f39 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py@@ -1,5 +1,6 @@import uuidimport decimal+import hashlibimport datetimefrom ipaddress import IPv4Address, IPv6Addressfrom typing import Any, cast@@ -16,6 +17,7 @@ from structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (+ NULL_NUMERICAL_PARTITION,SchemaColumnTypeChangedException,_get_max_decimal_type,_to_list_array,@@ -1421,3 +1423,37 @@ def test_align_incoming_decimals_to_delta_raises_when_integer_overflows():with pytest.raises(SchemaColumnTypeChangedException):align_incoming_decimals_to_delta(arrow_table, delta_schema)+++ "mode,partition_count,partition_size,partition_format,expected",+ [+ # datetime is the reported crash: a persisted `hs_timestamp`/`_creation_time` key that the+ # source stopped returning fell into `row[key]` and raised a raw KeyError, failing every sync.+ ("datetime", None, None, "month", "1970-01"),+ ("numerical", None, 100, None, NULL_NUMERICAL_PARTITION),+ ("md5", 4, None, None, str(int(hashlib.md5(b"None").hexdigest(), 16) % 4)),+ ],+)+def test_append_partition_key_missing_column_buckets_into_fallback(+ mode, partition_count, partition_size, partition_format, expected+):+ # A persisted partition mode is reused on later batches without re-running detection, so a source+ # schema drift that drops the partition key column must bucket rows into a catch-all partition+ # rather than raise a raw KeyError.+ table = pa.table({"id": pa.array([1, 2, 3], type=pa.int64())})++ result = append_partition_key_to_table(+ table=table,+ partition_count=partition_count,+ partition_size=partition_size,+ partition_keys=["dropped_field"],+ partition_mode=mode,+ partition_format=partition_format,+ logger=cast(FilteringBoundLogger, structlog.get_logger()),+ )++ assert result is not None+ partitioned_table, resolved_mode, _, _ = result+ assert resolved_mode == mode+ assert partitioned_table.column(PARTITION_KEY).to_pylist() == [expected, expected, expected]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.pyindex 5eaff7e8603c..6b1807063a33 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py@@ -610,7 +610,9 @@ def append_partition_key_to_table(mode = "md5"# If there is only one primary key and it's a numerical ID, then bucket by the ID itself instead of hashing it- is_partition_key_int = pa.types.is_integer(table.field(normalized_partition_keys[0]).type)+ is_partition_key_int = normalized_partition_keys[0] in table.column_names and pa.types.is_integer(+ table.field(normalized_partition_keys[0]).type+ )are_incrementing_ints = Falseif is_partition_key_int:partition_column = table.column(normalized_partition_keys[0])@@ -646,6 +648,18 @@ def append_partition_key_to_table(else:logger.debug(f"append_partition_key_to_table: partitioning mode {mode} selected")+ # A persisted partition mode skips the detection block above, so the partition key column may be+ # absent from this batch — e.g. the source's schema drifted and stopped returning the field we+ # previously partitioned on. Reading a missing key per-row would raise a raw KeyError and fail+ # every sync; instead those rows fall back to a catch-all bucket (via `row.get`). When the missing+ # field is also the incremental field, the downstream incremental-value check surfaces an+ # actionable, non-retryable error.+ missing_partition_keys = [key for key in normalized_partition_keys if key not in table.column_names]+ if missing_partition_keys:+ logger.warning(+ f"append_partition_key_to_table: partition key(s) missing from incoming table, bucketing into fallback: {missing_partition_keys}"+ )+partition_array: list[str] = []for batch in table.to_batches():@@ -653,7 +667,7 @@ def append_partition_key_to_table(if mode == "md5":assert partition_count is not None, "append_partition_key_to_table: partition_count is None"- primary_key_values = [str(row[key]) for key in normalized_partition_keys]+ primary_key_values = [str(row.get(key)) for key in normalized_partition_keys]delimited_primary_key_value = "|".join(primary_key_values)# this hash has no security impact@@ -666,7 +680,7 @@ def append_partition_key_to_table(assert partition_size is not None, "append_partition_key_to_table: partition_size is None"key = normalized_partition_keys[0]- key_value = row[key]+ key_value = row.get(key)if key_value is None:partition_array.append(NULL_NUMERICAL_PARTITION)@@ -685,7 +699,7 @@ def append_partition_key_to_table(partition_array.append(str(coerced_key_value // partition_size))elif mode == "datetime":key = normalized_partition_keys[0]- date = row[key]+ date = row.get(key)if partition_format is None:partition_format = "week"