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(data-modeling): fall back to the untouched query when the DESCRIBE probe fails (#91130)

Andy Zhao4fa8e10ae2e9
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 5589fe2137da..c28a0ef2bb20 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -29,7 +29,10 @@ from posthog.ph_client import feature_enabled_or_false
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.settings.base_variables import TEST
from posthog.sync import database_sync_to_async_pool
-from posthog.temporal.common.clickhouse import get_client as get_clickhouse_client
+from posthog.temporal.common.clickhouse import (
+ ClickHouseError,
+ get_client as get_clickhouse_client,
+)
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from posthog.temporal.data_modeling.activities.incremental_write import (
@@ -101,6 +104,30 @@ def _print_describe_variant(
return print_prepared_ast(downgraded, context=context, dialect="clickhouse", settings=settings, stack=[])
+def _print_untouched(
+ prepared_query: ast.SelectQuery | ast.SelectSetQuery, context: HogQLContext, settings: HogQLGlobalSettings
+) -> str:
+ return print_prepared_ast(prepared_query, context=context, dialect="clickhouse", settings=settings, stack=[])
+
+
+async def _describe_columns(
+ printed: str, query_parameters: dict[str, typing.Any], query_settings: dict[str, str] | None
+) -> dict[str, str]:
+ async with _clickhouse_query_semaphore, get_clickhouse_client() as client:
+ async with client.apost_query(
+ query=f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw",
+ query_parameters=query_parameters,
+ query_id=str(uuid.uuid4()),
+ settings=query_settings,
+ ) as ch_response:
+ table_describe_response = await ch_response.content.read()
+ columns: dict[str, str] = {}
+ for line in table_describe_response.decode("utf-8").splitlines():
+ column_name, ch_type = line.strip().split("\t")
+ columns[column_name] = ch_type
+ return columns
+
+
CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000
DELTA_TABLE_RETENTION_HOURS = 24
@@ -540,7 +567,6 @@ async def hogql_table(
printed = await database_sync_to_async_pool(_print_describe_variant)(prepared_hogql_query, context, settings)
- table_describe_query = f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw"
arrow_type_conversion: dict[str, tuple[str, tuple[ast.Constant, ...]]] = {
"DateTime": ("toTimeZone", (ast.Constant(value="UTC"),)),
"Nullable(Nothing)": ("toNullableString", ()),
@@ -565,21 +591,23 @@ async def hogql_table(
iter([call_tuple for uat, call_tuple in arrow_type_conversion.items() if uat.lower() in ch_type.lower()])
)
+ try:
+ described_columns = await _describe_columns(printed, context.values, DESCRIBE_QUERY_SETTINGS)
+ except ClickHouseError as error:
+ # ClickHouse cannot plan some shapes once GLOBAL is gone, such as an IN subquery inside an
+ # aggregate function. The untouched query is the one that runs, so it always describes.
+ await logger.awarning(
+ "DESCRIBE with local subqueries failed, retrying with the untouched query", error=str(error)
+ )
+ untouched = await database_sync_to_async_pool(_print_untouched)(prepared_hogql_query, context, settings)
+ described_columns = await _describe_columns(untouched, context.values, None)
+
query_typings: list[tuple[str, str, tuple[str, tuple[ast.Constant, ...]] | None]] = []
- async with _clickhouse_query_semaphore, get_clickhouse_client() as client:
- async with client.apost_query(
- query=table_describe_query,
- query_parameters=context.values,
- query_id=str(uuid.uuid4()),
- settings=DESCRIBE_QUERY_SETTINGS,
- ) as ch_response:
- table_describe_response = await ch_response.content.read()
- for line in table_describe_response.decode("utf-8").splitlines():
- column_name, ch_type = line.strip().split("\t")
- if _needs_conversion(ch_type):
- query_typings.append((column_name, ch_type, get_call_tuple(ch_type)))
- else:
- query_typings.append((column_name, ch_type, None))
+ for column_name, ch_type in described_columns.items():
+ if _needs_conversion(ch_type):
+ query_typings.append((column_name, ch_type, get_call_tuple(ch_type)))
+ else:
+ query_typings.append((column_name, ch_type, None))
has_type_to_convert = any(call_tuple is not None for _, _, call_tuple in query_typings)
if has_type_to_convert:
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 71f813f7cf61..a17c0c2f90cb 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -20,6 +20,7 @@ from posthog.hogql.resolver import ResolverFactory
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
+from posthog.temporal.common.clickhouse import ClickHouseError
from posthog.temporal.data_modeling.activities import (
CreateDataModelingJobInputs,
FailMaterializationInputs,
@@ -1641,6 +1642,8 @@ class _EmptyArrowClient:
self.schema_query_calls = 0
self.describe_settings: dict[str, str] | None = None
self.describe_query: str | None = None
+ self.describe_calls: list[tuple[str, dict[str, str] | None]] = []
+ self.reject_describe_with_settings = False
self.arrow_query: str | None = None
async def astream_query_as_arrow(
@@ -1668,6 +1671,9 @@ class _EmptyArrowClient:
settings: dict[str, str] | None = None,
) -> AsyncIterator[Any]:
if query.startswith("DESCRIBE TABLE"):
+ self.describe_calls.append((query, settings))
+ if self.reject_describe_with_settings and settings is not None:
+ raise ClickHouseError("Code: 8. DB::Exception: Cannot find column in source stream", query=query)
self.describe_settings = settings
self.describe_query = query
body = self.describe_body
@@ -1736,6 +1742,28 @@ class TestHogqlTableDescribeSettings:
assert client.describe_query is not None and global_function not in client.describe_query
assert client.arrow_query is not None and global_function in client.arrow_query
+ async def test_describe_probe_falls_back_to_the_untouched_query(self, ateam: Team) -> None:
+ client = _EmptyArrowClient(pa.schema([pa.field("distinct_id", pa.string())]))
+ client.describe_body = b"distinct_id\tString\n"
+ client.reject_describe_with_settings = True
+ query = "SELECT distinct_id FROM events WHERE distinct_id IN (SELECT distinct_id FROM events WHERE event = 'x')"
+
+ @contextlib.asynccontextmanager
+ async def fake_get_client(**kwargs: Any) -> AsyncIterator[_EmptyArrowClient]:
+ yield client
+
+ with unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client
+ ):
+ batches = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]
+
+ assert [settings for _, settings in client.describe_calls] == [
+ {"distributed_product_mode": "allow", "prefer_global_in_and_join": "0"},
+ None,
+ ]
+ assert "globalIn(" in client.describe_calls[1][0]
+ assert batches[0][1] == [("distinct_id", "String")]
+
class _SlowDescribeClient(_EmptyArrowClient):
describe_body = b"ts\tDateTime\n"