: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
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.pyindex 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 Databasefrom posthog.hogql.errors import ParsingErrorfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast+from posthog.hogql.visitor import CloningVisitorfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.exceptions_capture import capture_exception@@ -67,6 +68,39 @@ from products.warehouse_sources.backend.facade.temporal import AccountPropertyRoLOGGER = 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 * 1000DELTA_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.pyindex 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 asyncioimport contextlib-from collections.abc import AsyncIterator, Collection, Iterable+from collections.abc import AsyncIterator, Callable, Collection, Iterablefrom dataclasses import replacefrom io import BytesIOfrom typing import Any, cast@@ -18,7 +18,7 @@ import pyarrow.parquet as pqfrom posthog.hogql.resolver import ResolverFactory-from posthog.models import User+from posthog.models import Team, Userfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_modeling.activities import (CreateDataModelingJobInputs,@@ -1639,17 +1639,37 @@ class _EmptyArrowClient:self.schema = schemaself.arrow_query_calls = 0self.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 = queryif on_schema is not None:on_schema(self.schema)returnyield # 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 = querybody = self.describe_bodyelse: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