: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
feat(batch-exports): execute hogql queries in internal stage activity (#72508)
Rossacb40ffac2c3
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex f96d69b1a777..d37a33b6b593 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -361,10 +361,15 @@ class ClickHouseClient:has_format_placeholders = re.search(r"(?<!{){[^{}]*}(?!})|{{[^{}]*}}", query)format_parameters = {k: encode_clickhouse_data(v).decode("utf-8") for k, v in query_parameters.items()}- query = query % format_parametersif has_format_placeholders:+ # Escape any curly brackets `{` or `}` in the format parameters so they are not parsed+ # as format placeholders+ escaped_parameters = {k: v.replace("{", "{{").replace("}", "}}") for k, v in format_parameters.items()}+ query = query % escaped_parametersquery = KeywordOnlyFormatter().format(query, **format_parameters)+ else:+ query = query % format_parametersreturn query@@ -603,7 +608,13 @@ class ClickHouseClient:return Noneasync def execute_query_with_summary(- self, query, *data, query_parameters=None, query_id: str | None = None, timeout: float | None = None+ self,+ query,+ *data,+ query_parameters=None,+ query_id: str | None = None,+ timeout: float | None = None,+ settings: dict[str, str] | None = None,) -> dict[str, typing.Any] | None:"""Execute the given query and return ClickHouse's query summary, if available.@@ -618,6 +629,10 @@ class ClickHouseClient:this for queries whose client-bound response is small — e.g. `INSERT INTO FUNCTIONs3(...)`, whose response body is empty (rows go to S3, counts come back in theheader) — so the buffering is negligible regardless of `http_response_buffer_size`.++ Arguments:+ settings: Extra ClickHouse settings to apply to this query, sent as+ query-string parameters."""async with self.apost_query(query,@@ -625,7 +640,7 @@ class ClickHouseClient:query_parameters=query_parameters,query_id=query_id,timeout=timeout,- settings={"wait_end_of_query": "1"},+ settings={**(settings or {}), "wait_end_of_query": "1"},) as response:summary = response.headers.get("X-ClickHouse-Summary")if not summary:diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.pyindex d079b3163046..2e3d10f1549c 100644--- a/posthog/temporal/tests/test_clickhouse.py+++ b/posthog/temporal/tests/test_clickhouse.py@@ -236,6 +236,31 @@ def test_post_query_disables_http_compression(clickhouse_client):{"event": "index_{something}", "another": "event"},"select * from events where event = 'index_{something}' and event != 'event'",),+ # a value containing an unbalanced brace used to crash the format pass+ (+ "select * from events where event = %(event)s and event != {another}",+ {"event": "brace {", "another": "event"},+ "select * from events where event = 'brace {' and event != 'event'",+ ),+ # a JSON string value used to be mangled by the format pass+ (+ "select * from events where properties = %(props)s and event != {another}",+ {"props": '{"a": 1}', "another": "event"},+ "select * from events where properties = '{\"a\": 1}' and event != 'event'",+ ),+ # a value matching another parameter's name must not be substituted again+ (+ "select * from events where event = %(event)s and event != {another}",+ {"event": "literal {another}", "another": "event"},+ "select * from events where event = 'literal {another}' and event != 'event'",+ ),+ # the INSERT INTO FUNCTION s3(...) shape used by batch exports: intentional escapes+ # collapse while a value containing '%' and braces survives verbatim+ (+ "INSERT INTO FUNCTION s3('bucket/export_{{_partition_id}}.arrow') SELECT %(v)s SETTINGS log_comment={log_comment}",+ {"v": '100%-{"a": 1}', "log_comment": "comment"},+ "INSERT INTO FUNCTION s3('bucket/export_{_partition_id}.arrow') SELECT '100%-{\"a\": 1}' SETTINGS log_comment='comment'",+ ),],)def test_prepare_query(clickhouse_client, query, query_parameters, expected):diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.pynew file mode 100644index 000000000000..0ab4b147756f--- /dev/null+++ b/products/batch_exports/backend/hogql_source.py@@ -0,0 +1,39 @@+"""Helpers for batch exports powered by a user-defined HogQL query.++This module must stay importable by both the API layer and the Temporal worker, so it+should not import from `products.batch_exports.backend.temporal` or any DRF code.+"""++from posthog.hogql import ast+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.placeholders import find_placeholders+++class UnsupportedHogQLQueryError(Exception):+ """Raised when a HogQL query cannot be used to power a batch export."""+++def parse_hogql_select_for_batch_export(hogql_query: str) -> ast.SelectQuery | ast.SelectSetQuery:+ """Parse a HogQL SELECT query intended to power a batch export.++ Placeholders are not currently supported in batch exports, they will be coming soon...++ Raises:+ UnsupportedHogQLQueryError: If the query cannot be parsed as a SELECT or+ contains placeholders, which batch exports have no way to resolve.+ InternalHogQLError: Left to propagate. An internal HogQL engine error is our+ bug, not a problem with the user's query, so it should surface as an error+ (and get alerted on) rather than be reported back as an unsupported query.+ """+ try:+ parsed = parse_select(hogql_query)+ except ExposedHogQLError as e:+ raise UnsupportedHogQLQueryError(f"Failed to parse HogQL query: {e}") from e++ # TODO: support placeholder expressions in batch exports+ placeholders = find_placeholders(parsed)+ if placeholders.has_filters or placeholders.placeholder_fields or placeholders.placeholder_expressions:+ raise UnsupportedHogQLQueryError("Placeholders are not supported in batch export queries")++ return parseddiff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex d673613f09f5..472e72e23689 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -158,6 +158,7 @@ class BatchExportModel:name: strschema: BatchExportSchema | Nonefilters: list[dict[str, str | list[str] | None]] | None = None+ hogql_query: str | None = None@dataclassdiff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex d2a7184ed911..3fee07bae219 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -581,8 +581,9 @@ async def _write_batch_export_record_batches_to_internal_stage(# Some tests create data in the future, so we do not check this.raise DataIntervalEndInFutureError(end_at)- with TRACER.start_as_current_span("batch_export.stage.wait_for_delta"):- await wait_for_delta_past_data_interval_end(end_at, delta)+ if not isinstance(query_or_model, RecordBatchModel) or query_or_model.wait_for_data_interval_end:+ with TRACER.start_as_current_span("batch_export.stage.wait_for_delta"):+ await wait_for_delta_past_data_interval_end(end_at, delta)done_ranges: list[tuple[dt.datetime, dt.datetime]] = []async with get_client(@@ -619,8 +620,10 @@ async def _write_batch_export_record_batches_to_internal_stage(s3_secret=aws_secret_access_key,num_partitions=num_partitions or settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS,)+ query_settings = query_or_model.get_clickhouse_request_settings()else:query = query_or_model+ query_settings = {}base_s3_staging_folder = get_base_s3_staging_folder(batch_export_id=batch_export_id,@@ -644,7 +647,7 @@ async def _write_batch_export_record_batches_to_internal_stage(try:with TRACER.start_as_current_span("batch_export.stage.clickhouse_query") as query_span:- written_rows = await _execute_query(client, query, query_parameters)+ written_rows = await _execute_query(client, query, query_parameters, query_settings)if written_rows is not None:query_span.set_attribute("batch_export.stage.written_rows", written_rows)except ClickHouseError:@@ -673,7 +676,12 @@ def _written_rows_from_summary(summary: dict[str, typing.Any] | None) -> int | Nreturn None-async def _execute_query(client: ClickHouseClient, query: str, query_parameters: dict[str, typing.Any]) -> int | None:+async def _execute_query(+ client: ClickHouseClient,+ query: str,+ query_parameters: dict[str, typing.Any],+ query_settings: dict[str, str] | None = None,+) -> int | None:"""Execute the batch exports query and wait for it to complete.If the query takes longer than 300 seconds, we time out and wait for the query to complete by checking the query log@@ -689,7 +697,7 @@ async def _execute_query(client: ClickHouseClient, query: str, query_parameters:with log_query_duration(logger=logger, query_id=query_id, query_type="insert_into_internal_stage"):try:summary = await client.execute_query_with_summary(- query, query_parameters=query_parameters, query_id=query_id, timeout=300+ query, query_parameters=query_parameters, query_id=query_id, timeout=300, settings=query_settings)except ClickHouseClientTimeoutError:logger.warning(diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex fe1bbf0e95d2..877c5f15c40f 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -3,6 +3,7 @@ import uuidimport typingimport datetime as dt+from posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.hogql import ast@@ -17,6 +18,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryError, parse_hogql_select_for_batch_exportfrom products.batch_exports.backend.service import BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal import sqlfrom products.batch_exports.backend.temporal.metrics import log_query_duration@@ -28,14 +30,27 @@ QueryParameters = dict[str, typing.Any]BatchExportDateRange = tuple[dt.datetime | None, dt.datetime]+def _as_clickhouse_request_settings(query_settings: HogQLQuerySettings) -> dict[str, str]:+ """Render HogQL query settings as ClickHouse HTTP-interface settings."""+ return {+ name: "1" if value is True else "0" if value is False else str(value)+ for name, value in query_settings.model_dump(exclude_none=True).items()+ }++class RecordBatchModel(abc.ABC):"""Base class for models that can be produced as record batches.Attributes:team_id: The ID of the team we are producing records for.batch_export_id: The ID of the batch export we are producing records for.+ wait_for_data_interval_end: Whether to wait before querying until the data+ interval end has passed and replication lag past it has settled. Models+ without data interval semantics query "as of now" and skip the wait."""+ wait_for_data_interval_end: bool = True+def __init__(self, team_id: int, batch_export_id: str | None = None):self.team_id = team_idself.batch_export_id = batch_export_id@@ -48,6 +63,11 @@ class RecordBatchModel(abc.ABC):team_id=team.id,enable_select_queries=True,limit_top_select=False,+ # A bit of a hack: the query references neither half of this, but both are required:+ # - we need to call `get_log_comment` in order to tag the queries+ # - we need to pass non-empty `values` to `ClickHouseClient.prepare_query` to avoid it returning+ # early and not resolving the `{{_partition_id}}` and `%%` escapes in the s3 function+ # call.values={"log_comment": self.get_log_comment(),},@@ -57,6 +77,11 @@ class RecordBatchModel(abc.ABC):return contextdef get_log_comment(self) -> str:+ """Tag this export's queries, and return the tags as a log comment.++ The ClickHouse client reads these tags back to set `log_comment` on the requests+ it sends, which is what ties a row in `system.query_log` to its batch export.+ """tags = query_tagging.get_query_tags()tags.team_id = self.team_idif self.batch_export_id:@@ -66,13 +91,47 @@ class RecordBatchModel(abc.ABC):return tags.to_json()@abc.abstractmethod+ def get_hogql_query(+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ """Return the HogQL query to export, scoped to the given data interval."""+ raise NotImplementedError++ def get_clickhouse_request_settings(self) -> dict[str, str]:+ """ClickHouse settings to apply to this model's queries.++ These are sent as query parameters rather than written into the query, so+ we avoid having to manipulate a `SETTINGS` clause as a string. Models that bake+ their settings onto the query AST (letting the printer render them) need none.+ """+ return {}++ async def _print_query(+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime, output_format: str | None+ ) -> tuple[str, QueryParameters]:+ """Transpile the model's HogQL query to ClickHouse SQL, returning it with its parameters."""+ hogql_query = self.get_hogql_query(data_interval_start, data_interval_end)+ context = await self.get_hogql_context()++ prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(+ hogql_query, context=context, dialect="clickhouse", stack=[]+ )+ assert prepared_hogql_query is not None+ if output_format is not None:+ context.output_format = output_format+ # Printing can lazily read from Postgres (e.g. the events table checks the+ # new-events-schema instance setting), so it must run off the event loop.+ printed = await database_sync_to_async(print_prepared_ast)(+ prepared_hogql_query, context=context, dialect="clickhouse", stack=[]+ )+ return printed, context.values+async def as_query_with_parameters(self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime) -> tuple[Query, QueryParameters]:"""Produce a printed query and any necessary ClickHouse query parameters."""- raise NotImplementedError+ return await self._print_query(data_interval_start, data_interval_end, output_format="ArrowStream")- @abc.abstractmethodasync def as_insert_into_s3_query_with_parameters(self,data_interval_start: dt.datetime | None,@@ -82,8 +141,14 @@ class RecordBatchModel(abc.ABC):s3_secret: str | None,num_partitions: int,) -> tuple[Query, QueryParameters]:- """Produce a printed query and any necessary ClickHouse query parameters."""- raise NotImplementedError+ """Produce an `INSERT INTO FUNCTION s3(...)` query and its ClickHouse parameters."""+ printed, parameters = await self._print_query(data_interval_start, data_interval_end, output_format=None)+ s3_function = sql.get_s3_function_call(s3_folder, s3_key, s3_secret, num_partitions)+ insert_query = f"""+INSERT INTO FUNCTION {s3_function}+{printed}+"""+ return insert_query, parametersclass SessionsRecordBatchModel(RecordBatchModel):@@ -136,64 +201,6 @@ class SessionsRecordBatchModel(RecordBatchModel):return hogql_query- async def as_query_with_parameters(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime- ) -> tuple[Query, QueryParameters]:- """Produce a printed query and any necessary ClickHouse query parameters."""- hogql_query = self.get_hogql_query(data_interval_start, data_interval_end)- context = await self.get_hogql_context()-- prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(- hogql_query, context=context, dialect="clickhouse", stack=[]- )- assert prepared_hogql_query is not None- context.output_format = "ArrowStream"- printed = print_prepared_ast(- prepared_hogql_query,- context=context,- dialect="clickhouse",- stack=[],- )- return printed, context.values-- async def as_insert_into_s3_query_with_parameters(- self,- data_interval_start: dt.datetime | None,- data_interval_end: dt.datetime,- s3_folder: str,- s3_key: str | None,- s3_secret: str | None,- num_partitions: int,- ) -> tuple[Query, QueryParameters]:- """Produce a printed query and any necessary ClickHouse query parameters."""- hogql_query = self.get_hogql_query(data_interval_start, data_interval_end)- context = await self.get_hogql_context()-- prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(- hogql_query, context=context, dialect="clickhouse", stack=[]- )- assert prepared_hogql_query is not None- printed = print_prepared_ast(- prepared_hogql_query,- context=context,- dialect="clickhouse",- stack=[],- )-- log_comment = "log_comment={log_comment}"- if "settings" not in printed.lower():- log_comment = " SETTINGS log_comment={log_comment}"- else:- log_comment = ", " + log_comment-- s3_function = sql.get_s3_function_call(s3_folder, s3_key, s3_secret, num_partitions)- insert_query = f"""-INSERT INTO FUNCTION {s3_function}-{printed}{log_comment}-"""-- return insert_query, context.values-def get_backfill_info_hogql_query(self, start_at: dt.datetime | None, end_at: dt.datetime | None) -> ast.SelectQuery:@@ -305,6 +312,40 @@ INSERT INTO FUNCTION {s3_function}return min_timestamp, record_count+class HogQLQueryRecordBatchModel(RecordBatchModel):+ """A model to produce record batches from an arbitrary HogQL query.++ The query is stored as a raw HogQL string and transpiled to ClickHouse SQL at run+ time, so it stays resilient to printer changes.++ TODO: Data interval bounds are accepted to satisfy the base class contract but ignored: the+ query has no interval semantics yet.+ """++ # The query is executed as-is with no data interval, so there is nothing to wait for.+ wait_for_data_interval_end = False++ def __init__(self, team_id: int, hogql_query: str, batch_export_id: str | None = None):+ super().__init__(team_id=team_id, batch_export_id=batch_export_id)+ self.hogql_query = hogql_query++ def get_hogql_query(+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ """Return the parsed HogQL query used for this model.++ The data interval bounds are ignored: the query is exported as-is (see the class+ docstring). They are accepted to satisfy the base class contract.+ """+ return parse_hogql_select_for_batch_export(self.hogql_query)++ def get_clickhouse_request_settings(self) -> dict[str, str]:+ # Sent with the request instead of set on the query AST, because the user query may+ # not parse to a simple `ast.SelectQuery` (e.g. a UNION parses to an+ # `ast.SelectSetQuery`, which has no `settings` field to attach these to).+ return _as_clickhouse_request_settings(sql.HogQLQueryBatchExportSettings())++def resolve_batch_exports_model(team_id: int,batch_export_model: BatchExportModel | None = None,@@ -318,7 +359,7 @@ def resolve_batch_exports_model(be removed."""model: BatchExportModel | BatchExportSchema | None = None- record_batch_model = None+ record_batch_model: RecordBatchModel | None = Noneif batch_export_schema is None:model = batch_export_modelif model is not None:@@ -329,6 +370,12 @@ def resolve_batch_exports_model(if model_name == "sessions":record_batch_model = SessionsRecordBatchModel(team_id=team_id, batch_export_id=batch_export_id)+ elif model_name == "hogql":+ if model.hogql_query is None:+ raise UnsupportedHogQLQueryError("Batch export model is 'hogql' but no HogQL query was provided")+ record_batch_model = HogQLQueryRecordBatchModel(+ team_id=team_id, hogql_query=model.hogql_query, batch_export_id=batch_export_id+ )else:model_name = "events"extra_query_parameters = Nonediff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex 1fa645a79e5b..2b74d5a7a8cc 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -543,7 +543,12 @@ def test_create_batch_export_with_custom_schema(}assert batch_export.schema == expected_schema- assert args["batch_export_model"] == {"filters": None, "name": "events", "schema": expected_schema}+ assert args["batch_export_model"] == {+ "filters": None,+ "name": "events",+ "schema": expected_schema,+ "hogql_query": None,+ }@pytest.mark.parametrize(diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.pyindex 6a210bc68310..ea379a0749fe 100644--- a/products/batch_exports/backend/tests/api/test_update.py+++ b/products/batch_exports/backend/tests/api/test_update.py@@ -751,6 +751,7 @@ def test_can_patch_hogql_query(client: HttpClient, temporal, encryption_codec, o"values": {"hogql_val_0": "test", "hogql_val_1": "Int64"},"hogql_query": "SELECT toString(uuid) AS uuid, 'test' AS test, toInt(plus(1, 1)) AS n FROM events",},+ "hogql_query": None,}diff --git a/products/batch_exports/backend/tests/temporal/conftest.py b/products/batch_exports/backend/tests/temporal/conftest.pyindex 73c4bba19def..b1bcbfb03d1b 100644--- a/products/batch_exports/backend/tests/temporal/conftest.py+++ b/products/batch_exports/backend/tests/temporal/conftest.py@@ -27,6 +27,11 @@ from posthog.temporal.tests.utils.events import generate_test_events_in_clickhoufrom products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptor+from products.batch_exports.backend.tests.temporal.utils.clickhouse import (+ truncate_events,+ truncate_persons,+ truncate_sessions,+)from products.batch_exports.backend.tests.temporal.utils.persons import (PersonDistinctId2Values,PersonValues,@@ -36,6 +41,14 @@ from products.batch_exports.backend.tests.temporal.utils.persons import ()+@pytest_asyncio.fixture+async def truncate_clickhouse_tables(clickhouse_client):+ yield+ await truncate_events(clickhouse_client)+ await truncate_persons(clickhouse_client)+ await truncate_sessions(clickhouse_client)++@pytest.fixture(scope="package", autouse=True)def clickhouse_create_db_and_tables():database = Database(diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.pyindex b1cb5b190d59..962853ba400a 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py@@ -1,5 +1,6 @@import jsonimport uuid+import randomimport typing as timport asyncioimport datetime as dt@@ -12,11 +13,19 @@ from django.conf import settingsfrom django.test.utils import override_settingsimport pyarrow as pa+import pytest_asynciofrom structlog.testing import capture_logsfrom temporalio.testing import ActivityEnvironmentfrom posthog.models.scoping import team_scope+from posthog.models.utils import uuid7+from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.clickhouse import ClickHouseClient, ClickHouseClientTimeoutError, ClickHouseQueryStatus+from posthog.temporal.tests.utils.events import (+ generate_test_events,+ insert_event_values_in_clickhouse,+ insert_sessions_in_clickhouse,+)from products.batch_exports.backend.models.batch_export import (BatchExport,@@ -41,6 +50,7 @@ from products.batch_exports.backend.tests.temporal.utils.persons import (generate_test_persons_in_clickhouse,)from products.batch_exports.backend.tests.temporal.utils.s3 import assert_files_in_s3+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuerypytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -244,10 +254,11 @@ async def _run_activity(data_interval_end: dt.datetime,exclude_events: list[str] | None = None,model: BatchExportModel | None = None,+ batch_export_id: str | None = None,) -> list[dict]:"""Get rows from the internal stage."""- batch_export_id = str(uuid.uuid4())+ batch_export_id = batch_export_id or str(uuid.uuid4())insert_inputs = BatchExportInsertIntoInternalStageInputs(team_id=team_id,batch_export_id=batch_export_id,@@ -300,6 +311,7 @@ async def test_insert_into_stage_activity_for_events_model(ateam,model: BatchExportModel,exclude_events,+ truncate_clickhouse_tables,):"""Test that the insert_into_internal_stage_activity produces expected data in the internal stage.@@ -338,6 +350,7 @@ async def test_insert_into_stage_activity_reports_records_total_for_events_modeldata_interval_end,ateam,model: BatchExportModel,+ truncate_clickhouse_tables,):"""The activity reports the number of rows written to the stage, from ClickHouse's query summary."""@@ -500,6 +513,7 @@ async def test_insert_into_stage_activity_for_persons_model(clickhouse_client,model: BatchExportModel,limited_export: bool,+ truncate_clickhouse_tables,):"""Test that the insert_into_internal_stage_activity produces expected data in the internal stage for the personsmodel.@@ -946,6 +960,7 @@ async def test_insert_into_stage_activity_writes_dynamic_number_of_files(data_interval_end,ateam,model: BatchExportModel,+ truncate_clickhouse_tables,):"""A previous run's row count drives how many staging files the activity writes."""batch_export = await _acreate_batch_export_for_test(ateam.pk)@@ -1005,6 +1020,7 @@ async def test_insert_into_stage_activity_uses_static_default_without_previous_rdata_interval_end,ateam,model: BatchExportModel,+ truncate_clickhouse_tables,):"""With no previous run to estimate from, the activity writes the static-default number of files."""insert_inputs = BatchExportInsertIntoInternalStageInputs(@@ -1039,3 +1055,340 @@ async def test_insert_into_stage_activity_uses_static_default_without_previous_rjson_columns=None,)assert len(keys) == 4+++async def _assert_staging_query_settings(clickhouse_client: ClickHouseClient, batch_export_id: str) -> None:+ """Currently every model's staging query should run with the same batch export settings applied."""+ actual_settings = await _fetch_staging_query_settings(clickhouse_client, batch_export_id)+ # one staging query, with max_bytes_before_external_sort and optimize_aggregation_in_order set+ assert actual_settings == [["50000000000", "1"]]+++async def _fetch_staging_query_settings(+ clickhouse_client: ClickHouseClient,+ batch_export_id: str,+ max_wait_time: float = 10.0,+ poll_interval: float = 0.5,+) -> list[list[str]]:+ """Return the settings ClickHouse recorded for this export's staging queries.++ Looking the queries up by their log comment means a result is also proof the log+ comment was attached.++ ClickHouse pushes a query's `system.query_log` entry after it has responded to the+ client, so poll rather than read once: a `SYSTEM FLUSH LOGS` right after the export+ can flush before the entry is even queued, which lags further under CI load.++ Matching on `query_kind` rather than the query text keeps this query from finding+ itself: it runs with the same log comment as the export it is looking up.+ """+ elapsed_time = 0.0+ while True:+ await clickhouse_client.execute_query("SYSTEM FLUSH LOGS")+ rows = await clickhouse_client.read_query(+ "SELECT Settings['max_bytes_before_external_sort'], Settings['optimize_aggregation_in_order'] "+ "FROM system.query_log "+ f"WHERE JSONExtractString(log_comment, 'batch_export_id') = '{batch_export_id}' "+ "AND JSONExtractString(log_comment, 'product') = 'batch_export' "+ "AND query_kind = 'Insert' AND type = 'QueryFinish'"+ )+ settings_per_query = [line.split("\t") for line in rows.decode().splitlines()]+ if settings_per_query or elapsed_time >= max_wait_time:+ return settings_per_query+ await asyncio.sleep(poll_interval)+ elapsed_time += poll_interval+++ "model",+ [+ BatchExportModel(name="events", schema=None),+ BatchExportModel(name="persons", schema=None),+ BatchExportModel(name="sessions", schema=None),+ ],+ ids=["events", "persons", "sessions"],+)+async def test_insert_into_stage_activity_applies_settings_and_log_comment(+ activity_environment,+ minio_client,+ ateam,+ clickhouse_client,+ data_interval_start,+ data_interval_end,+ model: BatchExportModel,+):+ """Every model's settings and log comment reach the query ClickHouse runs.++ These models write their settings into the query, unlike the hogql model, but all of+ them get their log comment from the query tags. No data is inserted: the query runs+ (and is logged) either way, and what each model exports is covered elsewhere.+ """+ batch_export_id = str(uuid.uuid4())+ insert_inputs = BatchExportInsertIntoInternalStageInputs(+ team_id=ateam.pk,+ batch_export_id=batch_export_id,+ data_interval_start=data_interval_start.isoformat(),+ data_interval_end=data_interval_end.isoformat(),+ batch_export_model=model,+ )++ await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)++ await _assert_staging_query_settings(clickhouse_client, batch_export_id)+++class TestHogQLModel:+ """Tests for the 'hogql' model, which exports the results of a user-defined HogQL query."""++ @pytest_asyncio.fixture+ async def hogql_model_test_data(+ self, clickhouse_client, ateam, data_interval_start, data_interval_end, truncate_clickhouse_tables+ ):+ """Insert persons and events linked by person and distinct ID for HogQL model tests.++ All of this team's events share one session, which is also backfilled into+ `raw_sessions` so queries can read the sessions table. Events and persons are also+ inserted for another team, sharing that session ID, so tests verify the HogQL+ printer's team scoping.+ """+ session_id = str(uuid7())+ persons, _ = await generate_test_persons_in_clickhouse(+ client=clickhouse_client,+ team_id=ateam.pk,+ start_time=data_interval_start,+ end_time=data_interval_end,+ count=3,+ count_other_team=3,+ properties={"utm_medium": "referral"},+ )++ events = []+ for person in persons:+ distinct_id = f"distinct-id-{person['id']}"+ await generate_test_person_distinct_id2_in_clickhouse(+ client=clickhouse_client,+ team_id=ateam.pk,+ person_id=uuid.UUID(person["id"]),+ distinct_id=distinct_id,+ timestamp=dt.datetime.fromisoformat(person["_timestamp"]),+ )+ person_events = generate_test_events(+ count=2,+ team_id=ateam.pk,+ possible_datetimes=[data_interval_start, data_interval_end - dt.timedelta(minutes=1)],+ event_name="test-{i}",+ properties={"$browser": "Chrome", "$session_id": session_id, "custom": 'nope-100%-{"a": 1}'},+ distinct_ids=[distinct_id],+ )+ for event in person_events:+ event["person_id"] = person["id"]+ events.extend(person_events)++ events_from_other_team = generate_test_events(+ count=3,+ team_id=ateam.pk + random.randint(1, 1000),+ possible_datetimes=[data_interval_start],+ event_name="test-{i}",+ properties={"$browser": "Chrome", "$session_id": session_id},+ )+ await insert_event_values_in_clickhouse(+ client=clickhouse_client, events=events + events_from_other_team, table="sharded_events"+ )+ await insert_sessions_in_clickhouse(client=clickhouse_client, table="sharded_events")++ return events, persons++ @pytest.mark.parametrize(+ "hogql_query,expected_columns,build_expected_rows",+ [+ pytest.param(+ """+ SELECT event AS event, distinct_id AS distinct_id, properties.$browser AS browser+ FROM events+ WHERE event != 'filter_out'+ """,+ ["event", "distinct_id", "browser"],+ lambda events, persons: [(e["event"], e["distinct_id"], "Chrome") for e in events],+ id="events",+ ),+ # Add some special characters to the query to ensure it is properly escaped+ pytest.param(+ """+ SELECT event AS event, distinct_id AS distinct_id, properties.$browser AS browser+ FROM events+ WHERE event != 'filter-%-{"a": 1}'+ """,+ ["event", "distinct_id", "browser"],+ lambda events, persons: [(e["event"], e["distinct_id"], "Chrome") for e in events],+ id="events-with-special-chars",+ ),+ pytest.param(+ "SELECT toString(id) AS id, properties.utm_medium AS utm_medium FROM persons",+ ["id", "utm_medium"],+ lambda events, persons: [(p["id"], "referral") for p in persons],+ id="persons",+ ),+ # every event shares one session, and the other team's events share its ID+ pytest.param(+ "SELECT session_id AS session_id FROM sessions",+ ["session_id"],+ lambda events, persons: [(events[0]["properties"]["$session_id"],)],+ id="sessions",+ ),+ pytest.param(+ """+ SELECT events.event AS event, persons.properties.utm_medium AS medium+ FROM events+ INNER JOIN persons ON events.person_id = persons.id+ """,+ ["event", "medium"],+ lambda events, persons: [(e["event"], "referral") for e in events],+ id="events-join-persons",+ ),+ pytest.param(+ """+ WITH ev AS (SELECT event AS event, person_id AS person_id FROM events)+ SELECT ev.event AS event, persons.properties.utm_medium AS medium+ FROM ev+ INNER JOIN persons ON ev.person_id = persons.id+ """,+ ["event", "medium"],+ lambda events, persons: [(e["event"], "referral") for e in events],+ id="cte-join",+ ),+ # A UNION parses to an ast.SelectSetQuery rather than an ast.SelectQuery+ pytest.param(+ """+ SELECT event AS event, 'first' AS part FROM events+ UNION ALL+ SELECT event AS event, 'second' AS part FROM events+ """,+ ["event", "part"],+ lambda events, persons: (+ [(e["event"], "first") for e in events] + [(e["event"], "second") for e in events]+ ),+ id="union",+ ),+ ],+ )+ async def test_stages_expected_data(+ self,+ hogql_model_test_data,+ activity_environment,+ minio_client,+ ateam,+ data_interval_start,+ data_interval_end,+ hogql_query,+ expected_columns,+ build_expected_rows,+ ):+ """insert_into_internal_stage_activity stages correct data for a user-defined HogQL query.++ The data interval has no meaning for the HogQL model currently: the query is executed as-is,+ scoped to the team by the HogQL printer, and we don't wait for the interval end to pass.+ Each case asserts exact rows and column names (aliases) read back from the staged Arrow+ files.+ """+ events, persons = hogql_model_test_data++ with patch(+ "products.batch_exports.backend.temporal.pipeline.internal_stage.wait_for_delta_past_data_interval_end"+ ) as mock_wait:+ exported_rows = await _run_activity(+ activity_environment=activity_environment,+ minio_client=minio_client,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ model=BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query),+ )++ assert all(list(row.keys()) == expected_columns for row in exported_rows)+ assert sorted(tuple(row[column] for column in expected_columns) for row in exported_rows) == sorted(+ build_expected_rows(events, persons)+ )+ mock_wait.assert_not_called()++ async def test_stages_expected_data_for_warehouse_view(+ self,+ hogql_model_test_data,+ activity_environment,+ minio_client,+ ateam,+ data_interval_start,+ data_interval_end,+ ):+ """A HogQL query selecting from a data warehouse view (saved query) stages the view's rows.++ Non-materialized saved queries are inlined as subqueries at query resolution time, so+ no materialization is required. Column metadata is required though: field resolution+ against a view goes through its declared columns (the API computes these on create).+ """+ await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(+ team=ateam,+ name="events_view",+ query={+ "kind": "HogQLQuery",+ "query": "SELECT toString(uuid) AS event_id, event AS event, distinct_id AS distinct_id FROM events",+ },+ columns={"event_id": "String", "event": "String", "distinct_id": "String"},+ )++ exported_rows = await _run_activity(+ activity_environment=activity_environment,+ minio_client=minio_client,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ model=BatchExportModel(+ name="hogql", schema=None, hogql_query="SELECT event_id, event, distinct_id FROM events_view"+ ),+ )++ events, _ = hogql_model_test_data+ assert sorted((row["event_id"], row["event"], row["distinct_id"]) for row in exported_rows) == sorted(+ (e["uuid"], e["event"], e["distinct_id"]) for e in events+ )++ # also assert doing a SELECT * works (should give same result)+ exported_rows_2 = await _run_activity(+ activity_environment=activity_environment,+ minio_client=minio_client,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT * FROM events_view"),+ )+ assert sorted((row["event_id"], row["event"], row["distinct_id"]) for row in exported_rows_2) == sorted(+ (e["uuid"], e["event"], e["distinct_id"]) for e in events+ )++ async def test_applies_settings_and_log_comment(+ self,+ hogql_model_test_data,+ activity_environment,+ minio_client,+ ateam,+ clickhouse_client,+ data_interval_start,+ data_interval_end,+ ):+ """The batch export settings and log comment reach the query ClickHouse actually runs.++ Neither is written into the query text; they are both sent as query paramaters, so this+ asserts against ClickHouse's own record of the query rather than the SQL we generated.+ """+ batch_export_id = str(uuid.uuid4())++ await _run_activity(+ activity_environment=activity_environment,+ minio_client=minio_client,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"),+ batch_export_id=batch_export_id,+ )++ await _assert_staging_query_settings(clickhouse_client, batch_export_id)diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.pyindex b1f7bc0d5dc7..28aa13f42444 100644--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py@@ -5,7 +5,13 @@ from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.sync import database_sync_to_async-from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel+from products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryError+from products.batch_exports.backend.service import BatchExportModel+from products.batch_exports.backend.temporal.record_batch_model import (+ HogQLQueryRecordBatchModel,+ SessionsRecordBatchModel,+ resolve_batch_exports_model,+)pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -93,7 +99,7 @@ class TestSessionsRecordBatchModel:model = SessionsRecordBatchModel(team_id=ateam.id,)- printed_query, query_parameters = await model.as_insert_into_s3_query_with_parameters(+ printed_query, _ = await model.as_insert_into_s3_query_with_parameters(data_interval_start=data_interval_start,data_interval_end=data_interval_end,s3_folder="https://test-bucket.s3.amazonaws.com/test-prefix",@@ -122,10 +128,11 @@ class TestSessionsRecordBatchModel:"greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus("in printed_query)-- # check that we have a log_comment set (we pass this in as a query parameter)- assert "log_comment={log_comment}" in printed_query- assert "log_comment" in query_parameters+ # the sessions query carries its settings on the AST, so the printer renders them+ assert "SETTINGS" in printed_query+ assert "optimize_aggregation_in_order=1" in printed_query+ # this model needs no request settings: the printer already emitted them+ assert model.get_clickhouse_request_settings() == {}async def test_as_insert_into_s3_query_with_parameters_keyless_auth(self, ateam, data_interval_start, data_interval_end@@ -151,3 +158,89 @@ class TestSessionsRecordBatchModel:in printed_query)assert "PARTITION BY rand() %% 5" in printed_query+++class TestHogQLQueryRecordBatchModel:+ async def test_as_query_with_parameters(self, ateam, data_interval_start, data_interval_end):+ model = HogQLQueryRecordBatchModel(+ team_id=ateam.id, hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events"+ )+ printed_query, query_parameters = await model.as_query_with_parameters(data_interval_start, data_interval_end)++ # should add filter on team_id+ assert f"equals(events.team_id, {ateam.id})" in printed_query+ assert "FORMAT ArrowStream" in printed_query+ assert "log_comment" in query_parameters++ async def test_as_insert_into_s3_query_with_parameters(self, ateam, data_interval_start, data_interval_end):+ model = HogQLQueryRecordBatchModel(+ team_id=ateam.id, hogql_query="SELECT event AS event, distinct_id AS distinct_id FROM events"+ )+ printed_query, query_parameters = await model.as_insert_into_s3_query_with_parameters(+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ s3_folder="https://test-bucket.s3.amazonaws.com/test-prefix",+ s3_key="test-key",+ s3_secret="test-secret",+ num_partitions=5,+ )++ assert "INSERT INTO FUNCTION" in printed_query+ assert "https://test-bucket.s3.amazonaws.com/test-prefix/export_{{_partition_id}}.arrow" in printed_query+ assert "PARTITION BY rand() %% 5" in printed_query+ assert f"equals(events.team_id, {ateam.id})" in printed_query+ # the user's query is wrapped as-is: settings are sent as query parameters, so we never write a+ # SETTINGS clause into the query+ assert "SETTINGS" not in printed_query++ async def test_get_clickhouse_request_settings(self):+ """Batch export settings are sent as query parameters rather than a SETTINGS clause.++ Values are rendered the way the HogQL printer renders them (bools as 1/0), so a+ setting reads the same in query_log however it was applied. ClickHouse rejects+ unknown setting names outright, so a typo here fails the export.+ """+ model = HogQLQueryRecordBatchModel(team_id=1, hogql_query="SELECT event AS event FROM events")++ assert model.get_clickhouse_request_settings() == {+ "optimize_aggregation_in_order": "1",+ "max_bytes_before_external_sort": "50000000000",+ "max_bytes_before_external_group_by": "50000000000",+ }++ @pytest.mark.parametrize(+ "hogql_query,expected_message",+ [+ ("SELECT event AS event FROM events WHERE {filters}", "Placeholders are not supported"),+ ("SELECT event AS event FROM events WHERE event = {placeholder_field}", "Placeholders are not supported"),+ ("SELECT event AS event FROM events WHERE event = {concat('a', 'b')}", "Placeholders are not supported"),+ ("not a valid query", "Failed to parse HogQL query"),+ ("DROP TABLE events", "Failed to parse HogQL query"),+ ],+ ids=["filters", "placeholder-field", "placeholder-expression", "invalid-syntax", "not-a-select"],+ )+ async def test_get_hogql_query_raises_on_unsupported_query(+ self, hogql_query, expected_message, data_interval_start, data_interval_end+ ):+ model = HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)++ with pytest.raises(UnsupportedHogQLQueryError, match=expected_message):+ model.get_hogql_query(data_interval_start, data_interval_end)++ async def test_resolve_batch_exports_model_returns_hogql_model(self):+ batch_export_model = BatchExportModel(+ name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"+ )++ _, record_batch_model, model_name, _, _, _ = resolve_batch_exports_model(+ team_id=1, batch_export_model=batch_export_model+ )++ assert isinstance(record_batch_model, HogQLQueryRecordBatchModel)+ assert model_name == "hogql"+ assert record_batch_model.hogql_query == batch_export_model.hogql_query++ async def test_resolve_batch_exports_model_raises_without_hogql_query(self):+ """Without this, a missing query would fall through to the events template path and export the wrong data."""+ with pytest.raises(UnsupportedHogQLQueryError):+ resolve_batch_exports_model(team_id=1, batch_export_model=BatchExportModel(name="hogql", schema=None))