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.

perf(data-modeling): stop DESCRIBE from scanning subqueries (#90544)

Andy Zhao705da0a7f233
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 1fc1934c738b..5589fe2137da 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -20,6 +20,7 @@ from posthog.hogql.database.database import Database
from posthog.hogql.errors import ParsingError
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
+from posthog.hogql.visitor import CloningVisitor
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.exceptions_capture import capture_exception
@@ -67,6 +68,39 @@ from products.warehouse_sources.backend.facade.temporal import AccountPropertyRo
LOGGER = get_logger(__name__)
MB_100_IN_BYTES = 100 * 1000 * 1000
+
+# ClickHouse builds every GLOBAL IN subquery as a temporary table while it plans a query, and
+# DESCRIBE plans the query too, so the schema probe scans the source tables just to return column
+# types. The probe therefore prints a copy of the query with GLOBAL IN downgraded to plain IN and
+# runs with the two settings that would add GLOBAL back pinned off (the cluster profile sets
+# distributed_product_mode=global). Joins keep their GLOBAL prefix: the resolver adds it to
+# events-to-S3 join chains to work around a ClickHouse bug, not for cost. The materialization query
+# itself is printed from the untouched AST.
+DESCRIBE_QUERY_SETTINGS = {"distributed_product_mode": "allow", "prefer_global_in_and_join": "0"}
+
+_LOCAL_COMPARE_OPS = {
+ ast.CompareOperationOp.GlobalIn: ast.CompareOperationOp.In,
+ ast.CompareOperationOp.GlobalNotIn: ast.CompareOperationOp.NotIn,
+}
+
+
+class _DowngradeGlobalIn(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False, clear_locations=False)
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> ast.CompareOperation:
+ cloned = super().visit_compare_operation(node)
+ cloned.op = _LOCAL_COMPARE_OPS.get(cloned.op, cloned.op)
+ return cloned
+
+
+def _print_describe_variant(
+ prepared_query: ast.SelectQuery | ast.SelectSetQuery, context: HogQLContext, settings: HogQLGlobalSettings
+) -> str:
+ downgraded = _DowngradeGlobalIn().visit(prepared_query)
+ return print_prepared_ast(downgraded, context=context, dialect="clickhouse", settings=settings, stack=[])
+
+
CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000
DELTA_TABLE_RETENTION_HOURS = 24
@@ -504,13 +538,7 @@ async def hogql_table(
if prepared_hogql_query is None:
raise EmptyHogQLResponseColumnsError()
- printed = await database_sync_to_async_pool(print_prepared_ast)(
- prepared_hogql_query,
- context=context,
- dialect="clickhouse",
- settings=settings,
- stack=[],
- )
+ 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, ...]]] = {
@@ -540,7 +568,10 @@ async def hogql_table(
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())
+ 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():
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 59c68be855c0..71f813f7cf61 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -1,6 +1,6 @@
import asyncio
import contextlib
-from collections.abc import AsyncIterator, Collection, Iterable
+from collections.abc import AsyncIterator, Callable, Collection, Iterable
from dataclasses import replace
from io import BytesIO
from typing import Any, cast
@@ -18,7 +18,7 @@ import pyarrow.parquet as pq
from posthog.hogql.resolver import ResolverFactory
-from posthog.models import User
+from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from posthog.temporal.data_modeling.activities import (
CreateDataModelingJobInputs,
@@ -1639,17 +1639,37 @@ class _EmptyArrowClient:
self.schema = schema
self.arrow_query_calls = 0
self.schema_query_calls = 0
-
- async def astream_query_as_arrow(self, query, *data, query_parameters=None, query_id=None, on_schema=None):
+ self.describe_settings: dict[str, str] | None = None
+ self.describe_query: str | None = None
+ self.arrow_query: str | None = None
+
+ async def astream_query_as_arrow(
+ self,
+ query: str,
+ *data: Any,
+ query_parameters: dict[str, Any] | None = None,
+ query_id: str | None = None,
+ on_schema: Callable[[pa.Schema], None] | None = None,
+ ) -> AsyncIterator[pa.RecordBatch]:
self.arrow_query_calls += 1
+ self.arrow_query = query
if on_schema is not None:
on_schema(self.schema)
return
yield # type: ignore[unreachable] # makes this an async generator that yields no batches
@contextlib.asynccontextmanager
- async def apost_query(self, query, *data, query_parameters=None, query_id=None):
+ async def apost_query(
+ self,
+ query: str,
+ *data: Any,
+ query_parameters: dict[str, Any] | None = None,
+ query_id: str | None = None,
+ settings: dict[str, str] | None = None,
+ ) -> AsyncIterator[Any]:
if query.startswith("DESCRIBE TABLE"):
+ self.describe_settings = settings
+ self.describe_query = query
body = self.describe_body
else:
self.schema_query_calls += 1
@@ -1688,6 +1708,35 @@ class TestHogqlTableEmptyResults:
assert client.schema_query_calls == 0
+class TestHogqlTableDescribeSettings:
+ @pytest.mark.parametrize(
+ "operator,global_function",
+ [("IN", "globalIn("), ("NOT IN", "globalNotIn(")],
+ )
+ async def test_describe_probe_drops_global_subqueries(
+ self, ateam: Team, operator: str, global_function: str
+ ) -> None:
+ client = _EmptyArrowClient(pa.schema([pa.field("distinct_id", pa.string())]))
+ client.describe_body = b"distinct_id\tString\n"
+ query = (
+ f"SELECT distinct_id FROM events WHERE distinct_id {operator} "
+ "(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
+ ):
+ _ = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]
+
+ assert client.describe_settings == {"distributed_product_mode": "allow", "prefer_global_in_and_join": "0"}
+ 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
+
+
class _SlowDescribeClient(_EmptyArrowClient):
describe_body = b"ts\tDateTime\n"
@@ -1696,9 +1745,18 @@ class _SlowDescribeClient(_EmptyArrowClient):
self.describe_seconds = describe_seconds
@contextlib.asynccontextmanager
- async def apost_query(self, query, *data, query_parameters=None, query_id=None):
+ async def apost_query(
+ self,
+ query: str,
+ *data: Any,
+ query_parameters: dict[str, Any] | None = None,
+ query_id: str | None = None,
+ settings: dict[str, str] | None = None,
+ ) -> AsyncIterator[Any]:
await asyncio.sleep(self.describe_seconds)
- async with super().apost_query(query, *data, query_parameters=query_parameters, query_id=query_id) as response:
+ async with super().apost_query(
+ query, *data, query_parameters=query_parameters, query_id=query_id, settings=settings
+ ) as response:
yield response