: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
feat(data-warehouse): sync id-like binary columns as hex on the arrow path (#89410)
Daniel RC40bbb092a44a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.pyindex 7bd5faaada16..94b349b1973b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py@@ -5,7 +5,7 @@ import mathimport uuidimport decimalimport datetime-from collections.abc import Callable, Iterator, Sequence+from collections.abc import Callable, Iterable, Iterator, Sequencefrom functools import _make_key, wrapsfrom ipaddress import IPv4Address, IPv6Addressfrom typing import TYPE_CHECKING, Any, Literal, Optional, cast@@ -228,7 +228,11 @@ def _time_to_seconds(value: datetime.time) -> float:return value.hour * 3600 + value.minute * 60 + value.second + value.microsecond / 1_000_000-def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Schema | None) -> pa.Table:+def evolve_pyarrow_schema(+ incoming_table: pa.Table,+ delta_schema: deltalake.Schema | None,+ merge_key_columns: Sequence[str] | None = None,+) -> pa.Table:# First pass: normalize types that Delta write path does not handle well.for column_name in incoming_table.column_names:incoming_column = incoming_table.column(column_name)@@ -285,6 +289,7 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Sche# Second pass: align with existing Delta table schema.delta_arrow_schema = pyarrow_schema_from_arrow_exportable(delta_schema)+ merge_keys = {_fold_column_name_for_match(name) for name in merge_key_columns or []}for delta_field in delta_arrow_schema:if delta_field.name not in incoming_table.schema.names:new_column_data = (@@ -356,6 +361,28 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Scheincoming_table = incoming_table.set_column(incoming_table.schema.get_field_index(delta_field.name), delta_field.name, parsed_timestamps)+ elif (+ _fold_column_name_for_match(delta_field.name) in merge_keys+ and (pa.types.is_binary(delta_field.type) or pa.types.is_large_binary(delta_field.type))+ and (pa.types.is_string(incoming_column.type) or pa.types.is_large_string(incoming_column.type))+ ):+ # A table written before `hex_encode_id_binary_columns` stores this key as raw+ # bytes while the batch now carries hex text. pyarrow casts string to binary+ # without complaint, which would store the hex text as bytes: the merge predicate+ # would then match no stored row and re-insert every incoming row. Fail instead,+ # so the table is reset and re-synced onto the hex representation.+ #+ # Only merge keys (primary keys and the partition-key source columns) take this+ # path. Every other column casts as before, so a source that legitimately turns a+ # non-key binary column into a string column keeps syncing.+ raise SchemaColumnTypeChangedException(+ f"Source column type changed: merge key '{delta_field.name}' is stored as {delta_field.type} "+ f"but now arrives as text ({incoming_column.type}). Reset and fully re-sync this table to "+ f"adopt the new type.",+ column_name=delta_field.name,+ stored_type=delta_field.type,+ incoming_type=incoming_column.type,+ )else:try:casted_column = incoming_column.cast(delta_field.type).combine_chunks()@@ -597,6 +624,38 @@ def _is_id_like_column(column_name: str, primary_keys: Sequence[str] | None) ->return any(lowered == key.lower() for key in (primary_keys or []))+def _hex_arrays_or_report(+ value_chunks: Iterable[Sequence[bytes | None]],+ column_name: str,+ binary_reporter: Optional[BinaryColumnReporter],+ hex_type: pa.DataType,+) -> Optional[list[pa.Array]]:+ """Lowercase-hex strings for one binary column, or None when the values can't be converted.++ Takes the column one chunk at a time so the Python `bytes` and `str` objects of a whole+ column are never live at once — an Arrow-native source hands over batches far larger than+ the row path's, and this is the only step that leaves Arrow.++ Callers decide what None means: the row path drops the column, the Arrow path leaves it+ binary. Both report the same way.+ """+ try:+ hex_arrays: list[pa.Array] = [+ pa.array([None if value is None else value.hex() for value in chunk], type=hex_type)+ for chunk in value_chunks+ ]+ # pa.ArrowException also catches the 32-bit offset overflow of a chunk whose hex crosses+ # 2 GB, which is an ArrowCapacityError and so sits outside ValueError.+ except (AttributeError, TypeError, ValueError, pa.ArrowException) as e:+ if binary_reporter:+ binary_reporter.conversion_failed(column_name, e)+ return None++ if binary_reporter:+ binary_reporter.converted(column_name)+ return hex_arrays++class BinaryColumnReporter:"""Logs each binary column's outcome once per instance lifetime (one sync), because`_process_batch` runs per batch and logging there directly would repeat the same line@@ -629,6 +688,42 @@ class BinaryColumnReporter:)+def hex_encode_id_binary_columns(+ table: pa.Table,+ primary_keys: Optional[Sequence[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,+) -> pa.Table:+ """Convert id-like binary columns of an Arrow-native batch to lowercase hex strings.++ Sources that hand the pipeline Arrow tables (BigQuery, Snowflake, Databricks, MotherDuck)+ never reach `_process_batch`, so their binary keys land in Delta as raw bytes, which cannot+ be read or joined in HogQL. Same name/primary-key gate as the row path.++ Non-key binary columns stay untouched: this path has always synced them, so dropping them+ the way the row path does would delete data these tables already carry.+ """+ for index, field in enumerate(table.schema):+ if not (pa.types.is_binary(field.type) or pa.types.is_large_binary(field.type)):+ continue+ if not _is_id_like_column(field.name, primary_keys):+ continue++ # Indexed, not by name: a batch carrying the same column name twice makes the name+ # lookup raise instead of converting.+ column = table.column(index)+ # Keep 64-bit offsets where the source column has them: hex doubles the byte length.+ hex_type = pa.large_string() if pa.types.is_large_binary(field.type) else pa.string()+ hex_arrays = _hex_arrays_or_report(+ (chunk.to_pylist() for chunk in column.chunks), field.name, binary_reporter, hex_type+ )+ if hex_arrays is None:+ continue++ table = table.set_column(index, field.with_type(hex_type), pa.chunked_array(hex_arrays, type=hex_type))++ return table++def _convert_uuid_to_string(row: dict) -> dict:return {key: str(value) if isinstance(value, uuid.UUID) else value for key, value in row.items()}@@ -1147,23 +1242,21 @@ def _process_batch(# and incremental merges on the synced table.if pa.types.is_binary(field.type):if _is_id_like_column(str(field_name), primary_keys):- try:- hex_array = pa.array(- [None if s is None else s.hex() for s in _to_list_array(columnar_table_data[field_name])]- )- except (AttributeError, TypeError, ValueError) as e:- if binary_reporter:- binary_reporter.conversion_failed(str(field_name), e)+ hex_arrays = _hex_arrays_or_report(+ [_to_list_array(columnar_table_data[field_name])],+ str(field_name),+ binary_reporter,+ pa.string(),+ )+ if hex_arrays is None:drop_column_names.add(field_name)else:- columnar_table_data[field_name] = hex_array+ columnar_table_data[field_name] = hex_arrays[0]py_type = strunique_types_in_column = {str}arrow_schema = arrow_schema.set(field_index, arrow_schema.field(field_index).with_type(pa.string()))- if binary_reporter:- binary_reporter.converted(str(field_name))else:if binary_reporter:binary_reporter.dropped(str(field_name))@@ -1405,23 +1498,18 @@ def _process_batch(# schemas, or a declared type the values don't match).if issubclass(py_type, bytes):if _is_id_like_column(str(field_name), primary_keys):- try:- hex_array = pa.array(- [None if s is None else s.hex() for s in _to_list_array(columnar_table_data[field_name])]- )- except (AttributeError, TypeError, ValueError) as e:- if binary_reporter:- binary_reporter.conversion_failed(str(field_name), e)+ hex_arrays = _hex_arrays_or_report(+ [_to_list_array(columnar_table_data[field_name])], str(field_name), binary_reporter, pa.string()+ )+ if hex_arrays is None:drop_column_names.add(field_name)else:- columnar_table_data[field_name] = hex_array+ columnar_table_data[field_name] = hex_arrays[0]py_type = strif arrow_schema:arrow_schema = arrow_schema.set(field_index, arrow_schema.field(field_index).with_type(pa.string()))- if binary_reporter:- binary_reporter.converted(str(field_name))else:if binary_reporter:binary_reporter.dropped(str(field_name))diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.pyindex 9896e7f7ec8d..17efabeff4d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py@@ -8,6 +8,7 @@ from structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (BinaryColumnReporter,+ hex_encode_id_binary_columns,table_from_py_list,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import (@@ -313,6 +314,9 @@ class Batcher:# losing data. (In practice sources emit only one item type, never a mix.)if self._buffer:raise Exception("Cannot batch a pa.Table while list/dict rows are buffered; call get_table() first")+ # Arrow-native sources skip `_rows_to_table`, so their binary keys are converted here+ # instead.+ item = hex_encode_id_binary_columns(item, self._primary_keys, self._binary_reporter)if self._coalesce_tables:self._batch_table(item)returndiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.pyindex 9f8cb11a63b6..598820bbb18c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_batcher.py@@ -486,3 +486,22 @@ def test_batching_should_yield_when_buffer_not_full_with_incomplete_chunk_set():expected_table = pa.table({"a": [1, 2, 3]})assert result_table.equals(expected_table)+++def test_batching_pa_table_converts_primary_key_binary_column_to_hex():+ batcher = Batcher(logger=mock.MagicMock(), primary_keys=["sk_load"])++ batcher.batch(+ pa.table(+ {+ "sk_load": pa.array([b"\xbd\xd6\x40", None], type=pa.binary()),+ "payload": pa.array([b"\x01", b"\x02"], type=pa.binary()),+ }+ )+ )++ result_table = batcher.get_table()++ assert result_table.column("sk_load").to_pylist() == ["bdd640", None]+ assert result_table.schema.field("sk_load").type == pa.string()+ assert result_table.column("payload").to_pylist() == [b"\x01", b"\x02"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.pyindex c610bde3f02e..22df271244a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrapply_enabled_columns_projection,conditional_lru_cache_async,evolve_pyarrow_schema,+ hex_encode_id_binary_columns,is_safe_numeric_widening,merge_observed_columns_into_schema_metadata,normalize_table_column_names,@@ -379,6 +380,48 @@ def test_table_from_py_list_keeps_binary_id_column_with_schema():assert table.column("column").to_pylist() == ["hello", "world"]+ "column_name,column_type,primary_keys,expected_values,expected_type",+ [+ ("id", pa.binary(), None, ["bdd640", None], pa.string()),+ ("order_id", pa.binary(), None, ["bdd640", None], pa.string()),+ ("sk_load", pa.binary(), ["sk_load"], ["bdd640", None], pa.string()),+ ("sk_load", pa.large_binary(), ["sk_load"], ["bdd640", None], pa.large_string()),+ ("sk_load", pa.binary(), None, [b"\xbd\xd6\x40", None], pa.binary()),+ ("payload", pa.binary(), None, [b"\xbd\xd6\x40", None], pa.binary()),+ ],+)+def test_hex_encode_id_binary_columns(+ column_name: str,+ column_type: pa.DataType,+ primary_keys: list[str] | None,+ expected_values: list[Any],+ expected_type: pa.DataType,+):+ table = pa.table({column_name: pa.array([b"\xbd\xd6\x40", None], type=column_type), "other": [1.0, 2.0]})++ converted = hex_encode_id_binary_columns(table, primary_keys)++ assert converted.column(column_name).to_pylist() == expected_values+ assert converted.column("other").to_pylist() == [1.0, 2.0]+ assert converted.schema.field(column_name).type == expected_type+++def test_hex_encode_id_binary_columns_keeps_chunk_order_and_nulls():+ chunked = pa.chunked_array(+ [+ pa.array([b"\xbd\xd6\x40", None], type=pa.binary()),+ pa.array([None, b"\x01\xff"], type=pa.binary()),+ ]+ )+ table = pa.table({"id": chunked})++ converted = hex_encode_id_binary_columns(table)++ assert converted.column("id").to_pylist() == ["bdd640", None, None, "01ff"]+ assert converted.schema.field("id").type == pa.string()++def test_binary_column_reporter_logs_each_column_once_across_batches():logger = MagicMock()reporter = BinaryColumnReporter(logger)@@ -930,6 +973,34 @@ def test_evolve_pyarrow_schema_whole_valued_floats_cast_into_stored_integer_coluassert evolved_table.column("val").to_pylist() == [10, 20]+ "merge_key_columns,raises",+ [+ (["val"], True),+ (None, False),+ ],+)+def test_evolve_pyarrow_schema_guards_only_merge_keys_against_hex_text(+ merge_key_columns: list[str] | None, raises: bool+):+ arrow_table = pa.table(+ {+ "id": pa.array([1, 2], type=pa.int64()),+ "val": pa.array(["01ff", "02ff"], type=pa.string()),+ }+ )+ delta_schema = deltalake.Schema.from_arrow(+ pa.schema(cast(Any, [pa.field("id", pa.int64(), nullable=False), pa.field("val", pa.binary(), nullable=True)]))+ )++ if raises:+ with pytest.raises(SchemaColumnTypeChangedException, match="merge key"):+ evolve_pyarrow_schema(arrow_table, delta_schema, merge_key_columns=merge_key_columns)+ else:+ evolved = evolve_pyarrow_schema(arrow_table, delta_schema, merge_key_columns=merge_key_columns)+ assert evolved.column("val").to_pylist() == [b"01ff", b"02ff"]++@pytest.mark.parametrize("delta_type, incoming_column",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.pyindex 751fd75dc8c0..3f24a28e7e8f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py@@ -341,7 +341,16 @@ class PipelineNonDLT(Generic[ResumableData]):pa_table = await setup_partitioning(pa_table, delta_table, self._schema, self._resource, self._logger)- pa_table = evolve_pyarrow_schema(pa_table, delta_table.schema() if delta_table is not None else None)+ pa_table = evolve_pyarrow_schema(+ pa_table,+ delta_table.schema() if delta_table is not None else None,+ merge_key_columns=[+ *(self._resource.primary_keys or []),+ *(self._schema.partitioning_keys_override or []),+ *(self._schema.partitioning_keys or []),+ *(self._resource.partition_keys or []),+ ],+ )pa_table = _handle_null_columns_with_definitions(pa_table, self._resource)write_type: Literal["incremental", "full_refresh", "append"] = "full_refresh"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex 9db501544429..df49be649f3d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -898,7 +898,11 @@ def _process_message_reported(if existing_delta_table is not None:try:- pa_table = evolve_pyarrow_schema(pa_table, existing_delta_table.schema())+ pa_table = evolve_pyarrow_schema(+ pa_table,+ existing_delta_table.schema(),+ merge_key_columns=[*(primary_keys or []), *(export_signal.partition_keys or [])],+ )except SchemaColumnTypeChangedException as e:# A safe numeric widening is mechanically recoverable: stamp reset_pipeline so the# next scheduled sync resets and re-syncs the table, and reword the failure so