: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(warehouse-sources): fall back to native format for clickhouse syncs (#105253)
Daniel RC85ec89acaec2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.pyindex 9566d9e3dfd7..3bcfc2bb9ca5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py@@ -6,8 +6,8 @@ import mathimport timeimport threadingimport collections-from collections.abc import Callable, Iterator-from contextlib import _GeneratorContextManager+from collections.abc import Callable, Generator, Iterator, Sequence+from contextlib import _GeneratorContextManager, closingfrom typing import Any, Literal, Optionalimport pyarrow as pa@@ -1265,6 +1265,8 @@ _ARROW_UNSUPPORTED_PREFIXES: tuple[str, ...] = ("Nested(","Variant(","Object(",+ "JSON(",+ "Dynamic(",)@@ -1395,6 +1397,97 @@ def _query_settings(chunk_size: int) -> dict[str, Any]:}+# Some hosts serve the ClickHouse HTTP interface but not the ArrowStream output format, and the+# rejection names the format: Tinybird answers with a 403 "invalid format ArrowStream", and a+# ClickHouse build without Arrow support raises "Unknown format ArrowStream" (UNKNOWN_FORMAT).+_ARROW_FORMAT_REJECTED_SUBSTRING = "format ArrowStream"+++def _is_arrow_format_rejected(message: str) -> bool:+ return _ARROW_FORMAT_REJECTED_SUBSTRING in message+++_TIMESTAMP_UNIT_DIGITS: dict[str, int] = {"s": 0, "ms": 3, "us": 6, "ns": 9}+++def _datetime64_precision(column: ClickHouseColumn) -> int | None:+ inner, _ = _strip_type_modifiers(column.data_type)+ match = _DATETIME64_RE.match(inner)+ return int(match.group(1)) if match is not None else None+++def _ticks_to_timestamp(ticks: Sequence[Any], precision: int, timestamp_type: pa.TimestampType) -> pa.Array[Any]:+ scale = 10 ** (_TIMESTAMP_UNIT_DIGITS[timestamp_type.unit] - precision)+ if scale != 1:+ ticks = [None if tick is None else tick * scale for tick in ticks]+ return pa.array(ticks, type=pa.int64()).cast(timestamp_type)+++def _native_column_to_arrow(+ values: Sequence[Any], field: pa.Field[pa.DataType], datetime64_precision: int | None+) -> pa.Array[Any]:+ if datetime64_precision is not None and isinstance(field.type, pa.TimestampType):+ return _ticks_to_timestamp(values, datetime64_precision, field.type)+ try:+ return pa.array(values, type=field.type)+ except (pa.ArrowInvalid, pa.ArrowTypeError):+ # Types that `_build_select_list` does not cast with toString() but `to_arrow_field` maps to+ # string (geo types, AggregateFunction states, ...) decode to Python tuples, lists or numbers.+ if not pa.types.is_string(field.type):+ raise+ return pa.array([None if value is None else str(value) for value in values], type=pa.string())+++def _native_block_to_record_batch(+ block: Sequence[Sequence[Any]], schema: pa.Schema, datetime64_precisions: list[int | None]+) -> pa.RecordBatch:+ return pa.RecordBatch.from_arrays(+ [+ _native_column_to_arrow(column, field, precision)+ for column, field, precision in zip(block, schema, datetime64_precisions)+ ],+ schema=schema,+ )+++def _stream_record_batches(+ client: ClickHouseClient,+ query: str,+ parameters: dict[str, Any],+ columns: list[ClickHouseColumn],+ logger: FilteringBoundLogger,+) -> Generator[pa.RecordBatch]:+ """Stream the extraction query as one Arrow record batch per ClickHouse block.++ ArrowStream is the fast path because the server builds the batches. When the host rejects that+ format, we read the same query in the Native format, which every host that passed discovery+ accepts because clickhouse-connect uses it for the metadata queries. Each Native block is+ converted against the discovered schema. The host rejects the format before it sends any rows,+ so the retry cannot duplicate data. Both paths hold one block (`max_block_size` rows) at a+ time, plus the bounded HTTP read buffer of clickhouse-connect.+ """+ try:+ arrow_stream = client.query_arrow_stream(query, parameters=parameters)+ except ClickHouseError as e:+ if not _is_arrow_format_rejected(str(e)):+ raise+ logger.warning("ClickHouse host rejected the ArrowStream format, reading in the Native format instead")+ schema = pa.schema([column.to_arrow_field() for column in columns])+ datetime64_precisions = [_datetime64_precision(column) for column in columns]+ # Python datetimes stop at microseconds, so DateTime64 columns come back as integer ticks+ # to keep the sub-microsecond digits of DateTime64(7..9).+ column_formats: dict[str, str | dict[str, str]] = {+ column.name: "int" for column, precision in zip(columns, datetime64_precisions) if precision is not None+ }+ with client.query_column_block_stream(query, parameters=parameters, column_formats=column_formats) as blocks:+ for block in blocks:+ yield _native_block_to_record_batch(block, schema, datetime64_precisions)+ return++ with arrow_stream as batches:+ yield from batches++def clickhouse_source(*,tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],@@ -1547,7 +1640,7 @@ def clickhouse_source(logger.info(f"ClickHouse query: {query}")- # query_arrow_stream yields pa.RecordBatch chunks — one per+ # The stream yields pa.RecordBatch chunks — one per# ClickHouse block, capped by max_block_size. We accumulate# these into ~YIELD_TARGET_BYTES / YIELD_TARGET_ROWS pa.Tables# before yielding, so the pipeline's Delta writer sees fewer,@@ -1555,7 +1648,9 @@ def clickhouse_source(pending: list[pa.RecordBatch] = []pending_rows = 0pending_bytes = 0- with stream_client.query_arrow_stream(query, parameters=parameters) as stream:+ with closing(+ _stream_record_batches(stream_client, query, parameters, projected_columns, logger)+ ) as stream:for chunk in stream:if chunk.num_rows == 0:continuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.pyindex b3678f7827b2..6af1c993fe8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py@@ -1,8 +1,11 @@import os+import arrayimport socketimport threadingfrom collections.abc import AsyncIterable, Iteratorfrom contextlib import contextmanager+from datetime import UTC, datetime+from zoneinfo import ZoneInfoimport pytestfrom posthog.test.base import BaseTest@@ -240,6 +243,8 @@ class TestBuildQuery:ClickHouseColumn(name="ip", data_type="Nullable(IPv4)", nullable=True),ClickHouseColumn(name="tags", data_type="Array(String)", nullable=False),ClickHouseColumn(name="status", data_type="LowCardinality(Enum8('a' = 1))", nullable=False),+ ClickHouseColumn(name="payload", data_type="JSON(a UInt32)", nullable=False),+ ClickHouseColumn(name="value", data_type="Dynamic(max_types=8)", nullable=False),],should_use_incremental_field=False,incremental_field=None,@@ -249,6 +254,8 @@ class TestBuildQuery:assert "toString(`ip`) AS `ip`" in queryassert "toString(`tags`) AS `tags`" in queryassert "toString(`status`) AS `status`" in query+ assert "toString(`payload`) AS `payload`" in query+ assert "toString(`value`) AS `value`" in querydef test_full_refresh_with_row_filters_binds_values_as_params(self):query, params = _build_query(@@ -1449,7 +1456,7 @@ class TestGetRowsBatching:cm.__exit__.return_value = Falsereturn cm- def _run_get_rows(self, blocks):+ def _run_get_rows(self, blocks, stream_client=None, columns=None):"""Invoke `clickhouse_source(...).items()` against a stream of `blocks`."""from contextlib import contextmanager@@ -1459,9 +1466,12 @@ class TestGetRowsBatching:mock_client = MagicMock()mock_table = MagicMock()mock_table.to_arrow_schema.return_value = pa.schema([pa.field("id", pa.int64())])+ if columns is not None:+ mock_table.columns = columns- stream_client = MagicMock()- stream_client.query_arrow_stream.return_value = self._stream_context(blocks)+ if stream_client is None:+ stream_client = MagicMock()+ stream_client.query_arrow_stream.return_value = self._stream_context(blocks)@contextmanagerdef fake_tunnel():@@ -1525,6 +1535,69 @@ class TestGetRowsBatching:def test_empty_stream_yields_nothing(self):assert self._run_get_rows([]) == []+ @parameterized.expand(+ [+ ("http_403", "HTTP driver received HTTP status 403, server response: invalid format ArrowStream"),+ ("unknown_format", "Code: 73. DB::Exception: Unknown format ArrowStream. (UNKNOWN_FORMAT)"),+ ]+ )+ def test_reads_native_blocks_when_host_rejects_arrow(self, _name, error_msg):+ columns = [+ ClickHouseColumn("id", "UInt64", False),+ ClickHouseColumn("created_at", "DateTime('UTC')", False),+ ClickHouseColumn("label", "Nullable(String)", True),+ ClickHouseColumn("location", "Point", False),+ ClickHouseColumn("exact_at", "Nullable(DateTime64(9, 'UTC'))", True),+ ClickHouseColumn("tenth_at", "DateTime64(1)", False),+ ]+ new_york = ZoneInfo("America/New_York")+ native_blocks = [+ [+ array.array("Q", [1, 2]),+ [datetime(2026, 1, 1, 12, tzinfo=UTC), datetime(2026, 1, 1, 7, tzinfo=new_york)],+ ["a", None],+ [(1.5, 2.5), (0.0, 0.0)],+ [1767268800123456789, None],+ [17672688001, 17672688002],+ ],+ [array.array("Q", [3]), [datetime(2026, 1, 2, tzinfo=UTC)], ["c"], [(3.0, 4.0)], [1], [0]],+ ]+ stream_client = MagicMock()+ stream_client.query_arrow_stream.side_effect = ClickHouseError(error_msg)+ stream_client.query_column_block_stream.return_value = self._stream_context(native_blocks)++ yielded = self._run_get_rows([], stream_client=stream_client, columns=columns)++ assert stream_client.query_column_block_stream.call_args.kwargs["column_formats"] == {+ "exact_at": "int",+ "tenth_at": "int",+ }+ assert len(yielded) == 1+ assert yielded[0].schema == pa.schema([column.to_arrow_field() for column in columns])+ assert yielded[0].column("exact_at").cast(pa.int64()).to_pylist() == [1767268800123456789, None, 1]+ assert yielded[0].column("tenth_at").cast(pa.int64()).to_pylist() == [1767268800100, 1767268800200, 0]+ assert yielded[0].drop_columns(["exact_at", "tenth_at"]).to_pydict() == {+ "id": [1, 2, 3],+ "created_at": [+ datetime(2026, 1, 1, 12, tzinfo=UTC),+ datetime(2026, 1, 1, 12, tzinfo=UTC),+ datetime(2026, 1, 2, tzinfo=UTC),+ ],+ "label": ["a", None, "c"],+ "location": ["(1.5, 2.5)", "(0.0, 0.0)", "(3.0, 4.0)"],+ }++ def test_other_query_errors_do_not_fall_back_to_native(self):+ stream_client = MagicMock()+ stream_client.query_arrow_stream.side_effect = ClickHouseError(+ "Code: 60. DB::Exception: Unknown table expression identifier. (UNKNOWN_TABLE)"+ )++ with pytest.raises(ClickHouseError, match="UNKNOWN_TABLE"):+ self._run_get_rows([], stream_client=stream_client)++ stream_client.query_column_block_stream.assert_not_called()+class TestClickHouseReconcileSchemaMetadata(BaseTest):"""The ClickHouse-specific override that routes through the shared reconcile helper."""