: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 strings (#86518)
estefania22bd5b22b986
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 f1eab656e65d..c1848ebeaac9 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@@ -587,6 +587,48 @@ def merge_observed_columns_into_schema_metadata(config: dict[str, Any], observedexisting["is_nullable"] = observed["is_nullable"]+BINARY_ID_COLUMN_NAMES = {"id", "uuid", "guid"}+++def _is_id_like_column(column_name: str, primary_keys: Sequence[str] | None) -> bool:+ lowered = column_name.lower()+ if lowered in BINARY_ID_COLUMN_NAMES or lowered.endswith("_id"):+ return True+ return any(lowered == key.lower() for key in (primary_keys or []))+++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+ for every batch in the sync logs."""++ def __init__(self, logger: FilteringBoundLogger) -> None:+ self._logger = logger+ self._reported_columns: set[str] = set()++ def _once(self, column_name: str) -> bool:+ if column_name in self._reported_columns:+ return False+ self._reported_columns.add(column_name)+ return True++ def converted(self, column_name: str) -> None:+ if self._once(column_name):+ self._logger.info(f"Column '{column_name}' has a binary data type. Its values were synced as hex strings.")++ def dropped(self, column_name: str) -> None:+ if self._once(column_name):+ self._logger.warning(+ f"Column '{column_name}' was not synced because its binary data type is not supported."+ )++ def conversion_failed(self, column_name: str, error: Exception) -> None:+ if self._once(column_name):+ self._logger.warning(+ f"Column '{column_name}' was not synced because its binary values could not be converted to hex strings: {error}"+ )++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()}@@ -601,22 +643,36 @@ def _json_dumps(obj: Any) -> str:return str(obj)-def table_from_iterator(data_iterator: Iterator[dict], schema: Optional[pa.Schema] = None) -> pa.Table:+def table_from_iterator(+ data_iterator: Iterator[dict],+ schema: Optional[pa.Schema] = None,+ *,+ primary_keys: Optional[Sequence[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,+) -> pa.Table:batch = list(data_iterator)if not batch:return pa.Table.from_pylist([])- processed_batch = _process_batch(batch, schema)+ processed_batch = _process_batch(batch, schema, primary_keys=primary_keys, binary_reporter=binary_reporter)return processed_batch-def table_from_py_list(table_data: list[Any], schema: Optional[pa.Schema] = None) -> pa.Table:+def table_from_py_list(+ table_data: list[Any],+ schema: Optional[pa.Schema] = None,+ *,+ primary_keys: Optional[Sequence[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,+) -> pa.Table:"""Convert a list of Python dictionaries to a PyArrow Table.This is a wrapper around table_from_iterator for backward compatibility."""- return table_from_iterator(iter(table_data), schema=schema)+ return table_from_iterator(+ iter(table_data), schema=schema, primary_keys=primary_keys, binary_reporter=binary_reporter+ )def restrict_schema_to_columns(schema: pa.Schema, column_names: Sequence[str]) -> pa.Schema:@@ -936,7 +992,13 @@ def _serialize_dict_columns(table_data: list[dict]) -> tuple[list[dict], set[strreturn serialized_rows, dict_columns-def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -> pa.Table:+def _process_batch(+ table_data: list[dict],+ schema: Optional[pa.Schema] = None,+ *,+ primary_keys: Optional[Sequence[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,+) -> pa.Table:table_data, serialized_dict_columns = _serialize_dict_columns(table_data)# Support both given schemas and inferred schemas@@ -1049,9 +1111,32 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -adjusted_field = arrow_schema.field(field_index).with_type(pa.timestamp("us")).with_nullable(has_nulls)arrow_schema = arrow_schema.set(field_index, adjusted_field)- # Remove any binary columns+ # Binary columns can't be queried, so they are dropped; id-like ones are kept as hex+ # strings because they are usually the table's key, and losing the key breaks joins+ # and incremental merges on the synced table.if pa.types.is_binary(field.type):- drop_column_names.add(field_name)+ 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)+ drop_column_names.add(field_name)+ else:+ columnar_table_data[field_name] = hex_array+ py_type = str+ unique_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))+ drop_column_names.add(field_name)# Ensure duration columns have the correct arrow typecol = columnar_table_data[field_name]@@ -1284,9 +1369,32 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -if arrow_schema:arrow_schema = arrow_schema.set(field_index, arrow_schema.field(field_index).with_type(pa.string()))- # Remove any binary columns+ # Same keep-or-drop rule as the schema-typed binary branch above; this one catches+ # columns whose binary type is only visible from the Python values (e.g. inferred+ # schemas, or a declared type the values don't match).if issubclass(py_type, bytes):- drop_column_names.add(field_name)+ 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)+ drop_column_names.add(field_name)+ else:+ columnar_table_data[field_name] = hex_array+ py_type = str+ if 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))+ drop_column_names.add(field_name)if len(drop_column_names) != 0:for column in drop_column_names: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 5723a46877c1..9896e7f7ec8d 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@@ -6,7 +6,10 @@ import pyarrow as paimport pyarrow.compute as pcfrom structlog.types import FilteringBoundLogger-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ BinaryColumnReporter,+ table_from_py_list,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import (record_table_stats,table_payload_bytes,@@ -79,6 +82,8 @@ class Batcher:_source_type: Optional[str]_team_id: Optional[int]_schema_name: Optional[str]+ _primary_keys: Optional[list[str]]+ _binary_reporter: BinaryColumnReporterdef __init__(self,@@ -91,8 +96,11 @@ class Batcher:team_id: Optional[int] = None,schema_name: Optional[str] = None,coalesce_tables: bool = False,+ primary_keys: Optional[list[str]] = None,) -> None:self._logger = logger+ self._primary_keys = primary_keys+ self._binary_reporter = BinaryColumnReporter(logger)self._chunk_size = chunk_size or DEFAULT_CHUNK_SIZEself._chunk_size_bytes = chunk_size_bytes or DEFAULT_CHUNK_SIZE_BYTES@@ -120,6 +128,9 @@ class Batcher:self._ready = deque()self._ready_bytes = 0+ def _rows_to_table(self, rows: list[Any]) -> pa.Table:+ return table_from_py_list(rows, primary_keys=self._primary_keys, binary_reporter=self._binary_reporter)+def _set_ready(self, table: pa.Table) -> None:"""Split `table` so no yielded chunk overflows a 32-bit offset column or exceedsthe per-table Arrow-payload cap (keeping the loader's per-batch merge bounded)."""@@ -276,14 +287,14 @@ class Batcher:if self._buffer_size_bytes >= self._chunk_size_bytes or len(self._buffer) >= self._chunk_size:self._logger.debug(f"Processing buffer (list). Length of buffer = {len(self._buffer)}")- self._set_ready(table_from_py_list(self._buffer))+ self._set_ready(self._rows_to_table(self._buffer))else:returnelse:self._buffer_size_bytes += self._estimate_size(item)if self._buffer_size_bytes >= self._chunk_size_bytes or len(item) >= self._chunk_size:self._logger.debug(f"Processing item (list). Length of item = {len(item)}")- self._set_ready(table_from_py_list(item))+ self._set_ready(self._rows_to_table(item))else:self._buffer.extend(item)return@@ -294,7 +305,7 @@ class Batcher:returnself._logger.debug(f"Processing buffer (dict). Length of buffer = {len(self._buffer)}")- self._set_ready(table_from_py_list(self._buffer))+ self._set_ready(self._rows_to_table(self._buffer))elif isinstance(item, pa.Table):# A pa.Table never joins the list/dict buffer. Clearing the buffer# below would silently drop any rows accumulated from earlier list/dict@@ -324,7 +335,7 @@ class Batcher:def get_table(self) -> pa.Table:if not self._ready and len(self._buffer) > 0:self._logger.debug(f"Processing leftover buffer. Length of buffer = {len(self._buffer)}")- self._set_ready(table_from_py_list(self._buffer))+ self._set_ready(self._rows_to_table(self._buffer))self._buffer = []self._buffer_size_bytes = 0diff --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 1f5d5cae77a4..2c234237ab90 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@@ -20,6 +20,7 @@ from posthog.temporal.common.errors import NonReportableErrorfrom products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errorsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (BillingLimitsWillBeReachedException,+ BinaryColumnReporter,SchemaColumnTypeChangedException,_get_max_decimal_type,_to_list_array,@@ -343,6 +344,53 @@ def test_table_from_py_list_with_null_filled_binary_column():)+ "column_name,primary_keys,expect_kept",+ [+ ("id", None, True),+ ("ID", None, True),+ ("order_id", None, True),+ ("uuid", None, True),+ ("guid", None, True),+ ("token", ["token"], True),+ ("token", None, False),+ ("payload", None, False),+ ],+)+def test_table_from_py_list_keeps_id_like_binary_columns_as_hex(+ column_name: str, primary_keys: list[str] | None, expect_kept: bool+):+ table = table_from_py_list([{column_name: b"\xbd\xd6\x40", "other": 1.0}], primary_keys=primary_keys)++ if expect_kept:+ assert table.column(column_name).to_pylist() == ["bdd640"]+ assert table.schema.field(column_name).type == pa.string()+ else:+ assert column_name not in table.schema.names+++def test_table_from_py_list_keeps_binary_id_column_with_schema():+ schema = pa.schema(cast(Any, [pa.field("id", pa.binary()), pa.field("column", pa.string())]))+ table = table_from_py_list([{"id": b"\x01\xff", "column": "hello"}, {"id": None, "column": "world"}], schema)++ assert table.column("id").to_pylist() == ["01ff", None]+ assert table.schema.field("id").type == pa.string()+ assert table.column("column").to_pylist() == ["hello", "world"]+++def test_binary_column_reporter_logs_each_column_once_across_batches():+ logger = MagicMock()+ reporter = BinaryColumnReporter(logger)++ for _ in range(2):+ table_from_py_list([{"id": b"\x01", "payload": b"\x02"}], binary_reporter=reporter)++ assert logger.info.call_count == 1+ assert "id" in logger.info.call_args[0][0]+ assert logger.warning.call_count == 1+ assert "payload" in logger.warning.call_args[0][0]++@pytest.mark.parametrize("value, expected_type",[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 e69dd380a891..751fd75dc8c0 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@@ -141,6 +141,7 @@ class PipelineNonDLT(Generic[ResumableData]):source_type=self._source.source_type,team_id=self._job.team_id,schema_name=self._schema.name,+ primary_keys=self._resource.primary_keys,)self._internal_schema = HogQLSchema()self._sinks = build_pipeline_sinks(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 79bc88eec761..42a8a03e0dd0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -225,6 +225,7 @@ class PipelineV3(Generic[ResumableData]):team_id=self._job.team_id,schema_name=self._schema.name,coalesce_tables=resumable_source_manager is None and not self._schema.is_webhook,+ primary_keys=self._resource.primary_keys,)self._internal_schema = HogQLSchema()self._sinks = build_pipeline_sinks(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.pyindex 3794df489b83..2a338eb69934 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py@@ -25,6 +25,7 @@ from posthog.exceptions_capture import capture_exceptionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (DEFAULT_NUMERIC_PRECISION,DEFAULT_NUMERIC_SCALE,+ BinaryColumnReporter,build_pyarrow_decimal_type,table_from_iterator,)@@ -922,6 +923,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con)def get_rows() -> Iterator[Any]:+ binary_reporter = BinaryColumnReporter(logger)with self.connect(config) as streaming_connection:with streaming_connection.cursor() as cursor:query, args = _build_query(@@ -949,7 +951,12 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conif not rows:break- yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)+ yield table_from_iterator(+ (dict(zip(column_names, row)) for row in rows),+ arrow_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )return SourceResponse(name=location.response_name,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.pyindex 892fa2deaeb5..f12e49f78eba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py@@ -41,6 +41,7 @@ from posthog.exceptions_capture import capture_exception # noqa: F401from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (DEFAULT_NUMERIC_PRECISION,DEFAULT_NUMERIC_SCALE,+ BinaryColumnReporter,build_pyarrow_decimal_type,restrict_schema_to_columns,table_from_iterator,@@ -1446,6 +1447,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conprimary_keys, arrow_schema, chunk_size, partition_settings, rows_to_sync = (_retry_on_transient_tablet_unavailable(_discover_metadata, logger))+ binary_reporter = BinaryColumnReporter(logger)def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:"""Open a fresh connection and stream rows.@@ -1525,7 +1527,12 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conif not batch:break- yield table_from_iterator((dict(zip(column_names, row)) for row in batch), read_schema)+ yield table_from_iterator(+ (dict(zip(column_names, row)) for row in batch),+ read_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )finally:# Tear the streaming cursor down without draining the rest of# the unbuffered result set — see `_release_streaming_cursor`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.pyindex f461e4b6d792..17e7970c37aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py@@ -13,6 +13,7 @@ from psycopg import sqlfrom structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ BinaryColumnReporter,QueryTimeoutException,restrict_schema_to_columns,table_from_iterator,@@ -378,6 +379,8 @@ def iterate_date_windows(is_connection_dropped: Callable[[BaseException], bool] = lambda _e: False,clock: Callable[[], float] = time.monotonic,sleeper: Callable[[float], None] = time.sleep,+ primary_keys: Optional[list[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,) -> Iterator[pa.Table]:"""Walk the incremental field in adaptive bounded windows.@@ -447,7 +450,12 @@ def iterate_date_windows(if not rows:breakrows_this_window += len(rows)- yield table_from_iterator((dict(zip(columns, r)) for r in rows), window_schema)+ yield table_from_iterator(+ (dict(zip(columns, r)) for r in rows),+ window_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )except psycopg.errors.QueryCanceled:qc_retries += 1if qc_retries > WINDOW_MAX_QUERY_CANCELED_RETRIES or window <= min_window:@@ -598,6 +606,8 @@ def iterate_partitions(incremental_field_type: Optional[IncrementalFieldType] = None,db_incremental_field_last_value: Any = None,clock: Callable[[], float] = time.monotonic,+ primary_keys: Optional[list[str]] = None,+ binary_reporter: Optional[BinaryColumnReporter] = None,) -> Iterator[pa.Table]:"""One query per child partition. Used when partition key is not the incrementalfield or when the field isn't ordered (string/uuid)."""@@ -637,7 +647,12 @@ def iterate_partitions(if not rows:breakrows_this_partition += len(rows)- yield table_from_iterator((dict(zip(columns, r)) for r in rows), partition_schema)+ yield table_from_iterator(+ (dict(zip(columns, r)) for r in rows),+ partition_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )elapsed = clock() - p_starttotal_rows += rows_this_partitiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex ad10bc030af0..b0217e457868 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrDEFAULT_NUMERIC_PRECISION,DEFAULT_NUMERIC_SCALE,MAX_NUMERIC_SCALE,+ BinaryColumnReporter,QueryTimeoutException,TemporaryFileSizeExceedsLimitException,build_pyarrow_decimal_type,@@ -3306,6 +3307,7 @@ def postgres_source(time.sleep(min(2 * setup_connection_dropped_errors, 30))def get_rows(chunk_size: int) -> Iterator[Any]:+ binary_reporter = BinaryColumnReporter(logger)arrow_schema = table.to_arrow_schema()if xmin_bounds is not None:# The forced `_ph_xmin` projection isn't part of the discovered columns, so add it to@@ -3477,6 +3479,8 @@ def postgres_source(yield table_from_iterator((dict(zip(column_names, row)) for row in rows),restrict_schema_to_columns(arrow_schema, column_names),+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,)successive_errors = 0@@ -3607,6 +3611,8 @@ def postgres_source(incremental_field=incremental_field,incremental_field_type=incremental_field_type,db_incremental_field_last_value=db_incremental_field_last_value,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,)return@@ -3641,6 +3647,8 @@ def postgres_source(logger=logger,using_read_replica=using_read_replica,is_connection_dropped=_is_connection_dropped_error,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,)return@@ -3685,7 +3693,9 @@ def postgres_source(dicts = [dict(zip(column_names, row)) for row in rows]del rows- yield table_from_iterator(iter(dicts), read_schema)+ yield table_from_iterator(+ iter(dicts), read_schema, primary_keys=primary_keys, binary_reporter=binary_reporter+ )offset += len(dicts)returnexcept psycopg.errors.SerializationFailure as e:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.pyindex d8f480305277..9f2216ffffcf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py@@ -30,6 +30,7 @@ from posthog.exceptions_capture import capture_exceptionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (DEFAULT_NUMERIC_PRECISION,DEFAULT_NUMERIC_SCALE,+ BinaryColumnReporter,QueryTimeoutException,TemporaryFileSizeExceedsLimitException,build_pyarrow_decimal_type,@@ -477,6 +478,9 @@ def _stream_rows_as_arrow_batches(query: sql.Composed,chunk_size: int,arrow_schema: pa.Schema,+ *,+ primary_keys: list[str] | None = None,+ binary_reporter: BinaryColumnReporter | None = None,) -> Iterator[pa.Table]:"""Yield one Arrow table per `chunk_size` rows, reading rows straight off the wire.@@ -488,7 +492,12 @@ def _stream_rows_as_arrow_batches(pending: list[Any] = []def to_arrow(rows: list[Any]) -> pa.Table:- return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)+ return table_from_iterator(+ (dict(zip(column_names, row)) for row in rows),+ arrow_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )for row in cursor.stream(query, size=_libpq_rows_per_chunk()):if not column_names:@@ -508,6 +517,9 @@ def _fetch_arrow_batches(chunk_size: int,arrow_schema: pa.Schema,fetch_size: int | None = None,+ *,+ primary_keys: list[str] | None = None,+ binary_reporter: BinaryColumnReporter | None = None,) -> Iterator[pa.Table]:"""Yield one Arrow table per `chunk_size` rows drawn from an already-executed `cursor`.@@ -521,7 +533,12 @@ def _fetch_arrow_batches(page_size = fetch_size or chunk_sizedef to_arrow(rows: list[Any]) -> pa.Table:- return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)+ return table_from_iterator(+ (dict(zip(column_names, row)) for row in rows),+ arrow_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ )pending: list[Any] = []while True:@@ -547,6 +564,8 @@ def _stream_arrow_batches(arrow_schema: pa.Schema,cursor_name: str,logger: FilteringBoundLogger,+ *,+ primary_keys: list[str] | None = None,) -> Iterator[pa.Table]:"""Stream `query` as Arrow tables, holding only `chunk_size` rows in the worker at a time.@@ -569,10 +588,18 @@ def _stream_arrow_batches(re-emit rows the pipeline has already consumed, so later errors propagate."""yielded = False+ binary_reporter = BinaryColumnReporter(logger)try:with connection.cursor() as stream_cursor:- for batch in _stream_rows_as_arrow_batches(stream_cursor, query, chunk_size, arrow_schema):+ for batch in _stream_rows_as_arrow_batches(+ stream_cursor,+ query,+ chunk_size,+ arrow_schema,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ ):yielded = Trueyield batchreturn@@ -592,7 +619,14 @@ def _stream_arrow_batches(# first), so this never masks the original failure with a CLOSE error.with connection.cursor(name=cursor_name) as server_cursor:server_cursor.execute(query)- for batch in _fetch_arrow_batches(server_cursor, chunk_size, arrow_schema, fetch_size):+ for batch in _fetch_arrow_batches(+ server_cursor,+ chunk_size,+ arrow_schema,+ fetch_size,+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,+ ):yielded = Trueyield batchreturn@@ -1550,6 +1584,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoarrow_schema,f"posthog_{inputs.team_id}_{schema}.{table_name}",logger,+ primary_keys=primary_keys,)return SourceResponse(diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex e36cb4a0fdb4..8f20d453d45f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -982,6 +982,44 @@ async def test_postgres_binary_columns(team, postgres_config, postgres_connectioassert any(x == "id" for x in columns)[email protected]_db(transaction=True)+async def test_postgres_binary_primary_key_synced_as_hex(team, postgres_config, postgres_connection):+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.binary_pk_test (pk_col bytea PRIMARY KEY, name text)".format(+ schema=postgres_config["schema"]+ )+ )+ # Non-UTF8 bytes on purpose: a binary key's bytes usually aren't valid text+ await postgres_connection.execute(+ "INSERT INTO {schema}.binary_pk_test (pk_col, name) VALUES ('\\x8080fefe', 'row-1')".format(+ schema=postgres_config["schema"]+ )+ )+ await postgres_connection.commit()++ await _run(+ team=team,+ schema_name="binary_pk_test",+ table_name="postgres_binary_pk_test",+ source_type="Postgres",+ job_inputs={+ "host": postgres_config["host"],+ "port": postgres_config["port"],+ "database": postgres_config["database"],+ "user": postgres_config["user"],+ "password": postgres_config["password"],+ "schema": postgres_config["schema"],+ "ssh_tunnel_enabled": "False",+ },+ mock_data_response=[],+ )++ res = await sync_to_async(execute_hogql_query)(f"SELECT pk_col, name FROM postgres_binary_pk_test", team)++ assert res.results == [("8080fefe", "row-1")]++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncioasync def test_delta_wrapper_files(team, stripe_balance_transaction, mock_stripe_client, minio_client):