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(warehouse-sources): page clickhouse reads past host query limits (#106716)

Daniel RCcf215bf562a3
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.py
index 3bcfc2bb9ca5..8bab555bf3d4 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
@@ -76,6 +76,10 @@ DATA_QUERY_TIMEOUT_SECONDS = 60 * 60 # 1 hour
YIELD_TARGET_BYTES = 200 * 1024 * 1024 # 200 MiB, matches pipeline partition target
YIELD_TARGET_ROWS = 100_000
+# Page sizes for re-reading a table whose single query hits a host's per-query result or memory cap.
+PAGED_READ_INITIAL_ROWS = 500_000
+PAGED_READ_MIN_ROWS = 1_000
+
# Quoter for user-supplied row-filter column names — the allowlist-validated
# safety rail the shared predicate renderer expects. Trusted internal
# identifiers (table/incremental columns) keep using `_quote_identifier`.
@@ -1327,6 +1331,25 @@ def _last_value_expr(incremental_field_type: Optional[IncrementalFieldType]) ->
return "%(last_value)s"
+def _build_conditions(
+ *,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ incremental_field_type: Optional[IncrementalFieldType] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
+) -> tuple[list[str], dict[str, Any]]:
+ """WHERE conditions of the extraction query: the incremental cursor, then the row filters."""
+ filter_conditions, filter_params = render_named_conditions(row_filters or [], _ROW_FILTER_IDENTIFIER_QUOTER)
+ if not should_use_incremental_field:
+ return filter_conditions, filter_params
+
+ if incremental_field is None:
+ raise ValueError("incremental_field can't be None when should_use_incremental_field is True")
+
+ cursor_condition = f"{_quote_identifier(incremental_field)} > {_last_value_expr(incremental_field_type)}"
+ return [cursor_condition, *filter_conditions], filter_params
+
+
def _build_query(
*,
database: str,
@@ -1336,6 +1359,7 @@ def _build_query(
incremental_field: Optional[str],
incremental_field_type: Optional[IncrementalFieldType] = None,
row_filters: Optional[list[ValidatedRowFilter]] = None,
+ page_conditions: Sequence[str] = (),
) -> tuple[str, dict[str, Any]]:
"""Build the data extraction query and its bound parameters.
@@ -1349,20 +1373,72 @@ def _build_query(
qualified = _qualified_table(database, table_name)
select_list = _build_select_list(columns)
- filter_conditions, filter_params = render_named_conditions(row_filters or [], _ROW_FILTER_IDENTIFIER_QUOTER)
+ conditions, filter_params = _build_conditions(
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ row_filters=row_filters,
+ )
+ conditions = [*conditions, *page_conditions]
- if not should_use_incremental_field:
- if filter_conditions:
- return f"SELECT {select_list} FROM {qualified} WHERE {' AND '.join(filter_conditions)}", filter_params
- return f"SELECT {select_list} FROM {qualified}", filter_params
+ query = f"SELECT {select_list} FROM {qualified}"
+ if conditions:
+ query += f" WHERE {' AND '.join(conditions)}"
+ if should_use_incremental_field and incremental_field is not None:
+ query += f" ORDER BY {_quote_identifier(incremental_field)} ASC"
+ return query, filter_params
- if incremental_field is None:
- raise ValueError("incremental_field can't be None when should_use_incremental_field is True")
- quoted_field = _quote_identifier(incremental_field)
- conditions = [f"{quoted_field} > {_last_value_expr(incremental_field_type)}", *filter_conditions]
- query = f"SELECT {select_list} FROM {qualified} WHERE {' AND '.join(conditions)} ORDER BY {quoted_field} ASC"
- return query, filter_params
+def _page_key(
+ columns: Sequence[ClickHouseColumn],
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ primary_keys: Optional[list[str]],
+) -> list[str] | None:
+ """Columns whose values split the table into pages, or None when the table has none.
+
+ A NULL fails every comparison, so a nullable sorting-key column would drop its NULL rows from
+ every page. The incremental cursor has no such problem: the cursor condition already skips them.
+ """
+ if should_use_incremental_field:
+ return [incremental_field] if incremental_field else None
+ if not primary_keys:
+ return None
+ nullable_by_name = {column.name: column.nullable for column in columns}
+ if any(nullable_by_name.get(key, True) for key in primary_keys):
+ return None
+ return primary_keys
+
+
+def _page_conditions(
+ key: list[str], lower: Sequence[str] | None, upper: Sequence[str] | None
+) -> tuple[list[str], dict[str, Any]]:
+ """Conditions that keep the rows whose key is above `lower` and at most `upper`.
+
+ Bounds are the key values as ClickHouse renders them with toString(). ClickHouse parses each one
+ back into its column type for the comparison, so no precision is lost in the round trip.
+ """
+ key_tuple = f"({', '.join(_quote_identifier(column) for column in key)})"
+ conditions: list[str] = []
+ parameters: dict[str, Any] = {}
+ for name, operator, bound in (("page_lower", ">", lower), ("page_upper", "<=", upper)):
+ if bound is None:
+ continue
+ placeholders = [f"%({name}_{index})s" for index in range(len(bound))]
+ conditions.append(f"{key_tuple} {operator} ({', '.join(placeholders)})")
+ parameters.update({f"{name}_{index}": value for index, value in enumerate(bound)})
+ return conditions, parameters
+
+
+def _build_page_bound_query(
+ *, database: str, table_name: str, key: list[str], conditions: Sequence[str], page_rows: int
+) -> str:
+ """Query for the key of the last row of a page that starts after the given conditions."""
+ quoted_key = [_quote_identifier(column) for column in key]
+ query = f"SELECT {', '.join(f'toString({column})' for column in quoted_key)} FROM {_qualified_table(database, table_name)}"
+ if conditions:
+ query += f" WHERE {' AND '.join(conditions)}"
+ return f"{query} ORDER BY {', '.join(quoted_key)} LIMIT 1 OFFSET {page_rows - 1}"
def _query_settings(chunk_size: int) -> dict[str, Any]:
@@ -1407,6 +1483,15 @@ def _is_arrow_format_rejected(message: str) -> bool:
return _ARROW_FORMAT_REJECTED_SUBSTRING in message
+# Per-query caps some hosts enforce and a user can't raise. Tinybird caps each result at 500 MiB and
+# each query's memory, and fails the query before it sends any row.
+_QUERY_LIMIT_EXCEEDED_SUBSTRINGS: tuple[str, ...] = ("TOO_MANY_ROWS_OR_BYTES", "MEMORY_LIMIT_EXCEEDED")
+
+
+def _is_query_limit_exceeded(message: str) -> bool:
+ return any(substring in message for substring in _QUERY_LIMIT_EXCEEDED_SUBSTRINGS)
+
+
_TIMESTAMP_UNIT_DIGITS: dict[str, int] = {"s": 0, "ms": 3, "us": 6, "ns": 9}
@@ -1544,6 +1629,7 @@ def clickhouse_source(
# Project to the user-selected columns (always keeping PK + cursor).
projected_columns = _project_columns(list(table.columns), enabled_columns, primary_keys, incremental_field)
+ page_key = _page_key(list(table.columns), should_use_incremental_field, incremental_field, primary_keys)
# Warn when the incremental cursor isn't the sorting-key prefix.
# ClickHouse can only skip the sort if the ORDER BY column leads
@@ -1621,10 +1707,7 @@ def clickhouse_source(
)
try:
- query, filter_params = _build_query(
- database=database,
- table_name=table_name,
- columns=projected_columns,
+ base_conditions, filter_params = _build_conditions(
should_use_incremental_field=should_use_incremental_field,
incremental_field=incremental_field,
incremental_field_type=incremental_field_type,
@@ -1638,7 +1721,66 @@ def clickhouse_source(
last_value = incremental_type_to_initial_value(incremental_field_type)
parameters["last_value"] = last_value
- logger.info(f"ClickHouse query: {query}")
+ def read_batches() -> Generator[pa.RecordBatch]:
+ """Read the table in one query, or in pages of key ranges once a host limit rejects that.
+
+ A page is retried with half as many rows while the host rejects it before it sends a
+ row. A rejection after rows were read raises, because the retry would read them again.
+ """
+ page_rows: int | None = None
+ lower: list[str] | None = None
+ while True:
+ read_any = False
+ try:
+ upper: list[str] | None = None
+ page_conditions: list[str] = []
+ page_parameters: dict[str, Any] = {}
+ if page_rows is not None and page_key is not None:
+ lower_conditions, lower_parameters = _page_conditions(page_key, lower, None)
+ bound_query = _build_page_bound_query(
+ database=database,
+ table_name=table_name,
+ key=page_key,
+ conditions=[*base_conditions, *lower_conditions],
+ page_rows=page_rows,
+ )
+ bound_rows = stream_client.query(
+ bound_query, parameters={**parameters, **lower_parameters}
+ ).result_rows
+ upper = list(bound_rows[0]) if bound_rows else None
+ page_conditions, page_parameters = _page_conditions(page_key, lower, upper)
+
+ query, _ = _build_query(
+ database=database,
+ table_name=table_name,
+ columns=projected_columns,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ row_filters=row_filters,
+ page_conditions=page_conditions,
+ )
+ logger.info(f"ClickHouse query: {query}")
+ with closing(
+ _stream_record_batches(
+ stream_client, query, {**parameters, **page_parameters}, projected_columns, logger
+ )
+ ) as batches:
+ for batch in batches:
+ read_any = read_any or batch.num_rows > 0
+ yield batch
+ except ClickHouseError as e:
+ if read_any or page_key is None or not _is_query_limit_exceeded(str(e)):
+ raise
+ if page_rows is not None and page_rows // 2 < PAGED_READ_MIN_ROWS:
+ raise
+ page_rows = PAGED_READ_INITIAL_ROWS if page_rows is None else page_rows // 2
+ logger.warning(f"ClickHouse query exceeded a host limit, reading {page_rows} rows per page")
+ continue
+
+ if upper is None:
+ return
+ lower = upper
# The stream yields pa.RecordBatch chunks — one per
# ClickHouse block, capped by max_block_size. We accumulate
@@ -1648,9 +1790,7 @@ def clickhouse_source(
pending: list[pa.RecordBatch] = []
pending_rows = 0
pending_bytes = 0
- with closing(
- _stream_record_batches(stream_client, query, parameters, projected_columns, logger)
- ) as stream:
+ with closing(read_batches()) as stream:
for chunk in stream:
if chunk.num_rows == 0:
continue
diff --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.py
index 7dd503c75809..b00a125d906a 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,9 @@
import os
+import uuid
import array
import socket
import threading
-from collections.abc import AsyncIterable, Iterator
+from collections.abc import AsyncIterable, Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
@@ -11,7 +12,10 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
+from django.conf import settings
+
import pyarrow as pa
+import clickhouse_connect
from clickhouse_connect.driver.exceptions import ClickHouseError, OperationalError, ProgrammingError
from parameterized import parameterized
@@ -1617,6 +1621,138 @@ class TestGetRowsBatching:
stream_client.query_column_block_stream.assert_not_called()
+ def test_limit_error_after_rows_were_read_does_not_fall_back_to_pages(self):
+ def blocks_then_limit_error():
+ yield self._block(10)
+ raise ClickHouseError("Code: 396. DB::Exception: Limit for result exceeded. (TOO_MANY_ROWS_OR_BYTES)")
+
+ stream_client = MagicMock()
+ stream_client.query_arrow_stream.return_value = self._stream_context(blocks_then_limit_error())
+
+ with pytest.raises(ClickHouseError, match="TOO_MANY_ROWS_OR_BYTES"):
+ self._run_get_rows([], stream_client=stream_client, columns=[ClickHouseColumn("id", "UInt64", False)])
+
+ stream_client.query_arrow_stream.assert_called_once()
+ stream_client.query.assert_not_called()
+
+
+class TestPagedReadFallback:
+ _HOST_LIMITS = {"max_result_rows": 10, "result_overflow_mode": "throw", "http_wait_end_of_query": 1}
+ _BASE_NANOS = 1_767_225_600_000_000_000
+
+ @pytest.fixture
+ def make_table(self) -> Iterator[Callable[[str], str]]:
+ admin = clickhouse_connect.get_client(
+ host=settings.CLICKHOUSE_HOST,
+ port=8123,
+ username=settings.CLICKHOUSE_USER,
+ password=settings.CLICKHOUSE_PASSWORD,
+ )
+ admin.command(f"CREATE DATABASE IF NOT EXISTS {settings.CLICKHOUSE_DATABASE}")
+ created: list[str] = []
+
+ def make(order_by: str) -> str:
+ name = f"paged_read_{uuid.uuid4().hex}"
+ qualified = f"{settings.CLICKHOUSE_DATABASE}.{name}"
+ created.append(qualified)
+ admin.command(f"""
+ CREATE TABLE {qualified} (id UInt64, grp String, ts DateTime64(9, 'UTC'))
+ ENGINE = MergeTree ORDER BY {order_by}
+ """)
+ admin.command(f"""
+ INSERT INTO {qualified}
+ SELECT number, if(number % 2 = 0, 'a', 'b'), fromUnixTimestamp64Nano(toInt64({self._BASE_NANOS} + intDiv(number, 3) * 500), 'UTC')
+ FROM numbers(30)
+ """)
+ return name
+
+ yield make
+ for qualified in created:
+ admin.command(f"DROP TABLE IF EXISTS {qualified}")
+ admin.close()
+
+ def _read(self, table: str, host_limits: dict, **source_kwargs) -> pa.Table:
+ @contextmanager
+ def tunnel():
+ yield (settings.CLICKHOUSE_HOST, 8123)
+
+ real_query_settings = ch_module._query_settings
+ with (
+ patch.object(
+ ch_module, "_query_settings", lambda chunk_size: {**real_query_settings(chunk_size), **host_limits}
+ ),
+ patch.object(ch_module, "PAGED_READ_INITIAL_ROWS", 16),
+ patch.object(ch_module, "PAGED_READ_MIN_ROWS", 4),
+ ):
+ response = ch_module.clickhouse_source(
+ tunnel=tunnel,
+ user=settings.CLICKHOUSE_USER,
+ password=settings.CLICKHOUSE_PASSWORD,
+ database=settings.CLICKHOUSE_DATABASE,
+ secure=False,
+ verify=False,
+ table_names=[table],
+ logger=MagicMock(),
+ **source_kwargs,
+ )
+ items = response.items()
+ assert not isinstance(items, AsyncIterable)
+ return pa.concat_tables(list(items))
+
+ @pytest.mark.parametrize(
+ "last_value, expected_ids",
+ [
+ pytest.param(None, list(range(30)), id="first_sync"),
+ pytest.param(datetime.fromtimestamp(_BASE_NANOS // 10**9, tz=UTC), list(range(3, 30)), id="resume"),
+ ],
+ )
+ def test_incremental_sync_pages_through_a_result_cap_in_cursor_order(self, make_table, last_value, expected_ids):
+ rows = self._read(
+ make_table("id"),
+ self._HOST_LIMITS,
+ should_use_incremental_field=True,
+ incremental_field="ts",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value=last_value,
+ )
+
+ assert rows.column("ts").equals(rows.sort_by("ts").column("ts"))
+ assert rows.sort_by("id").column("id").to_pylist() == expected_ids
+
+ @pytest.mark.parametrize(
+ "order_by",
+ [pytest.param("(grp, ts)", id="string_and_datetime_key"), pytest.param("id", id="numeric_key")],
+ )
+ def test_full_refresh_pages_through_a_result_cap_on_the_sorting_key(self, make_table, order_by):
+ rows = self._read(
+ make_table(order_by),
+ self._HOST_LIMITS,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ assert rows.sort_by("id").column("id").to_pylist() == list(range(30))
+
+ @pytest.mark.parametrize(
+ "host_limits, order_by, should_use_incremental_field",
+ [
+ pytest.param({**_HOST_LIMITS, "max_result_rows": 2}, "id", True, id="cursor_ties_above_cap_at_min_page"),
+ pytest.param(_HOST_LIMITS, "tuple()", False, id="full_refresh_without_sorting_key"),
+ ],
+ )
+ def test_raises_the_limit_error_when_paging_cannot_fit_under_it(
+ self, make_table, host_limits, order_by, should_use_incremental_field
+ ):
+ with pytest.raises(ClickHouseError, match="TOO_MANY_ROWS_OR_BYTES"):
+ self._read(
+ make_table(order_by),
+ host_limits,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field="ts" if should_use_incremental_field else None,
+ incremental_field_type=IncrementalFieldType.Timestamp if should_use_incremental_field else None,
+ db_incremental_field_last_value=None,
+ )
+
class TestClickHouseReconcileSchemaMetadata(BaseTest):
"""The ClickHouse-specific override that routes through the shared reconcile helper."""