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): bind clickhouse datetime cursors exactly (#106727)

Daniel RC7484848424b8
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 8bab555bf3d4..d84607373af4 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
@@ -8,6 +8,7 @@ import threading
import collections
from collections.abc import Callable, Generator, Iterator, Sequence
from contextlib import _GeneratorContextManager, closing
+from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Optional
import pyarrow as pa
@@ -1159,7 +1160,7 @@ def _get_incremental_row_count(
try:
result = client.query(
query,
- parameters={"last_value": last_value},
+ parameters={"last_value": _last_value_param(last_value, incremental_field_type)},
settings={"max_execution_time": 30},
)
except ClickHouseError as e:
@@ -1316,6 +1317,10 @@ def _project_columns(
return projected or columns
+_DATETIME_CURSOR_TYPES = (IncrementalFieldType.DateTime, IncrementalFieldType.Timestamp)
+_UNIX_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
+
+
def _last_value_expr(incremental_field_type: Optional[IncrementalFieldType]) -> str:
"""SQL expression binding the `last_value` parameter for the incremental cursor.
@@ -1328,9 +1333,28 @@ def _last_value_expr(incremental_field_type: Optional[IncrementalFieldType]) ->
"""
if incremental_field_type == IncrementalFieldType.Date:
return "toDate32(%(last_value)s)"
+ if incremental_field_type in _DATETIME_CURSOR_TYPES:
+ return "fromUnixTimestamp64Micro(%(last_value)s)"
return "%(last_value)s"
+def _last_value_param(last_value: Any, incremental_field_type: Optional[IncrementalFieldType]) -> Any:
+ """The `last_value` parameter for `_last_value_expr`.
+
+ clickhouse-connect binds a datetime as a whole-second string, which ClickHouse then parses in
+ the column's timezone. Epoch microseconds keep the sub-second part and name one exact instant.
+ A naive cursor is UTC, like the naive Arrow timestamps it came from.
+ """
+ if incremental_field_type not in _DATETIME_CURSOR_TYPES:
+ return last_value
+ if isinstance(last_value, datetime):
+ instant = last_value if last_value.tzinfo is not None else last_value.replace(tzinfo=UTC)
+ return (instant - _UNIX_EPOCH) // timedelta(microseconds=1)
+ if isinstance(last_value, int | float) and not isinstance(last_value, bool):
+ return int(last_value * 1_000_000)
+ return last_value
+
+
def _build_conditions(
*,
should_use_incremental_field: bool,
@@ -1719,7 +1743,7 @@ def clickhouse_source(
last_value = db_incremental_field_last_value
if last_value is None and incremental_field_type is not None:
last_value = incremental_type_to_initial_value(incremental_field_type)
- parameters["last_value"] = last_value
+ parameters["last_value"] = _last_value_param(last_value, incremental_field_type)
def read_batches() -> Generator[pa.RecordBatch]:
"""Read the table in one query, or in pages of key ranges once a host limit rejects that.
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 b00a125d906a..cadcddb7e62e 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
@@ -1754,6 +1754,84 @@ class TestPagedReadFallback:
)
+class TestIncrementalResumeAgainstServer:
+ @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(ts_type: str) -> str:
+ name = f"cursor_resume_{uuid.uuid4().hex}"
+ qualified = f"{settings.CLICKHOUSE_DATABASE}.{name}"
+ created.append(qualified)
+ admin.command(f"CREATE TABLE {qualified} (id UInt64, ts {ts_type}) ENGINE = MergeTree ORDER BY id")
+ admin.command(f"""
+ INSERT INTO {qualified}
+ SELECT number, fromUnixTimestamp64Nano(toInt64(1767225600000000000 + 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()
+
+ @pytest.mark.parametrize(
+ "ts_type, last_value, expected_ids",
+ [
+ pytest.param(
+ "DateTime64(9, 'UTC')", datetime(2026, 1, 1, 0, 0, 0, 4, tzinfo=UTC), [27, 28, 29], id="sub_second"
+ ),
+ pytest.param(
+ "DateTime64(9, 'America/New_York')",
+ datetime(2026, 1, 1, 0, 0, 0, 4, tzinfo=UTC),
+ [27, 28, 29],
+ id="column_timezone",
+ ),
+ pytest.param("DateTime64(9)", datetime(2026, 1, 1, 0, 0, 0, 4), [27, 28, 29], id="naive_cursor"),
+ pytest.param(
+ "DateTime('America/New_York')",
+ datetime(2025, 12, 31, 23, 59, 59, tzinfo=UTC),
+ list(range(30)),
+ id="datetime_column_timezone",
+ ),
+ pytest.param("DateTime64(9, 'UTC')", 1767225600, list(range(3, 30)), id="epoch_seconds_cursor"),
+ ],
+ )
+ def test_incremental_resume_reads_only_rows_after_the_cursor(self, make_table, ts_type, last_value, expected_ids):
+ @contextmanager
+ def tunnel():
+ yield (settings.CLICKHOUSE_HOST, 8123)
+
+ 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=[make_table(ts_type)],
+ should_use_incremental_field=True,
+ incremental_field="ts",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value=last_value,
+ logger=MagicMock(),
+ )
+ items = response.items()
+ assert not isinstance(items, AsyncIterable)
+ rows = pa.concat_tables(list(items))
+
+ assert rows.sort_by("id").column("id").to_pylist() == expected_ids
+ assert response.rows_to_sync == len(expected_ids)
+
+
class TestClickHouseReconcileSchemaMetadata(BaseTest):
"""The ClickHouse-specific override that routes through the shared reconcile helper."""