: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): create file download batch exports from hogql queries (#72665)
Ross079ef86b20b8
diff --git a/products/batch_exports/backend/api/file_download.py b/products/batch_exports/backend/api/file_download.pyindex 731f1258b95b..a9fa76d0fb47 100644--- a/products/batch_exports/backend/api/file_download.py+++ b/products/batch_exports/backend/api/file_download.py@@ -11,22 +11,29 @@ from django.shortcuts import get_object_or_404import boto3import structlog+import posthoganalyticsfrom botocore.client import Configfrom botocore.exceptions import ClientErrorfrom drf_spectacular.utils import PolymorphicProxySerializer, extend_schemafrom rest_framework import mixins, response, serializers, status, viewsets-from rest_framework.exceptions import APIException, NotFound, ValidationError+from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationErrorfrom posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action+from posthog.models import Teamfrom posthog.temporal.common.client import sync_connect+from products.batch_exports.backend.hogql_source import (+ UnsupportedHogQLQueryError,+ validate_hogql_query_for_batch_export,+)from products.batch_exports.backend.models.batch_export import (BatchExportDestination,BatchExportFileDownload,BatchExportOnDemand,BatchExportRun,+ BatchExportSource,)from products.batch_exports.backend.service import (BatchExportModel,@@ -93,21 +100,69 @@ class FileDownloadSessionsRequestSerializer(serializers.Serializer):data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)+HOGQL_QUERY_HELP_TEXT = (+ "HogQL SELECT query whose results are exported. Placeholders are not currently supported, "+ "and every column in the SELECT clause must be a field or have an alias. The query runs as of the"+ "time the export starts; events ingested moments before may not be included yet."+)+++class FileDownloadHogQLRequestSerializer(serializers.Serializer):+ """Typed configuration for the hogql model."""++ file = FileDownloadDestinationFileConfigSerializer()+ model = serializers.ChoiceField(choices=["hogql"])+ hogql_query = serializers.CharField(help_text=HOGQL_QUERY_HELP_TEXT)+++def check_hogql_batch_exports_enabled(team: Team) -> None:+ """Raise if HogQL-powered batch exports are not enabled for the team."""+ if not posthoganalytics.feature_enabled(+ "hogql-batch-exports",+ str(team.uuid),+ groups={"organization": str(team.organization.id)},+ group_properties={+ "organization": {+ "id": str(team.organization.id),+ "created_at": team.organization.created_at,+ }+ },+ send_feature_flag_events=False,+ ):+ raise PermissionDenied("HogQL batch exports are not enabled for this team.")++class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):"""Request shape for a FileDownload batch export on demand."""file = FileDownloadDestinationFileConfigSerializer()- model = serializers.ChoiceField(choices=["events", "persons", "sessions"])+ model = serializers.ChoiceField(choices=["events", "persons", "sessions", "hogql"])# Only specific to eventsinclude = serializers.ListField(child=serializers.CharField(), required=False)exclude = serializers.ListField(child=serializers.CharField(), required=False)- # Run attributes- data_interval_start = serializers.DateTimeField(default_timezone=dt.UTC)- data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)+ # Only specific to hogql+ hogql_query = serializers.CharField(required=False, help_text=HOGQL_QUERY_HELP_TEXT)++ # Run attributes; required for all models except hogql, which runs as of now+ data_interval_start = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text="Start of the data interval to export"+ )+ data_interval_end = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text="End of the data interval to export"+ )def validate(self, data):+ if data["model"] == "hogql":+ return self._validate_hogql(data)++ if data.get("hogql_query") is not None:+ raise ValidationError("'hogql_query' is only supported when 'model' is 'hogql'")++ if data.get("data_interval_start") is None or data.get("data_interval_end") is None:+ raise ValidationError(f"'data_interval_start' and 'data_interval_end' are required for '{data['model']}'")+if data["data_interval_start"] > data["data_interval_end"]:raise ValidationError("'data_interval_end' must occur after 'data_interval_start'")@@ -121,6 +176,32 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):return data+ def _validate_hogql(self, data: dict) -> dict:+ team = self.context["get_team"]()+ check_hogql_batch_exports_enabled(team)++ # not sure if we need to be this strict but probably best to be explicit+ # TODO: can remove this once we do support data_interval_start/end+ if data.get("data_interval_start") is not None or data.get("data_interval_end") is not None:+ raise ValidationError(+ "'data_interval_start' and 'data_interval_end' are not supported when 'model' is 'hogql': "+ "the query runs as of the time the export starts"+ )++ if data.get("include") is not None or data.get("exclude") is not None:+ raise ValidationError("'include' and 'exclude' are not supported when 'model' is 'hogql'")++ hogql_query = data.get("hogql_query")+ if not hogql_query:+ raise ValidationError("'hogql_query' is required when 'model' is 'hogql'")++ try:+ validate_hogql_query_for_batch_export(hogql_query, team)+ except UnsupportedHogQLQueryError as e:+ raise ValidationError({"hogql_query": str(e)}) from e++ return data+def create(self, validated_data: dict) -> BatchExportRun:"""Create a `BatchExportRun` based on a `BatchExportOnDemand`.@@ -128,11 +209,20 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):"""team_id = self.context["team_id"]config = validated_data.pop("file")+ model = validated_data["model"]- data_interval_start = validated_data.pop("data_interval_start")- data_interval_end = validated_data.pop("data_interval_end")+ source = None+ if model == "hogql":+ source = BatchExportSource(team_id=team_id, hogql_query=validated_data.pop("hogql_query"))+ # For now, HogQL exports have no data interval: the query runs as of now.+ # We set a concrete now/now interval to keep everything downstream (eg workflow ID,+ # staging paths) working unchanged. We should perhaps make the data interval optional in+ # future.+ data_interval_start = data_interval_end = dt.datetime.now(dt.UTC)+ else:+ data_interval_start = validated_data.pop("data_interval_start")+ data_interval_end = validated_data.pop("data_interval_end")- model = validated_data["model"]if (include := validated_data.pop("include", None)) is not None and model == "events":config["include_events"] = include@@ -140,7 +230,7 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):config["exclude_events"] = excludedestination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config=config)- batch_export = BatchExportOnDemand(team_id=team_id, destination=destination, **validated_data)+ batch_export = BatchExportOnDemand(team_id=team_id, destination=destination, source=source, **validated_data)batch_export_run = BatchExportRun(status=BatchExportRun.Status.STARTING,batch_export_on_demand=batch_export,@@ -150,6 +240,8 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):with transaction.atomic():destination.save()+ if source is not None:+ source.save()batch_export.save()batch_export_run.save()@@ -250,6 +342,7 @@ class FileDownloadBatchExportOnDemandViewSet("events": FileDownloadEventsRequestSerializer,"persons": FileDownloadPersonsRequestSerializer,"sessions": FileDownloadSessionsRequestSerializer,+ "hogql": FileDownloadHogQLRequestSerializer,},resource_type_field_name="model",),@@ -285,6 +378,7 @@ class FileDownloadBatchExportOnDemandViewSet(instance = serializer.save()+ source = instance.batch_export_on_demand.sourcetry:start_file_download_batch_export(instance.batch_export_on_demand,@@ -292,7 +386,11 @@ class FileDownloadBatchExportOnDemandViewSet(batch_export_run_id=instance.id,data_interval_start=instance.data_interval_start,data_interval_end=instance.data_interval_end,- batch_export_model=BatchExportModel(name=instance.batch_export_on_demand.model, schema=None),+ batch_export_model=BatchExportModel(+ name=instance.batch_export_on_demand.model,+ schema=None,+ hogql_query=source.hogql_query if source is not None else None,+ ),compression=instance.batch_export_on_demand.destination.config.get("compression", None),format=instance.batch_export_on_demand.destination.config.get("format", "Parquet"),max_size_mb=instance.batch_export_on_demand.destination.config.get("max_size_mb", 0),diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.pyindex 0ab4b147756f..2663ada71de3 100644--- a/products/batch_exports/backend/hogql_source.py+++ b/products/batch_exports/backend/hogql_source.py@@ -4,10 +4,18 @@ This module must stay importable by both the API layer and the Temporal worker,should not import from `products.batch_exports.backend.temporal` or any DRF code."""+import typing+from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.placeholders import find_placeholders+from posthog.hogql.printer import prepare_ast_for_printing++if typing.TYPE_CHECKING:+ from posthog.models import Teamclass UnsupportedHogQLQueryError(Exception):@@ -37,3 +45,64 @@ def parse_hogql_select_for_batch_export(hogql_query: str) -> ast.SelectQuery | araise UnsupportedHogQLQueryError("Placeholders are not supported in batch export queries")return parsed+++def create_hogql_context_for_batch_export(team: "Team", values: dict[str, typing.Any] | None = None) -> HogQLContext:+ """Build the HogQLContext batch exports use to resolve and print a query.++ Both API-side validation and worker-side execution must build the context the same+ way (team-default modifiers, full database, no top-level LIMIT), otherwise a query+ that validates could resolve differently when it runs. This builder is the single+ source of truth for those semantics. It reads from Postgres, so worker code must+ call it off the event loop.+ """+ context = HogQLContext(+ team=team,+ team_id=team.id,+ enable_select_queries=True,+ limit_top_select=False,+ values=values if values is not None else {},+ )+ context.database = Database.create_for(team=team, modifiers=context.modifiers)+ return context+++def _validate_select_columns_are_named(parsed: ast.SelectQuery | ast.SelectSetQuery) -> None:+ """Check every top-level SELECT expression has a usable output column name.++ Bare fields and `*` name their columns; anything else (function calls, arithmetic,+ constants) prints as an expression, producing column names like `plus(1, 1)`, which are likely to+ cause issues in downstream destinations (e.g. BigQuery does not permit spaces in column names).++ We could relax this restriction in future and handle validation in the downstream destination.+ """+ select_query = parsed+ # In a set operation (e.g. UNION ALL) the first SELECT names the output columns.+ while isinstance(select_query, ast.SelectSetQuery):+ select_query = select_query.initial_select_query+ for expr in select_query.select:+ if not isinstance(expr, ast.Field | ast.Alias):+ raise UnsupportedHogQLQueryError(+ "Every column in the SELECT clause must be a field or have an alias (e.g. `count() AS event_count`)"+ )+++def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team") -> None:+ """Validate a HogQL query can power a batch export for the given team.++ Parses the query, checks output columns are named, and resolves types against the+ team's database (catching unknown tables/fields) with the same context the worker+ will execute with.++ Raises:+ UnsupportedHogQLQueryError: If the query cannot power a batch export.+ InternalHogQLError: Left to propagate, as in `parse_hogql_select_for_batch_export`.+ """+ parsed = parse_hogql_select_for_batch_export(hogql_query)+ _validate_select_columns_are_named(parsed)++ context = create_hogql_context_for_batch_export(team)+ try:+ prepare_ast_for_printing(parsed, context=context, dialect="clickhouse", stack=[])+ except ExposedHogQLError as e:+ raise UnsupportedHogQLQueryError(f"Invalid HogQL query: {e}") from ediff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex 877c5f15c40f..8bc64cf2057a 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -5,7 +5,6 @@ import datetime as dtfrom posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.database import Databasefrom posthog.hogql.hogql import astfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast@@ -18,7 +17,11 @@ 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_export+from products.batch_exports.backend.hogql_source import (+ UnsupportedHogQLQueryError,+ create_hogql_context_for_batch_export,+ parse_hogql_select_for_batch_export,+)from 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@@ -58,23 +61,16 @@ class RecordBatchModel(abc.ABC):async def get_hogql_context(self) -> HogQLContext:"""Return a HogQLContext to generate a ClickHouse query."""team = await Team.objects.aget(id=self.team_id)- context = HogQLContext(- team=team,- team_id=team.id,- enable_select_queries=True,- limit_top_select=False,+ # Building the context reads from Postgres, so it must run off the event loop.+ return await database_sync_to_async(create_hogql_context_for_batch_export)(+ team,# 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(),- },+ values={"log_comment": self.get_log_comment()},)- context.database = await database_sync_to_async(Database.create_for)(team=team, modifiers=context.modifiers)-- return contextdef get_log_comment(self) -> str:"""Tag this export's queries, and return the tags as a log comment.diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.pyindex 4561105d78e7..0c6aa59440b3 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py@@ -1,5 +1,6 @@import timeimport uuid+import randomimport asyncioimport datetime as dtfrom urllib.parse import urlsplit@@ -19,6 +20,7 @@ from rest_framework import statusfrom temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.models.scoping import team_scope+from posthog.temporal.tests.utils.events import generate_test_events, insert_event_values_in_clickhousefrom products.batch_exports.backend.api.file_download import (_calculate_expiration_for_file_download,@@ -30,6 +32,7 @@ from products.batch_exports.backend.models.batch_export import (BatchExportFileDownload,BatchExportOnDemand,BatchExportRun,+ BatchExportSource,)from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWS@@ -147,6 +150,15 @@ def override_file_download_settings(aws_role_arn, s3_bucket):yield+def mock_start_file_download_export():+ """Mock starting the Temporal workflow so create tests don't reach Temporal."""+ with unittest.mock.patch(+ "products.batch_exports.backend.api.file_download.start_file_download_batch_export"+ ) as mock_start:+ yield mock_start++@pytest.mark.django_db(transaction=True)async def test_file_download_retrieve_returns_error(async_client: AsyncClient, temporal_client, team, user, data_interval_start, data_interval_end, generate_test_data@@ -361,6 +373,7 @@ async def test_file_download_create_rejects_when_concurrency_limit_reached(user,data_interval_start,data_interval_end,+ mock_start_file_download_export,):destination = await BatchExportDestination.objects.acreate(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config={}@@ -376,26 +389,23 @@ async def test_file_download_create_rejects_when_concurrency_limit_reached(await async_client.aforce_login(user)- with unittest.mock.patch(- "products.batch_exports.backend.api.file_download.start_file_download_batch_export"- ) as mock_start:- response = await async_client.post(- f"/api/projects/{team.pk}/file_download_batch_exports",- {- "file": {- "format": "Parquet",- "compression": "zstd",- },- "model": "events",- "data_interval_start": data_interval_start,- "data_interval_end": data_interval_end,+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {+ "format": "Parquet",+ "compression": "zstd",},- content_type="application/json",- )+ "model": "events",+ "data_interval_start": data_interval_start,+ "data_interval_end": data_interval_end,+ },+ content_type="application/json",+ )assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS, response.json()assert response.json()["code"] == "too_many_concurrent_file_downloads"- mock_start.assert_not_called()+ mock_start_file_download_export.assert_not_called()@pytest.mark.django_db(transaction=True)@@ -403,33 +413,31 @@ async def test_file_download_create_rejects_future_data_interval_end(async_client: AsyncClient,team,user,+ mock_start_file_download_export,):now = dt.datetime.now(dt.UTC)await async_client.aforce_login(user)- with unittest.mock.patch(- "products.batch_exports.backend.api.file_download.start_file_download_batch_export"- ) as mock_start:- data_interval_end_iso = (now + dt.timedelta(hours=1)).isoformat()- response = await async_client.post(- f"/api/projects/{team.pk}/file_download_batch_exports",- {- "file": {- "format": "Parquet",- "compression": "zstd",- },- "model": "events",- "data_interval_start": (now - dt.timedelta(hours=1)).isoformat(),- "data_interval_end": data_interval_end_iso,+ data_interval_end_iso = (now + dt.timedelta(hours=1)).isoformat()+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {+ "format": "Parquet",+ "compression": "zstd",},- content_type="application/json",- )+ "model": "events",+ "data_interval_start": (now - dt.timedelta(hours=1)).isoformat(),+ "data_interval_end": data_interval_end_iso,+ },+ content_type="application/json",+ )assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()assert response.json()["detail"] == f"The provided 'data_interval_end' ({data_interval_end_iso}) is in the future"- mock_start.assert_not_called()+ mock_start_file_download_export.assert_not_called()assert (await BatchExportRun.objects.filter(batch_export_on_demand__team_id=team.pk,@@ -597,3 +605,273 @@ async def test_file_download_cancel_mocked(await run.arefresh_from_db()assert run.status == BatchExportRun.Status.CANCELLED+++class TestFileDownloadHogQL:+ """File download batch exports created from a user-defined HogQL query."""++ HOGQL_FLAG_PATCH_TARGET = "products.batch_exports.backend.api.file_download.posthoganalytics.feature_enabled"++ @pytest.fixture+ def enable_hogql_flag(self):+ """Enable the hogql-batch-exports feature flag for the duration of a test."""+ with unittest.mock.patch(self.HOGQL_FLAG_PATCH_TARGET, return_value=True):+ yield++ @pytest.fixture+ async def hogql_export_test_events(self, clickhouse_client, team):+ """Insert events for this and another team directly into the events table.++ A hogql export reads the main (sharded) events table with no interval filter, so+ the test controls exactly which rows exist there: no duplicates, plus another+ team's rows to verify only this team's data is exported.+ """+ timestamp = dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)+ events = generate_test_events(+ count=10,+ team_id=team.pk,+ possible_datetimes=[timestamp],+ event_name="test-{i}",+ properties={"$browser": "Chrome"},+ )+ events_from_other_team = generate_test_events(+ count=3,+ team_id=team.pk + random.randint(1, 1000),+ possible_datetimes=[timestamp],+ event_name="test-{i}",+ properties={"$browser": "Chrome"},+ )+ await insert_event_values_in_clickhouse(+ client=clickhouse_client, events=events + events_from_other_team, table="sharded_events"+ )+ return events++ @pytest.mark.django_db(transaction=True)+ async def test_rejected_when_flag_disabled(+ self, async_client: AsyncClient, team, user, mock_start_file_download_export+ ):+ await async_client.aforce_login(user)++ with unittest.mock.patch(self.HOGQL_FLAG_PATCH_TARGET, return_value=False) as mock_flag:+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {"format": "Parquet"},+ "model": "hogql",+ "hogql_query": "SELECT event AS event FROM events",+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ assert mock_flag.call_args[0][0] == "hogql-batch-exports"+ mock_start_file_download_export.assert_not_called()+ assert await sync_to_async(lambda: BatchExportSource.objects.for_team(team.pk).count())() == 0++ @pytest.mark.parametrize(+ "body_overrides,expected_error_fragment",+ [+ pytest.param(+ {"hogql_query": None},+ "'hogql_query' is required when 'model' is 'hogql'",+ id="missing-query",+ ),+ pytest.param(+ {"hogql_query": "this is not hogql"},+ "Failed to parse HogQL query",+ id="unparseable-query",+ ),+ pytest.param(+ {"hogql_query": "SELECT event AS event FROM events WHERE {filters}"},+ "Placeholders are not supported",+ id="placeholder-query",+ ),+ pytest.param(+ {"hogql_query": "SELECT count() FROM events"},+ "must be a field or have an alias",+ id="unaliased-expression-column",+ ),+ pytest.param(+ {"hogql_query": "SELECT x AS x FROM no_such_table"},+ "Invalid HogQL query",+ id="unknown-table",+ ),+ pytest.param(+ {"data_interval_start": "2026-01-01T00:00:00+00:00", "data_interval_end": "2026-01-02T00:00:00+00:00"},+ "not supported when 'model' is 'hogql'",+ id="intervals-with-hogql",+ ),+ pytest.param(+ {"include": ["my-event"]},+ "'include' and 'exclude' are not supported when 'model' is 'hogql'",+ id="include-with-hogql",+ ),+ pytest.param(+ {"model": "events"},+ "'hogql_query' is only supported when 'model' is 'hogql'",+ id="query-with-events-model",+ ),+ pytest.param(+ {"model": "events", "hogql_query": None},+ "'data_interval_start' and 'data_interval_end' are required",+ id="events-model-missing-intervals",+ ),+ ],+ )+ @pytest.mark.usefixtures("enable_hogql_flag")+ @pytest.mark.django_db(transaction=True)+ async def test_rejects_invalid_requests(+ self,+ async_client: AsyncClient,+ team,+ user,+ mock_start_file_download_export,+ body_overrides,+ expected_error_fragment,+ ):+ await async_client.aforce_login(user)++ body: dict = {+ "file": {"format": "Parquet"},+ "model": "hogql",+ "hogql_query": "SELECT event AS event FROM events",+ }+ for key, value in body_overrides.items():+ if value is None:+ body.pop(key, None)+ else:+ body[key] = value++ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ body,+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert expected_error_fragment in response.content.decode()+ mock_start_file_download_export.assert_not_called()+ assert (+ await BatchExportRun.objects.filter(+ batch_export_on_demand__team_id=team.pk,+ batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,+ ).acount()+ == 0+ )+ assert await sync_to_async(lambda: BatchExportSource.objects.for_team(team.pk).count())() == 0++ @pytest.mark.usefixtures("enable_hogql_flag")+ @pytest.mark.django_db(transaction=True)+ async def test_create(self, async_client: AsyncClient, team, user, mock_start_file_download_export):+ """A hogql create request stores the query on a source and threads it to the workflow.++ The run's data interval is faked as now/now: hogql exports have no interval, but+ everything downstream formats concrete bounds.+ """+ await async_client.aforce_login(user)+ hogql_query = "SELECT event AS event, distinct_id AS distinct_id FROM events"++ before = dt.datetime.now(dt.UTC)+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {"format": "Parquet"},+ "model": "hogql",+ "hogql_query": hogql_query,+ },+ content_type="application/json",+ )+ after = dt.datetime.now(dt.UTC)++ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()++ with team_scope(team_id=team.pk, canonical=True):+ run = await BatchExportRun.objects.select_related(+ "batch_export_on_demand__source", "batch_export_on_demand__destination"+ ).aget(id=response.json()["id"])++ assert run.data_interval_start == run.data_interval_end+ assert before <= run.data_interval_end <= after+ on_demand = run.batch_export_on_demand+ assert on_demand is not None+ assert on_demand.model == "hogql"+ assert on_demand.source is not None+ assert on_demand.source.hogql_query == hogql_query+ assert on_demand.source.team_id == team.pk+ assert "include_events" not in on_demand.destination.config++ mock_start_file_download_export.assert_called_once()+ batch_export_model = mock_start_file_download_export.call_args.kwargs["batch_export_model"]+ assert batch_export_model.name == "hogql"+ assert batch_export_model.hogql_query == hogql_query++ @pytest.mark.usefixtures("override_file_download_settings", "enable_hogql_flag")+ @pytest.mark.django_db(transaction=True)+ async def test_end_to_end(self, async_client: AsyncClient, temporal_client, team, user, hogql_export_test_events):+ """A hogql export produces a downloadable file whose contents match the query results."""+ await async_client.aforce_login(user)++ hogql_query = """+ SELECT event AS event, distinct_id AS distinct_id, properties.$browser AS browser+ FROM events+ """++ async with Worker(+ temporal_client,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ workflows=WORKFLOWS,+ activities=ACTIVITIES,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {"format": "Parquet", "compression": "zstd"},+ "model": "hogql",+ "hogql_query": hogql_query,+ },+ content_type="application/json",+ )+ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()++ run_id = response.json()["id"]++ timeout = 60+ start = time.monotonic()+ files = None+ while True:+ status_response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run_id}",+ )+ data = status_response.json()+ assert data["status"] in ("Starting", "Running", "Completed"), status_response.json()+ assert data.get("error", None) is None++ if data["status"] == "Completed":+ files = data["files"]+ break++ if time.monotonic() - start > timeout:+ raise TimeoutError("Batch export run took too long to complete")++ await asyncio.sleep(2)++ assert files is not None and len(files) == 1+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run_id}/download/{files[0]}",+ )+ assert response.status_code == 302+ pre_signed_url = response["Location"]++ async with aiohttp.ClientSession() as s:+ async with s.get(pre_signed_url) as resp:+ content = await resp.read()++ assert resp.status == 200, f"Invalid status: {resp.status}: {content!r}"++ table = pq.read_table(pa.BufferReader(content))++ assert set(table.column_names) == {"event", "distinct_id", "browser"}+ exported_rows = sorted((row["event"], row["distinct_id"], row["browser"]) for row in table.to_pylist())+ expected_rows = sorted((e["event"], e["distinct_id"], "Chrome") for e in hogql_export_test_events)+ assert exported_rows == expected_rowsdiff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 9217bfa0fe54..24d31463125b 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1645,10 +1645,28 @@ export interface FileDownloadSessionsRequestApi {data_interval_end: string}+export type FileDownloadHogQLRequestApiModel =+ (typeof FileDownloadHogQLRequestApiModel)[keyof typeof FileDownloadHogQLRequestApiModel]++export const FileDownloadHogQLRequestApiModel = {+ Hogql: 'hogql',+} as const++/**+ * Typed configuration for the hogql model.+ */+export interface FileDownloadHogQLRequestApi {+ file: FileDownloadDestinationFileConfigApi+ model: FileDownloadHogQLRequestApiModel+ /** HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet. */+ hogql_query: string+}+export type CreateFileDownloadRequestApi =| FileDownloadEventsRequestApi| FileDownloadPersonsRequestApi| FileDownloadSessionsRequestApi+ | FileDownloadHogQLRequestApi/*** Typed output for view set `create`.@@ -1716,6 +1734,7 @@ export type RetrieveFileDownloadResponseApi =* * `events` - events* * `persons` - persons* * `sessions` - sessions+ * * `hogql` - hogql*/export type FileDownloadBatchExportOnDemandModelEnumApi =(typeof FileDownloadBatchExportOnDemandModelEnumApi)[keyof typeof FileDownloadBatchExportOnDemandModelEnumApi]@@ -1724,6 +1743,7 @@ export const FileDownloadBatchExportOnDemandModelEnumApi = {Events: 'events',Persons: 'persons',Sessions: 'sessions',+ Hogql: 'hogql',} as const/**@@ -1734,8 +1754,12 @@ export interface FileDownloadBatchExportOnDemandApi {model: FileDownloadBatchExportOnDemandModelEnumApiinclude?: string[]exclude?: string[]- data_interval_start: string- data_interval_end: string+ /** HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet. */+ hogql_query?: string+ /** Start of the data interval to export */+ data_interval_start?: string+ /** End of the data interval to export */+ data_interval_end?: string}/**@@ -1768,6 +1792,16 @@ export const FileDownloadSessionsRequestModelEnumApi = {Sessions: 'sessions',} as const+/**+ * * `hogql` - hogql+ */+export type FileDownloadHogQLRequestModelEnumApi =+ (typeof FileDownloadHogQLRequestModelEnumApi)[keyof typeof FileDownloadHogQLRequestModelEnumApi]++export const FileDownloadHogQLRequestModelEnumApi = {+ Hogql: 'hogql',+} as const+/*** * `Starting` - Starting* * `Running` - Runningdiff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 584c70ce0da7..4fc51a37be8f 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -2749,6 +2749,9 @@ export const fileDownloadBatchExportsCreateBodyTwoFileMaxSizeMbMin = 0export const fileDownloadBatchExportsCreateBodyThreeFileFormatDefault = `Parquet`export const fileDownloadBatchExportsCreateBodyThreeFileMaxSizeMbMin = 0+export const fileDownloadBatchExportsCreateBodyFourFileFormatDefault = `Parquet`+export const fileDownloadBatchExportsCreateBodyFourFileMaxSizeMbMin = 0+export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([zod.object({@@ -2854,6 +2857,43 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([data_interval_end: zod.iso.datetime({ offset: true }),}).describe('Typed configuration for the sessions model.'),+ zod+ .object({+ file: zod+ .object({+ format: zod+ .enum(['Parquet', 'JSONLines'])+ .describe('\* `Parquet` - Parquet\n\* `JSONLines` - JSONLines')+ .default(fileDownloadBatchExportsCreateBodyFourFileFormatDefault)+ .describe('File format\n\n\* `Parquet` - Parquet\n\* `JSONLines` - JSONLines'),+ compression: zod+ .union([+ zod+ .enum(['brotli', 'gzip', 'lz4', 'snappy', 'zstd'])+ .describe(+ '\* `brotli` - brotli\n\* `gzip` - gzip\n\* `lz4` - lz4\n\* `snappy` - snappy\n\* `zstd` - zstd'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Compress the file with a supported compression format\n\n\* `zstd` - zstd\n\* `gzip` - gzip\n\* `brotli` - brotli\n\* `lz4` - lz4\n\* `snappy` - snappy'+ ),+ max_size_mb: zod+ .number()+ .min(fileDownloadBatchExportsCreateBodyFourFileMaxSizeMbMin)+ .nullish()+ .describe('Split download into multiple files of at most this size in MB'),+ })+ .describe('Typed configuration for a FileDownload batch-export destination.'),+ model: zod.enum(['hogql']),+ hogql_query: zod+ .string()+ .describe(+ 'HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.'+ ),+ })+ .describe('Typed configuration for the hogql model.'),])/**@@ -2892,11 +2932,20 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod}).describe('Typed configuration for a FileDownload batch-export destination.'),model: zod- .enum(['events', 'persons', 'sessions'])- .describe('\* `events` - events\n\* `persons` - persons\n\* `sessions` - sessions'),+ .enum(['events', 'persons', 'sessions', 'hogql'])+ .describe('\* `events` - events\n\* `persons` - persons\n\* `sessions` - sessions\n\* `hogql` - hogql'),include: zod.array(zod.string()).optional(),exclude: zod.array(zod.string()).optional(),- data_interval_start: zod.iso.datetime({ offset: true }),- data_interval_end: zod.iso.datetime({ offset: true }),+ hogql_query: zod+ .string()+ .optional()+ .describe(+ 'HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Start of the data interval to export'),+ data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),}).describe('Request shape for a FileDownload batch export on demand.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c9bc39cae4bd..a324757bf476 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15254,7 +15254,24 @@ export namespace Schemas {data_interval_end: string;}- export type CreateFileDownloadRequest = FileDownloadEventsRequest | FileDownloadPersonsRequest | FileDownloadSessionsRequest;+ export type FileDownloadHogQLRequestModel = typeof FileDownloadHogQLRequestModel[keyof typeof FileDownloadHogQLRequestModel];+++ export const FileDownloadHogQLRequestModel = {+ Hogql: 'hogql',+ } as const;++ /**+ * Typed configuration for the hogql model.+ */+ export interface FileDownloadHogQLRequest {+ file: FileDownloadDestinationFileConfig;+ model: FileDownloadHogQLRequestModel;+ /** HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet. */+ hogql_query: string;+ }++ export type CreateFileDownloadRequest = FileDownloadEventsRequest | FileDownloadPersonsRequest | FileDownloadSessionsRequest | FileDownloadHogQLRequest;/*** * `cost` - cost@@ -32281,6 +32298,7 @@ export namespace Schemas {* * `events` - events* * `persons` - persons* * `sessions` - sessions+ * * `hogql` - hogql*/export type FileDownloadBatchExportOnDemandModelEnum = typeof FileDownloadBatchExportOnDemandModelEnum[keyof typeof FileDownloadBatchExportOnDemandModelEnum];@@ -32289,6 +32307,7 @@ export namespace Schemas {Events: 'events',Persons: 'persons',Sessions: 'sessions',+ Hogql: 'hogql',} as const;/**@@ -32299,8 +32318,12 @@ export namespace Schemas {model: FileDownloadBatchExportOnDemandModelEnum;include?: string[];exclude?: string[];- data_interval_start: string;- data_interval_end: string;+ /** HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet. */+ hogql_query?: string;+ /** Start of the data interval to export */+ data_interval_start?: string;+ /** End of the data interval to export */+ data_interval_end?: string;}/**@@ -32313,6 +32336,16 @@ export namespace Schemas {Events: 'events',} as const;+ /**+ * * `hogql` - hogql+ */+ export type FileDownloadHogQLRequestModelEnum = typeof FileDownloadHogQLRequestModelEnum[keyof typeof FileDownloadHogQLRequestModelEnum];+++ export const FileDownloadHogQLRequestModelEnum = {+ Hogql: 'hogql',+ } as const;+/*** * `persons` - persons*/diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.tsindex c65b20369438..ead30f58d5b7 100644--- a/services/mcp/src/generated/batch_exports/api.ts+++ b/services/mcp/src/generated/batch_exports/api.ts@@ -760,6 +760,9 @@ export const fileDownloadBatchExportsCreateBodyTwoFileMaxSizeMbMin = 0export const fileDownloadBatchExportsCreateBodyThreeFileFormatDefault = `Parquet`export const fileDownloadBatchExportsCreateBodyThreeFileMaxSizeMbMin = 0+export const fileDownloadBatchExportsCreateBodyFourFileFormatDefault = `Parquet`+export const fileDownloadBatchExportsCreateBodyFourFileMaxSizeMbMin = 0+export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([zod.object({@@ -865,6 +868,43 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([data_interval_end: zod.iso.datetime({ offset: true }),}).describe('Typed configuration for the sessions model.'),+ zod+ .object({+ file: zod+ .object({+ format: zod+ .enum(['Parquet', 'JSONLines'])+ .describe('\* `Parquet` - Parquet\n\* `JSONLines` - JSONLines')+ .default(fileDownloadBatchExportsCreateBodyFourFileFormatDefault)+ .describe('File format\n\n\* `Parquet` - Parquet\n\* `JSONLines` - JSONLines'),+ compression: zod+ .union([+ zod+ .enum(['brotli', 'gzip', 'lz4', 'snappy', 'zstd'])+ .describe(+ '\* `brotli` - brotli\n\* `gzip` - gzip\n\* `lz4` - lz4\n\* `snappy` - snappy\n\* `zstd` - zstd'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Compress the file with a supported compression format\n\n\* `zstd` - zstd\n\* `gzip` - gzip\n\* `brotli` - brotli\n\* `lz4` - lz4\n\* `snappy` - snappy'+ ),+ max_size_mb: zod+ .number()+ .min(fileDownloadBatchExportsCreateBodyFourFileMaxSizeMbMin)+ .nullish()+ .describe('Split download into multiple files of at most this size in MB'),+ })+ .describe('Typed configuration for a FileDownload batch-export destination.'),+ model: zod.enum(['hogql']),+ hogql_query: zod+ .string()+ .describe(+ 'HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.'+ ),+ })+ .describe('Typed configuration for the hogql model.'),])/**@@ -928,11 +968,20 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod}).describe('Typed configuration for a FileDownload batch-export destination.'),model: zod- .enum(['events', 'persons', 'sessions'])- .describe('\* `events` - events\n\* `persons` - persons\n\* `sessions` - sessions'),+ .enum(['events', 'persons', 'sessions', 'hogql'])+ .describe('\* `events` - events\n\* `persons` - persons\n\* `sessions` - sessions\n\* `hogql` - hogql'),include: zod.array(zod.string()).optional(),exclude: zod.array(zod.string()).optional(),- data_interval_start: zod.iso.datetime({ offset: true }),- data_interval_end: zod.iso.datetime({ offset: true }),+ hogql_query: zod+ .string()+ .optional()+ .describe(+ 'HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Start of the data interval to export'),+ data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),}).describe('Request shape for a FileDownload batch export on demand.')diff --git a/services/mcp/src/tools/generated/batch_exports.ts b/services/mcp/src/tools/generated/batch_exports.tsindex 56cc0f04c60a..f2960be88042 100644--- a/services/mcp/src/tools/generated/batch_exports.ts+++ b/services/mcp/src/tools/generated/batch_exports.ts@@ -195,6 +195,9 @@ const fileDownloadBatchExportsCancelCreate = (): ToolBase<if (params.exclude !== undefined) {body['exclude'] = params.exclude}+ if (params.hogql_query !== undefined) {+ body['hogql_query'] = params.hogql_query+ }if (params.data_interval_start !== undefined) {body['data_interval_start'] = params.data_interval_start}@@ -230,12 +233,15 @@ const fileDownloadBatchExportsCreate = (): ToolBase<typeof FileDownloadBatchExpoif ('exclude' in params && params.exclude !== undefined) {body['exclude'] = params.exclude}- if (params.data_interval_start !== undefined) {+ if ('data_interval_start' in params && params.data_interval_start !== undefined) {body['data_interval_start'] = params.data_interval_start}- if (params.data_interval_end !== undefined) {+ if ('data_interval_end' in params && params.data_interval_end !== undefined) {body['data_interval_end'] = params.data_interval_end}+ if ('hogql_query' in params && params.hogql_query !== undefined) {+ body['hogql_query'] = params.hogql_query+ }const result = await context.api.request<unknown>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/file_download_batch_exports/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.jsonindex 6e21d761a6cf..e6ab9340d914 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json@@ -2,11 +2,13 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"data_interval_end": {+ "description": "End of the data interval to export","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"},"data_interval_start": {+ "description": "Start of the data interval to export","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"@@ -54,6 +56,10 @@},"type": "object"},+ "hogql_query": {+ "description": "HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.",+ "type": "string"+ },"id": {"description": "A UUID string identifying this batch export run.","type": "string"@@ -65,11 +71,11 @@"type": "array"},"model": {- "description": "* `events` - events\n* `persons` - persons\n* `sessions` - sessions",- "enum": ["events", "persons", "sessions"],+ "description": "* `events` - events\n* `persons` - persons\n* `sessions` - sessions\n* `hogql` - hogql",+ "enum": ["events", "persons", "sessions", "hogql"],"type": "string"}},- "required": ["id", "file", "model", "data_interval_start", "data_interval_end"],+ "required": ["id", "file", "model"],"type": "object"}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.jsonindex 668e5d0603fb..90b8fea239d4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json@@ -186,6 +186,58 @@},"required": ["file", "model", "data_interval_start", "data_interval_end"],"type": "object"+ },+ {+ "description": "Typed configuration for the hogql model.",+ "properties": {+ "file": {+ "description": "Typed configuration for a FileDownload batch-export destination.",+ "properties": {+ "compression": {+ "anyOf": [+ {+ "description": "* `brotli` - brotli\n* `gzip` - gzip\n* `lz4` - lz4\n* `snappy` - snappy\n* `zstd` - zstd",+ "enum": ["brotli", "gzip", "lz4", "snappy", "zstd"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Compress the file with a supported compression format\n\n* `zstd` - zstd\n* `gzip` - gzip\n* `brotli` - brotli\n* `lz4` - lz4\n* `snappy` - snappy"+ },+ "format": {+ "default": "Parquet",+ "description": "File format\n\n* `Parquet` - Parquet\n* `JSONLines` - JSONLines",+ "enum": ["Parquet", "JSONLines"],+ "type": "string"+ },+ "max_size_mb": {+ "anyOf": [+ {+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Split download into multiple files of at most this size in MB"+ }+ },+ "type": "object"+ },+ "hogql_query": {+ "description": "HogQL SELECT query whose results are exported. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. The query runs as of thetime the export starts; events ingested moments before may not be included yet.",+ "type": "string"+ },+ "model": {+ "enum": ["hogql"],+ "type": "string"+ }+ },+ "required": ["file", "model", "hogql_query"],+ "type": "object"}]}