Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(batch-exports): Support scheduled hogql model exports (#101791)

Tomás Farías Santana58fbad1a16bf
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.py
index 91a88b9461a8..9d24aa5d112d 100644
--- a/products/batch_exports/backend/api/batch_export.py
+++ b/products/batch_exports/backend/api/batch_export.py
@@ -13,7 +13,6 @@ from django.utils.timezone import now
import structlog
import posthoganalytics
-from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import filters, mixins, request, response, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotAuthenticated, NotFound, PermissionDenied, ValidationError
@@ -54,7 +53,15 @@ from posthog.utils import relative_date_parse, str_to_bool
from products.access_control.backend.facade.api import get_restricted_properties_with_group_type_index_for_team
from products.batch_exports.backend.api.destination_tests import get_destination_test
-from products.batch_exports.backend.hogql_source import serialize_batch_export_query
+from products.batch_exports.backend.api.utils import check_hogql_batch_exports_enabled
+from products.batch_exports.backend.hogql_source import (
+ DATA_INTERVAL_START_PLACEHOLDER,
+ UnsupportedHogQLQueryError,
+ find_interval_placeholders,
+ parse_hogql_select_for_batch_export,
+ serialize_batch_export_query,
+ validate_hogql_query_for_batch_export,
+)
from products.batch_exports.backend.models.batch_export import (
BATCH_EXPORT_INTERVALS,
OBJECT_STORAGE_DESTINATIONS,
@@ -64,6 +71,7 @@ from products.batch_exports.backend.models.batch_export import (
BatchExportBackfill,
BatchExportDestination,
BatchExportRun,
+ BatchExportSource,
)
from products.batch_exports.backend.service import (
DESTINATION_WORKFLOWS,
@@ -808,6 +816,17 @@ class BatchExportDestinationRequestField(serializers.JSONField):
pass
+HOGQL_QUERY_HELP_TEXT = (
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. "
+ "The query may reference the {data_interval_start} and {data_interval_end} placeholders, "
+ "replaced with each run's data interval bounds, for example: "
+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. "
+ "Without them every run exports all rows the query returns. "
+ "With model 'events', it defines a custom schema of columns to export instead. "
+ "Required when model is 'hogql'."
+)
+
+
class BatchExportRequestSerializer(serializers.Serializer):
"""Request body for create/partial_update on BatchExportViewSet.
@@ -820,7 +839,10 @@ class BatchExportRequestSerializer(serializers.Serializer):
model = serializers.ChoiceField(
choices=BatchExport.Model.choices,
required=False,
- help_text="Which data model to export (events, persons, sessions).",
+ help_text=(
+ "Which data model to export: events, persons, sessions, or hogql. "
+ "The hogql model exports the results of hogql_query."
+ ),
)
destination = BatchExportDestinationRequestField(
help_text="Destination configuration. Required integration_id is enforced per destination type.",
@@ -832,7 +854,8 @@ class BatchExportRequestSerializer(serializers.Serializer):
paused = serializers.BooleanField(required=False, help_text="Whether the batch export is paused.")
hogql_query = serializers.CharField(
required=False,
- help_text="Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.",
+ allow_null=True,
+ help_text=HOGQL_QUERY_HELP_TEXT,
)
filters = serializers.JSONField(
required=False,
@@ -1094,45 +1117,41 @@ def try_convert_to_type(value: typing.Any, target_type: type) -> tuple[typing.An
return (new_value, True)
-@extend_schema_field(OpenApiTypes.STR)
-class HogQLSelectQueryField(serializers.Field):
- def to_internal_value(self, data: str) -> ast.SelectQuery | ast.SelectSetQuery:
- """Parse a HogQL SelectQuery from a string query."""
- try:
- parsed_query = parse_select(data)
- except Exception:
- raise serializers.ValidationError("Failed to parse query")
+def parse_events_hogql_query(hogql_query: str, team_id: int, user: User | None) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Parse a HogQL SelectQuery from a string query."""
+ try:
+ parsed_query = parse_select(hogql_query)
+ except Exception:
+ raise serializers.ValidationError("Failed to parse query")
- try:
- restricted_properties = get_restricted_properties_with_group_type_index_for_team(
- user=self.context["request"].user, team_id=self.context["team_id"]
- )
- context = HogQLContext(
- team_id=self.context["team_id"],
- user=self.context["request"].user,
- enable_select_queries=True,
- restricted_properties=restricted_properties,
- modifiers=HogQLQueryModifiers(
- personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
- ),
- )
- if restricted_properties:
- # A restricted query is stored without its HogQL text, so no run can recompile it for
- # the native source, where a materialized column does not exist.
- context.modifiers.materializationMode = MaterializationMode.DISABLED
- use_native_schema = context.uses_new_events_schema()
- prepared_select_query = cast(
- ast.SelectQuery,
- prepare_ast_for_printing(
- parsed_query, context=context, dialect="hogql" if use_native_schema else "clickhouse"
- ),
- )
- if use_native_schema:
- resolve_types(clone_expr(parsed_query, clear_types=True), context=context, dialect="clickhouse")
- except errors.ExposedHogQLError as e:
- raise serializers.ValidationError(f"Invalid HogQL query: {e}")
+ try:
+ restricted_properties = get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team_id)
+ context = HogQLContext(
+ team_id=team_id,
+ user=user,
+ enable_select_queries=True,
+ restricted_properties=restricted_properties,
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ )
+ if restricted_properties:
+ # A restricted query is stored without its HogQL text, so no run can recompile it for
+ # the native source, where a materialized column does not exist.
+ context.modifiers.materializationMode = MaterializationMode.DISABLED
+ use_native_schema = context.uses_new_events_schema()
+ prepared_select_query = cast(
+ ast.SelectQuery,
+ prepare_ast_for_printing(
+ parsed_query, context=context, dialect="hogql" if use_native_schema else "clickhouse"
+ ),
+ )
+ if use_native_schema:
+ resolve_types(clone_expr(parsed_query, clear_types=True), context=context, dialect="clickhouse")
+ except errors.ExposedHogQLError as e:
+ raise serializers.ValidationError(f"Invalid HogQL query: {e}")
- return prepared_select_query
+ return prepared_select_query
class _SubqueryFinder(TraversingVisitor):
@@ -1182,9 +1201,10 @@ class BatchExportSerializer(serializers.ModelSerializer):
choices=BATCH_EXPORT_INTERVALS,
help_text="How often the batch export should run.",
)
- hogql_query = HogQLSelectQueryField(
+ hogql_query = serializers.CharField(
required=False,
- help_text="Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.",
+ allow_null=True,
+ help_text=HOGQL_QUERY_HELP_TEXT,
)
timezone = serializers.ChoiceField(
choices=TIMEZONES,
@@ -1283,8 +1303,28 @@ class BatchExportSerializer(serializers.ModelSerializer):
raise serializers.ValidationError("offset_hour is not applicable for non-daily/weekly intervals")
attrs["interval_offset"] = None
+ self._validate_model_query(attrs)
+
return attrs
+ def _validate_model_query(self, attrs: dict) -> None:
+ """Validate `hogql_query` for the model the batch export ends up with."""
+ current_model = (self.instance.model if self.instance is not None else None) or BatchExport.Model.EVENTS
+ model = attrs.get("model") or current_model
+
+ if self.instance is not None and model != current_model and BatchExport.Model.HOGQL in (model, current_model):
+ raise serializers.ValidationError(
+ {"model": "Changing the model to or from 'hogql' is not supported. Create a new batch export instead."}
+ )
+
+ if model == BatchExport.Model.HOGQL:
+ self._validate_hogql(attrs)
+ return
+
+ if (hogql_query := attrs.get("hogql_query")) is not None:
+ # For events model, we need the resolved AST.
+ attrs["hogql_query"] = self._validate_events_hogql_query(hogql_query)
+
def validate_interval(self, interval: str) -> str:
"""Validate sub-hour frequency intervals are only available when feature flag is enabled."""
team_id = self.context["team_id"]
@@ -1384,26 +1424,6 @@ class BatchExportSerializer(serializers.ModelSerializer):
)
return filters
- def validate_model(self, model) -> str:
- if model == "hogql":
- team_id = self.context["team_id"]
- team = Team.objects.get(id=team_id)
- 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.")
-
- return model
-
# TODO: could this be moved inside BatchExportDestinationSerializer::validate?
def validate_destination(self, destination_attrs: dict):
destination_type = destination_attrs["type"]
@@ -1717,21 +1737,29 @@ class BatchExportSerializer(serializers.ModelSerializer):
"""Create a BatchExport."""
destination_data = validated_data.pop("destination")
team_id = self.context["team_id"]
+ model = validated_data.get("model") or BatchExport.Model.EVENTS
+ hogql_query = validated_data.pop("hogql_query", None)
- hogql_query = None
- if hogql_query := validated_data.pop("hogql_query", None):
- batch_export_schema = self.serialize_hogql_query_to_batch_export_schema(hogql_query)
- validated_data["schema"] = batch_export_schema
+ source = None
+ if model == BatchExport.Model.HOGQL:
+ source = BatchExportSource(team_id=team_id, hogql_query=hogql_query)
+ elif hogql_query is not None:
+ # TODO: Migrate batch exports using a HogQL query to HogQL model.
+ validated_data["schema"] = self.serialize_hogql_query_to_batch_export_schema(hogql_query)
_set_default_parquet_extension(destination_data["type"], destination_data["config"])
destination = BatchExportDestination(**destination_data)
- batch_export = BatchExport(team_id=team_id, destination=destination, **validated_data)
+ batch_export = BatchExport(team_id=team_id, destination=destination, source=source, **validated_data)
sync_batch_export(batch_export, created=True)
with transaction.atomic():
destination.save()
+
+ if source is not None:
+ source.save()
+
batch_export.save()
return batch_export
@@ -1763,7 +1791,32 @@ class BatchExportSerializer(serializers.ModelSerializer):
schema.pop("hogql_query", None)
return schema
- def validate_hogql_query(self, hogql_query: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:
+ def _validate_hogql(self, attrs: dict[str, typing.Any]) -> None:
+ """Validate the source of a batch export with the 'hogql' model.
+
+ On update, a query missing from the request keeps the one stored in the source.
+ """
+ if attrs.get("filters"):
+ raise serializers.ValidationError({"filters": "'filters' are not supported when 'model' is 'hogql'"})
+
+ team = self.context["get_team"]()
+ check_hogql_batch_exports_enabled(team)
+
+ source = self.instance.source if self.instance is not None else None
+ if source is not None and "hogql_query" not in attrs:
+ return
+
+ hogql_query = attrs.get("hogql_query", source.hogql_query if source is not None else None)
+ if not hogql_query:
+ raise serializers.ValidationError({"hogql_query": "'hogql_query' is required when 'model' is 'hogql'"})
+
+ user = self.context["request"].user
+ try:
+ validate_hogql_query_for_batch_export(hogql_query, team, user=user)
+ except UnsupportedHogQLQueryError as e:
+ raise serializers.ValidationError({"hogql_query": str(e)}) from e
+
+ def _validate_events_hogql_query(self, hogql_query: str) -> ast.SelectQuery:
"""Validate a HogQL query being used for events batch exports.
This method essentially checks that a query is supported by batch exports:
@@ -1773,11 +1826,14 @@ class BatchExportSerializer(serializers.ModelSerializer):
4. Subqueries in SELECT expressions are not supported.
5. Query must select only from those fields we expose from the events table.
"""
+ parsed = parse_events_hogql_query(
+ hogql_query, team_id=self.context["team_id"], user=self.context["request"].user
+ )
- if isinstance(hogql_query, ast.SelectSetQuery):
+ if isinstance(parsed, ast.SelectSetQuery):
raise serializers.ValidationError("UNIONs are not supported")
- parsed = cast(ast.SelectQuery, hogql_query)
+ parsed = cast(ast.SelectQuery, parsed)
if parsed.select_from is None:
raise serializers.ValidationError("Query must SELECT FROM events")
@@ -1815,11 +1871,13 @@ class BatchExportSerializer(serializers.ModelSerializer):
f"Supported fields are: {', '.join(sorted(EXPORTABLE_EVENTS_MODEL_FIELDS))}."
)
- return hogql_query
+ return parsed
def update(self, batch_export: BatchExport, validated_data: dict) -> BatchExport:
"""Update a BatchExport."""
destination_data = validated_data.pop("destination", None)
+ hogql_query_provided = "hogql_query" in validated_data
+ hogql_query = validated_data.pop("hogql_query", None)
with transaction.atomic():
if destination_data:
@@ -1833,9 +1891,16 @@ class BatchExportSerializer(serializers.ModelSerializer):
integration = destination_data.get("integration", batch_export.destination.integration)
batch_export.destination.integration = integration
- if hogql_query := validated_data.pop("hogql_query", None):
- batch_export_schema = self.serialize_hogql_query_to_batch_export_schema(hogql_query)
- validated_data["schema"] = batch_export_schema
+ if batch_export.model == BatchExport.Model.HOGQL:
+ if hogql_query is not None:
+ source = batch_export.source or BatchExportSource(team_id=batch_export.team_id)
+ source.hogql_query = hogql_query
+ source.save()
+ batch_export.source = source
+ elif hogql_query is not None:
+ validated_data["schema"] = self.serialize_hogql_query_to_batch_export_schema(hogql_query)
+ elif hogql_query_provided:
+ validated_data["schema"] = None
batch_export.destination.save()
batch_export = super().update(batch_export, validated_data)
@@ -1881,7 +1946,12 @@ def recursive_dict_merge(
)
class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelViewSet):
scope_object = "batch_export"
- queryset = BatchExport.objects.exclude(deleted=True).order_by("-created_at").prefetch_related("destination").all()
+ queryset = (
+ BatchExport.objects.exclude(deleted=True)
+ .order_by("-created_at")
+ .prefetch_related("destination", "source")
+ .all()
+ )
serializer_class = BatchExportSerializer
log_source = "batch_exports"
@@ -2136,6 +2206,18 @@ def create_backfill(
):
raise ValidationError("Backfilling from the beginning of time is not enabled for this team.")
+ if batch_export.model == BatchExport.Model.HOGQL and (hogql_query := batch_export.hogql_query) is not None:
+ try:
+ parsed = parse_hogql_select_for_batch_export(hogql_query)
+ except UnsupportedHogQLQueryError as e:
+ raise ValidationError(str(e)) from e
+ if DATA_INTERVAL_START_PLACEHOLDER in find_interval_placeholders(parsed):
+ # TODO: We should maybe support beginning-of-time backfills with this placeholder.
+ raise ValidationError(
+ "This query references {data_interval_start}, which is unavailable when backfilling from the "
+ "beginning of time. Provide 'start_at' or remove {data_interval_start} from the query."
+ )
+
concurrency_limit = settings.BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM
active_backfills = BatchExportBackfill.objects.filter(
team_id=team.pk,
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.py
index c394d3d63ded..3d595136d9e0 100644
--- a/products/batch_exports/backend/debug/debugger.py
+++ b/products/batch_exports/backend/debug/debugger.py
@@ -279,6 +279,7 @@ class BatchExportsDebugger:
name=self.batch_export.model or "events",
schema=self.batch_export.schema,
filters=self.batch_export.filters,
+ hogql_query=self.batch_export.hogql_query,
),
integration_id=self.batch_export.destination.integration_id,
**destination_config,
diff --git a/products/batch_exports/backend/models/batch_export.py b/products/batch_exports/backend/models/batch_export.py
index f5d682b668aa..8dca15a85260 100644
--- a/products/batch_exports/backend/models/batch_export.py
+++ b/products/batch_exports/backend/models/batch_export.py
@@ -504,6 +504,11 @@ class BatchExport(ModelActivityMixin, UUIDTModel):
return offset_in_hours % 24
return None
+ @property
+ def hogql_query(self) -> str | None:
+ """Return the HogQL query of this batch export's source, if it has one."""
+ return self.source.hogql_query if self.source is not None else None
+
def get_batch_exports_using_integration(team_id: int, integration_id: int) -> list[BatchExport]:
"""Return a list of batch exports using integration_id.
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 4f4fe26fd8b7..319ac34bf07b 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -25,9 +25,6 @@ from temporalio.client import (
WorkflowHandle,
)
-from posthog.hogql.database.database import Database
-from posthog.hogql.hogql import HogQLContext
-
from posthog.dataclasses import frozen
from posthog.temporal.common.client import sync_connect
from posthog.temporal.common.schedule import (
@@ -1198,15 +1195,6 @@ def sync_batch_export(batch_export: BatchExport, created: bool):
else settings.BATCH_EXPORTS_TASK_QUEUE
)
- context = HogQLContext(
- team_id=batch_export.team.id,
- enable_select_queries=True,
- limit_top_select=False,
- )
- # Export models are only events/persons/sessions; warehouse tables and views are denied.
- # Pass bypass_warehouse_access_control=True or a user if that becomes an issue.
- context.database = Database.create_for(team=batch_export.team, modifiers=context.modifiers)
-
temporal = sync_connect()
schedule = Schedule(
action=ScheduleActionStartWorkflow(
@@ -1221,6 +1209,7 @@ def sync_batch_export(batch_export: BatchExport, created: bool):
name=batch_export.model or "events",
schema=batch_export.schema,
filters=batch_export.filters,
+ hogql_query=batch_export.hogql_query,
),
# TODO: This field is deprecated, but we still set it for backwards compatibility.
# New exports created will always have `batch_export_schema` set to `None`, but existing
diff --git a/products/batch_exports/backend/tests/api/backfills/test_create.py b/products/batch_exports/backend/tests/api/backfills/test_create.py
index edde2dc2d073..1734496a4ad7 100644
--- a/products/batch_exports/backend/tests/api/backfills/test_create.py
+++ b/products/batch_exports/backend/tests/api/backfills/test_create.py
@@ -1,4 +1,5 @@
import datetime as dt
+from typing import TYPE_CHECKING
import pytest
import time_machine
@@ -13,12 +14,16 @@ from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
from posthog.models.integration import Integration
from posthog.models.person.util import create_person
+from posthog.models.scoping import team_scope
from posthog.models.team import Team
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportBackfill
-from products.batch_exports.backend.tests.api.fixtures import create_organization
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportBackfill, BatchExportSource
+from products.batch_exports.backend.tests.api.fixtures import create_destination, create_organization
from products.batch_exports.backend.tests.api.operations import backfill_batch_export, create_batch_export_ok
+if TYPE_CHECKING:
+ from posthog.models import User
+
pytestmark = [
pytest.mark.django_db,
pytest.mark.usefixtures("temporal_worker", "cleanup"),
@@ -571,3 +576,96 @@ def test_batch_export_earliest_backfill_allowed_with_feature_flag(
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert "backfill_id" in response.json()
+
+
+ "model,hogql_query,start_at,expected_error",
+ [
+ pytest.param(
+ "hogql",
+ "SELECT event FROM (SELECT event FROM events WHERE timestamp >= {data_interval_start})",
+ None,
+ "This query references {data_interval_start}",
+ id="missing-referenced-start",
+ ),
+ pytest.param(
+ "hogql",
+ "SELECT event FROM events WHERE timestamp >= {data_interval_start}",
+ "2021-01-01T00:00:00+00:00",
+ None,
+ id="explicit-start",
+ ),
+ pytest.param(
+ "hogql",
+ "SELECT event FROM events WHERE timestamp < {data_interval_end}",
+ None,
+ None,
+ id="end-only",
+ ),
+ pytest.param(
+ "hogql",
+ "SELECT '{data_interval_start}' AS literal FROM events",
+ None,
+ None,
+ id="no-placeholders",
+ ),
+ pytest.param(
+ "events",
+ "SELECT event FROM events WHERE timestamp >= {data_interval_start}",
+ None,
+ None,
+ id="events-custom-schema",
+ ),
+ pytest.param(
+ "hogql",
+ "SELECT event FROM events WHERE timestamp >= {unknown}",
+ None,
+ "Unknown placeholder '{unknown}'",
+ id="unsupported-persisted-query",
+ ),
+ ],
+)
+def test_batch_export_backfill_hogql_interval_validation(
+ client: HttpClient,
+ team: Team,
+ user: "User",
+ model: str,
+ hogql_query: str,
+ start_at: str | None,
+ expected_error: str | None,
+) -> None:
+ client.force_login(user)
+ with team_scope(team_id=team.pk):
+ source = None
+ schema = None
+ if model == BatchExport.Model.HOGQL:
+ source = BatchExportSource.objects.create(team_id=team.pk, hogql_query=hogql_query)
+ else:
+ schema = {"hogql_query": hogql_query, "fields": [{"expression": "event", "alias": "event"}]}
+ batch_export = BatchExport.objects.create(
+ team=team,
+ name="Backfill interval validation",
+ destination=create_destination(),
+ interval="hour",
+ model=model,
+ source=source,
+ schema=schema,
+ )
+
+ with (
+ patch("products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled", return_value=True),
+ patch("products.batch_exports.backend.api.batch_export.sync_connect") as connect,
+ patch("products.batch_exports.backend.api.batch_export.backfill_export") as backfill,
+ ):
+ response = backfill_batch_export(client, team.pk, str(batch_export.pk), start_at, "2021-01-01T01:00:00+00:00")
+
+ if expected_error is not None:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert expected_error in response.json()["detail"]
+ connect.assert_not_called()
+ backfill.assert_not_called()
+ else:
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert "backfill_id" in response.json()
+ backfill.assert_called_once()
+ assert backfill.call_args.kwargs["start_at"] == (dt.datetime.fromisoformat(start_at) if start_at else None)
diff --git a/products/batch_exports/backend/tests/api/conftest.py b/products/batch_exports/backend/tests/api/conftest.py
index 3d0afb2fc2b7..0d28fcc09520 100644
--- a/products/batch_exports/backend/tests/api/conftest.py
+++ b/products/batch_exports/backend/tests/api/conftest.py
@@ -1,6 +1,7 @@
import logging
import pytest
+from unittest import mock
from django.conf import settings
@@ -132,6 +133,28 @@ def s3_compatible_integration(team, user):
)
+def hogql_batch_exports_enabled():
+ """Enable the hogql-batch-exports feature flag for the duration of a test."""
+ with mock.patch(
+ "products.batch_exports.backend.api.utils.posthoganalytics.feature_enabled", return_value=True
+ ) as feature_enabled:
+ yield feature_enabled
+
+
+def hogql_batch_export_data(s3_batch_export_data) -> dict:
+ """Return the request body for creating a minimal AwsS3 batch export of a HogQL model."""
+ return {
+ **s3_batch_export_data,
+ "model": "hogql",
+ "hogql_query": (
+ "SELECT uuid AS uuid, event AS event, timestamp AS timestamp FROM events "
+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"
+ ),
+ }
+
+
@pytest.fixture
def s3_batch_export_data(aws_s3_integration) -> dict:
"""Return the request body for creating a minimal AwsS3 batch export.
diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.py
index 02f783de5270..971154ac799a 100644
--- a/products/batch_exports/backend/tests/api/test_create.py
+++ b/products/batch_exports/backend/tests/api/test_create.py
@@ -15,14 +15,14 @@ from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
from posthog.models.integration import Integration
-from products.batch_exports.backend.models.batch_export import BatchExport
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportSource
from products.batch_exports.backend.tests.api.conftest import (
assert_is_daily_schedule,
assert_is_weekly_schedule,
describe_schedule,
)
from products.batch_exports.backend.tests.api.fixtures import create_organization
-from products.batch_exports.backend.tests.api.operations import create_batch_export
+from products.batch_exports.backend.tests.api.operations import create_batch_export, list_batch_exports_ok
pytestmark = [
pytest.mark.django_db,
@@ -587,6 +587,127 @@ def test_create_batch_export_fails_with_invalid_query(
assert response.json()["detail"] == expected_error_message
[email protected]("hogql_batch_exports_enabled")
+def test_create_batch_export_with_hogql_model(
+ client: HttpClient, temporal, encryption_codec, organization, team, user, hogql_batch_export_data
+):
+ client.force_login(user)
+
+ response = create_batch_export(client, team.pk, hogql_batch_export_data)
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ data = response.json()
+ assert data["model"] == "hogql"
+ assert data["hogql_query"] == hogql_batch_export_data["hogql_query"]
+ assert data["schema"] is None
+
+ batch_export = BatchExport.objects.select_related("source").get(id=data["id"])
+ assert batch_export.source is not None
+ assert batch_export.source.team_id == team.pk
+ assert batch_export.source.hogql_query == hogql_batch_export_data["hogql_query"]
+
+ listed = list_batch_exports_ok(client, team.pk)
+ assert [export["hogql_query"] for export in listed["results"]] == [hogql_batch_export_data["hogql_query"]]
+
+ schedule = describe_schedule(temporal, data["id"])
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
+ args = json.loads(decoded_payload[0].data)
+ assert args["batch_export_model"] == {
+ "filters": None,
+ "name": "hogql",
+ "schema": None,
+ "hogql_query": hogql_batch_export_data["hogql_query"],
+ }
+
+
[email protected]("hogql_batch_exports_enabled")
+def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(
+ client: HttpClient, temporal, organization, team, user, hogql_batch_export_data
+):
+ """A query without interval placeholders is valid: every run exports all rows it returns."""
+ client.force_login(user)
+ hogql_query = "SELECT event AS event FROM events"
+
+ response = create_batch_export(client, team.pk, {**hogql_batch_export_data, "hogql_query": hogql_query})
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ batch_export = BatchExport.objects.select_related("source").get(id=response.json()["id"])
+ assert batch_export.source is not None
+ assert batch_export.source.hogql_query == hogql_query
+
+
+ "overrides,expected_attr,expected_error_message",
+ [
+ (
+ {"hogql_query": "SELECT event AS event FROM events WHERE event = {unknown_placeholder}"},
+ "hogql_query",
+ "Unknown placeholder '{unknown_placeholder}'. "
+ "Only {data_interval_start} and {data_interval_end} are supported in batch export queries",
+ ),
+ (
+ {"hogql_query": "SELECT event AS event FROM events WHERE {filters}"},
+ "hogql_query",
+ "Unsupported placeholder. "
+ "Only {data_interval_start} and {data_interval_end} are supported in batch export queries",
+ ),
+ ({"hogql_query": None}, "hogql_query", "'hogql_query' is required when 'model' is 'hogql'"),
+ (
+ {"hogql_query": "SELECT count() FROM events"},
+ "hogql_query",
+ "Every column in the SELECT clause must be a field or have an alias (e.g. `count() AS event_count`)",
+ ),
+ (
+ {"filters": [{"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}]},
+ "filters",
+ "'filters' are not supported when 'model' is 'hogql'",
+ ),
+ ],
+ ids=[
+ "unknown-placeholder",
+ "filters-placeholder",
+ "missing-hogql-query",
+ "unaliased-column",
+ "filters",
+ ],
+)
[email protected]("hogql_batch_exports_enabled")
+def test_create_batch_export_with_hogql_model_fails_with_invalid_request(
+ client: HttpClient,
+ temporal,
+ organization,
+ team,
+ user,
+ hogql_batch_export_data,
+ overrides,
+ expected_attr,
+ expected_error_message,
+):
+ client.force_login(user)
+
+ response = create_batch_export(client, team.pk, {**hogql_batch_export_data, **overrides})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == expected_attr
+ # HogQL may append field name suggestions to a resolution error, so match on the prefix.
+ assert response.json()["detail"].startswith(expected_error_message), response.json()["detail"]
+ assert BatchExportSource.objects.for_team(team.pk).count() == 0
+
+
+def test_cannot_create_batch_export_with_hogql_model_if_not_enabled(
+ client: HttpClient, temporal, organization, team, user, hogql_batch_export_data
+):
+ client.force_login(user)
+ with mock.patch(
+ "products.batch_exports.backend.api.utils.posthoganalytics.feature_enabled", return_value=False
+ ) as feature_enabled:
+ response = create_batch_export(client, team.pk, hogql_batch_export_data)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert feature_enabled.call_args[0][0] == "hogql-batch-exports"
+ assert BatchExportSource.objects.for_team(team.pk).count() == 0
+
+
@pytest.mark.parametrize(
"type,config,expected_error_message",
[
diff --git a/products/batch_exports/backend/tests/api/test_serializers.py b/products/batch_exports/backend/tests/api/test_serializers.py
index 095fa5d5785a..52b6a5e7f25b 100644
--- a/products/batch_exports/backend/tests/api/test_serializers.py
+++ b/products/batch_exports/backend/tests/api/test_serializers.py
@@ -19,16 +19,13 @@ from posthog.models.integration import Integration
from products.batch_exports.backend.api.batch_export import (
BatchExportDestinationSerializer,
BatchExportSerializer,
- HogQLSelectQueryField,
+ parse_events_hogql_query,
)
def prepare_query(query: str, team_id: int) -> ast.SelectQuery:
"""Parse and resolve a HogQL query string into a prepared AST."""
- serializer = BatchExportSerializer(context={"team_id": team_id, "request": SimpleNamespace(user=None)})
- field = HogQLSelectQueryField()
- field.bind("hogql_query", serializer)
- return cast(ast.SelectQuery, field.to_internal_value(query))
+ return cast(ast.SelectQuery, parse_events_hogql_query(query, team_id=team_id, user=None))
class TestSerializeHogQLQueryToBatchExportSchema(BaseTest):
diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.py
index 194bdbf39548..6d0fded8f4ab 100644
--- a/products/batch_exports/backend/tests/api/test_update.py
+++ b/products/batch_exports/backend/tests/api/test_update.py
@@ -709,6 +709,18 @@ def test_can_patch_hogql_query(
"hogql_query": None,
}
+ for patch_data, expected_schema in [
+ ({"name": "renamed"}, response_data["schema"]),
+ ({"hogql_query": None}, None),
+ ]:
+ response = patch_batch_export(client, team.pk, batch_export["id"], patch_data)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert get_batch_export_ok(client, team.pk, batch_export["id"])["schema"] == expected_schema
+ schedule = describe_schedule(temporal, batch_export["id"])
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
+ args = json.loads(decoded_payload[0].data)
+ assert args["batch_export_model"]["schema"] == expected_schema
+
def test_patch_returns_error_on_unsupported_hogql_query(
client: HttpClient, temporal, organization, team, user, aws_s3_integration
@@ -748,6 +760,104 @@ def test_patch_returns_error_on_unsupported_hogql_query(
assert response.status_code == status.HTTP_400_BAD_REQUEST
[email protected]("hogql_enabled", [True, False], ids=["enabled", "disabled"])
+def test_patch_hogql_model_batch_export(
+ client: HttpClient,
+ temporal,
+ encryption_codec,
+ organization,
+ team,
+ user,
+ hogql_batch_export_data,
+ hogql_batch_exports_enabled,
+ hogql_enabled: bool,
+):
+ client.force_login(user)
+ batch_export = create_batch_export_ok(client, team.pk, hogql_batch_export_data)
+ source_id = BatchExport.objects.get(id=batch_export["id"]).source_id
+ hogql_batch_exports_enabled.return_value = hogql_enabled
+
+ # A change that does not touch the source keeps it as it is.
+ response = patch_batch_export(client, team.pk, batch_export["id"], {"name": "renamed"})
+ if not hogql_enabled:
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ unchanged = get_batch_export_ok(client, team.pk, batch_export["id"])
+ assert unchanged["name"] == batch_export["name"]
+ assert unchanged["hogql_query"] == hogql_batch_export_data["hogql_query"]
+ return
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ renamed = get_batch_export_ok(client, team.pk, batch_export["id"])
+ assert renamed["name"] == "renamed"
+ assert renamed["hogql_query"] == hogql_batch_export_data["hogql_query"]
+
+ # A query without interval placeholders is as valid as a bounded one.
+ new_hogql_query = "SELECT uuid AS uuid, created_at AS created_at FROM events"
+ response = patch_batch_export(
+ client,
+ team.pk,
+ batch_export["id"],
+ {"hogql_query": new_hogql_query},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ updated = get_batch_export_ok(client, team.pk, batch_export["id"])
+ assert updated["hogql_query"] == new_hogql_query
+ assert BatchExport.objects.get(id=batch_export["id"]).source_id == source_id
+
+ schedule = describe_schedule(temporal, batch_export["id"])
+ decoded_payload = async_to_sync(encryption_codec.decode)(schedule.schedule.action.args)
+ args = json.loads(decoded_payload[0].data)
+ assert args["batch_export_model"] == {
+ "filters": None,
+ "name": "hogql",
+ "schema": None,
+ "hogql_query": new_hogql_query,
+ }
+
+
[email protected]("hogql_batch_exports_enabled")
[email protected]("hogql_query", ["SELECT does_not_exist AS does_not_exist FROM events", None])
+def test_patch_hogql_model_batch_export_validates_new_query(
+ client: HttpClient, temporal, organization, team, user, hogql_batch_export_data, hogql_query: str | None
+):
+ client.force_login(user)
+ batch_export = create_batch_export_ok(client, team.pk, hogql_batch_export_data)
+
+ response = patch_batch_export(client, team.pk, batch_export["id"], {"hogql_query": hogql_query})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "hogql_query"
+ assert (
+ get_batch_export_ok(client, team.pk, batch_export["id"])["hogql_query"]
+ == (hogql_batch_export_data["hogql_query"])
+ )
+
+
[email protected]("from_model,to_model", [("events", "hogql"), ("hogql", "events")])
[email protected]("hogql_batch_exports_enabled")
+def test_patch_rejects_model_change_to_or_from_hogql(
+ client: HttpClient,
+ temporal,
+ organization,
+ team,
+ user,
+ s3_batch_export_data,
+ hogql_batch_export_data,
+ from_model,
+ to_model,
+):
+ client.force_login(user)
+ create_data = hogql_batch_export_data if from_model == "hogql" else s3_batch_export_data
+ batch_export = create_batch_export_ok(client, team.pk, create_data)
+
+ response = patch_batch_export(client, team.pk, batch_export["id"], {"model": to_model})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "model"
+ assert get_batch_export_ok(client, team.pk, batch_export["id"])["model"] == from_model
+
+
@pytest.fixture
def databricks_integration(team, user):
"""Create a Databricks integration."""
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
index 05a7824fca29..b2af89513466 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_local_object_storage.py
@@ -362,3 +362,56 @@ async def test_s3_export_workflow_with_local_object_storage_and_custom_key_prefi
s3_client=object_storage_client,
destination_type="S3Compatible",
)
+
+
[email protected]("interval", ["hour"], indirect=True)
[email protected]("events_table", ["sharded_events"], indirect=True)
+ "hogql_query",
+ [
+ (
+ "SELECT uuid AS uuid, event AS event, timestamp AS timestamp FROM events "
+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"
+ ),
+ "SELECT uuid AS uuid, event AS event, timestamp AS timestamp FROM events",
+ ],
+ ids=["bounded-by-interval-placeholders", "unbounded"],
+)
+async def test_s3_export_workflow_with_local_object_storage_with_hogql_model(
+ clickhouse_client,
+ object_storage_client,
+ ateam,
+ s3_compatible_batch_export,
+ bucket_name,
+ interval,
+ s3_key_prefix,
+ data_interval_start,
+ data_interval_end,
+ generate_test_data,
+ hogql_query,
+):
+ """The S3 workflow exports a HogQL model query end-to-end.
+
+ The fixture creates events in the data interval, outside it, and for another team. The
+ bounded case proves the interval placeholders are substituted with the run's bounds:
+ only the in-interval events land in the bucket. The unbounded case proves any query
+ runs, placeholders or not: every row the query returns at run time is exported.
+
+ `events_table` is pinned to `sharded_events` because the HogQL `events` table reads it,
+ while the fixture would otherwise default to `events_recent` for a recent interval.
+ """
+ model = BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query)
+
+ await run_s3_batch_export_workflow(
+ model=model,
+ ateam=ateam,
+ batch_export_id=str(s3_compatible_batch_export.id),
+ integration_id=s3_compatible_batch_export.destination.integration_id,
+ s3_destination_config=s3_compatible_batch_export.destination.config,
+ interval=interval,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ clickhouse_client=clickhouse_client,
+ s3_client=object_storage_client,
+ destination_type="S3Compatible",
+ )
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
index dca19ba312a3..c21657fda45c 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
@@ -17,9 +17,12 @@ from temporalio.testing import WorkflowEnvironment
from temporalio.testing._activity import ActivityEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.hogql import ast
+
from posthog.temporal.common.clickhouse import ClickHouseClient
from posthog.temporal.tests.utils.models import afetch_batch_export_runs
+from products.batch_exports.backend.hogql_source import parse_hogql_select_for_batch_export
from products.batch_exports.backend.service import (
AwsS3BatchExportInputs,
BackfillDetails,
@@ -46,7 +49,10 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
insert_into_internal_stage_activity,
)
from products.batch_exports.backend.temporal.queue import RecordBatchQueue
-from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
+from products.batch_exports.backend.temporal.record_batch_model import (
+ HogQLQueryRecordBatchModel,
+ SessionsRecordBatchModel,
+)
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue
from products.batch_exports.backend.tests.temporal.utils.s3 import assert_file_in_s3, assert_no_files_in_s3
@@ -202,6 +208,25 @@ async def assert_metrics_in_clickhouse(
)
+def _hogql_model_column_names(hogql_query: str | None) -> list[str]:
+ """Return the column names a HogQL model query exports.
+
+ In a set operation (e.g. UNION ALL) the first SELECT names the output columns.
+ """
+ parsed = parse_hogql_select_for_batch_export(hogql_query or "")
+ select_query = parsed
+ while isinstance(select_query, ast.SelectSetQuery):
+ select_query = select_query.initial_select_query
+
+ columns: list[str] = []
+ for expr in select_query.select:
+ if isinstance(expr, ast.Alias):
+ columns.append(expr.alias)
+ elif isinstance(expr, ast.Field):
+ columns.append(str(expr.chain[-1]))
+ return columns
+
+
async def assert_clickhouse_records_in_s3(
s3_compatible_client,
clickhouse_client: ClickHouseClient,
@@ -285,6 +310,10 @@ async def assert_clickhouse_records_in_s3(
"created_at",
"is_deleted",
]
+ elif isinstance(batch_export_model, BatchExportModel) and batch_export_model.name == "hogql":
+ # A HogQL model exports whichever columns the query selects, so the query is the schema:
+ # the team_id check and the sort below must key off the query's own columns.
+ schema_column_names = _hogql_model_column_names(batch_export_model.hogql_query)
else:
schema_column_names = [field["alias"] for field in s3_default_fields()]
@@ -296,6 +325,16 @@ async def assert_clickhouse_records_in_s3(
queue = RecordBatchQueue()
if model_name == "sessions":
producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))
+ elif (
+ model_name == "hogql"
+ and isinstance(batch_export_model, BatchExportModel)
+ and batch_export_model.hogql_query is not None
+ ):
+ # Re-running the query itself yields the expected rows, with the same interval bounds
+ # substituted as the run exported with.
+ producer = ClickHouseTestProducer(
+ model=HogQLQueryRecordBatchModel(team_id=team_id, hogql_query=batch_export_model.hogql_query)
+ )
else:
producer = ClickHouseTestProducer()
producer_task = await producer.start(
@@ -325,6 +364,10 @@ async def assert_clickhouse_records_in_s3(
expected_record[k] = json.loads(v)
elif isinstance(v, dt.datetime):
expected_record[k] = v.isoformat()
+ elif isinstance(v, uuid.UUID):
+ # The JSONL transformer writes non-JSON types via `default=str`, so
+ # uuid columns land in the file as strings.
+ expected_record[k] = str(v)
else:
expected_record[k] = v
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.py
index 19666e8dc05d..cb9350689c05 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
@@ -1449,10 +1449,9 @@ class TestHogQLModel:
):
"""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.
+ These queries reference no interval placeholders, so each 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
@@ -1474,6 +1473,55 @@ class TestHogQLModel:
)
mock_wait.assert_not_called()
+ async def test_stages_expected_data_bounded_by_interval_placeholders(
+ self,
+ hogql_model_test_data,
+ activity_environment,
+ object_storage_client,
+ ateam,
+ data_interval_start,
+ data_interval_end,
+ ):
+ """A query referencing the interval placeholders stages only rows within the run's interval.
+
+ The run covers the second half of the fixture's interval, so events stamped at the
+ interval start are excluded and those stamped later are kept. The wait for the interval
+ end is part of the contract too: a query bounded by the interval end must let
+ replication lag settle before reading, or the run misses rows that settle after it
+ queries.
+ """
+ events, _ = hogql_model_test_data
+ # Each person's events are stamped at either end of the fixture's interval, so halving
+ # it leaves exactly the later ones in range.
+ bounded_start = data_interval_start + (data_interval_end - data_interval_start) / 2
+
+ 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,
+ object_storage_client=object_storage_client,
+ team_id=ateam.pk,
+ data_interval_start=bounded_start,
+ data_interval_end=data_interval_end,
+ model=BatchExportModel(
+ name="hogql",
+ schema=None,
+ hogql_query=(
+ "SELECT uuid AS uuid, timestamp AS timestamp FROM events "
+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"
+ ),
+ ),
+ )
+
+ expected_uuids = {
+ uuid.UUID(event["uuid"])
+ for event in events
+ if dt.datetime.fromisoformat(event["timestamp"]).replace(tzinfo=dt.UTC) >= bounded_start
+ }
+ assert {row["uuid"] for row in exported_rows} == expected_uuids
+ mock_wait.assert_called_once()
+
async def test_stages_expected_data_for_warehouse_view(
self,
hogql_model_test_data,
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index f36da413d296..ff0e4c7b28d2 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -671,8 +671,11 @@ export interface BatchExportApi {
end_at?: string | null
/** The 10 most recent runs of this batch export, ordered newest first. */
readonly latest_runs: readonly BatchExportRunApi[]
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null
/** A schema of custom fields to select when exporting data. */
readonly schema: unknown
filters?: unknown
@@ -1456,7 +1459,7 @@ export type BatchExportDestinationRequestApi =
export interface BatchExportRequestApi {
/** Human-readable name for the batch export. */
name: string
- /** Which data model to export (events, persons, sessions).
+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.
*
* * `events` - Events
* * `persons` - Persons
@@ -1475,8 +1478,11 @@ export interface BatchExportRequestApi {
interval: BatchExportIntervalEnumApi
/** Whether the batch export is paused. */
paused?: boolean
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null
/** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */
filters?: unknown
/**
@@ -1617,7 +1623,7 @@ export interface PaginatedBatchExportRunListApi {
export interface PatchedBatchExportRequestApi {
/** Human-readable name for the batch export. */
name?: string
- /** Which data model to export (events, persons, sessions).
+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.
*
* * `events` - Events
* * `persons` - Persons
@@ -1636,8 +1642,11 @@ export interface PatchedBatchExportRequestApi {
interval?: BatchExportIntervalEnumApi
/** Whether the batch export is paused. */
paused?: boolean
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null
/** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */
filters?: unknown
/**
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index aa49f44491c7..e4695aebd92c 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -41,7 +41,7 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
.describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql')
.optional()
.describe(
- 'Which data model to export (events, persons, sessions).\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
+ 'Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
),
destination: zod
.union([
@@ -445,8 +445,10 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
paused: zod.boolean().optional().describe('Whether the batch export is paused.'),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod
.unknown()
.optional()
@@ -755,7 +757,7 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
.describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql')
.optional()
.describe(
- 'Which data model to export (events, persons, sessions).\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
+ 'Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
),
destination: zod
.union([
@@ -1159,8 +1161,10 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
paused: zod.boolean().optional().describe('Whether the batch export is paused.'),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod
.unknown()
.optional()
@@ -1222,7 +1226,7 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
.describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql')
.optional()
.describe(
- 'Which data model to export (events, persons, sessions).\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
+ 'Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
),
destination: zod
.union([
@@ -1632,8 +1636,10 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
paused: zod.boolean().optional().describe('Whether the batch export is paused.'),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod
.unknown()
.optional()
@@ -2083,8 +2089,10 @@ export const BatchExportsPauseCreateBody = /* @__PURE__ */ zod
.describe("Time after which any Batch Export runs won't be triggered."),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod.unknown().optional(),
timezone: zod
.union([zod.string(), zod.null()])
@@ -2546,8 +2554,10 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod
.describe("Time after which any Batch Export runs won't be triggered."),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod.unknown().optional(),
timezone: zod
.union([zod.string(), zod.null()])
@@ -2998,8 +3008,10 @@ export const BatchExportsUnpauseCreateBody = /* @__PURE__ */ zod
.describe("Time after which any Batch Export runs won't be triggered."),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod.unknown().optional(),
timezone: zod
.union([zod.string(), zod.null()])
@@ -3471,8 +3483,10 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod
.describe("Time after which any Batch Export runs won't be triggered."),
hogql_query: zod
.string()
- .optional()
- .describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
filters: zod.unknown().optional(),
timezone: zod
.union([zod.string(), zod.null()])
diff --git a/products/batch_exports/mcp/tools.yaml b/products/batch_exports/mcp/tools.yaml
index 967e00fea572..a8ffb8ee263b 100644
--- a/products/batch_exports/mcp/tools.yaml
+++ b/products/batch_exports/mcp/tools.yaml
@@ -24,8 +24,8 @@ tools:
BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a
team-scoped Integration for credentials (use integrations-list to find one). Other destination types are
permitted by the API but typically must be created via the PostHog UI because their credentials are stored
- in the destination config. Always specify the model field (events, persons, or sessions) — omitting it
- defaults to events but the field should be set explicitly.
+ in the destination config. Always specify the model field (events, persons, sessions, or hogql). Omitting it
+ defaults to events. For the hogql model, provide hogql_query.
exclude_params:
- id
- team_id
@@ -34,7 +34,6 @@ tools:
- last_paused_at
- latest_runs
- filters
- - hogql_query
- start_at
- end_at
- integration
@@ -87,7 +86,6 @@ tools:
- last_paused_at
- latest_runs
- filters
- - hogql_query
- integration
batch-exports-backfills-cancel-create:
operation: batch_exports_backfills_cancel_create
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e963f0a9f553..b6e66c878b7c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1000,7 +1000,7 @@
}
},
"batch-export-create": {
- "description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, or sessions) — omitting it defaults to events but the field should be set explicitly.",
+ "description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, sessions, or hogql). Omitting it defaults to events. For the hogql model, provide hogql_query.",
"category": "Data pipelines",
"feature": "batch_exports",
"summary": "Create batch export",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9b9077ea5e6b..e56ab4c5c426 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1015,7 +1015,7 @@
}
},
"batch-export-create": {
- "description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, or sessions) — omitting it defaults to events but the field should be set explicitly.",
+ "description": "Create a new batch export. Typed destination config schemas are available for Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible and Snowflake destinations. All of those except Snowflake require a team-scoped Integration for credentials (use integrations-list to find one). Other destination types are permitted by the API but typically must be created via the PostHog UI because their credentials are stored in the destination config. Always specify the model field (events, persons, sessions, or hogql). Omitting it defaults to events. For the hogql model, provide hogql_query.",
"category": "Data pipelines",
"feature": "batch_exports",
"summary": "Create batch export",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5fba69901701..58349f9d6967 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13704,8 +13704,11 @@ export namespace Schemas {
end_at?: string | null;
/** The 10 most recent runs of this batch export, ordered newest first. */
readonly latest_runs: readonly BatchExportRun[];
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string;
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null;
/** A schema of custom fields to select when exporting data. */
readonly schema: unknown;
filters?: unknown;
@@ -14529,7 +14532,7 @@ export namespace Schemas {
export interface BatchExportRequest {
/** Human-readable name for the batch export. */
name: string;
- /** Which data model to export (events, persons, sessions).
+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.
*
* * `events` - Events
* * `persons` - Persons
@@ -14548,8 +14551,11 @@ export namespace Schemas {
interval: BatchExportIntervalEnum;
/** Whether the batch export is paused. */
paused?: boolean;
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string;
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null;
/** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */
filters?: unknown;
/**
@@ -69217,7 +69223,7 @@ export namespace Schemas {
export interface PatchedBatchExportRequest {
/** Human-readable name for the batch export. */
name?: string;
- /** Which data model to export (events, persons, sessions).
+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.
*
* * `events` - Events
* * `persons` - Persons
@@ -69236,8 +69242,11 @@ export namespace Schemas {
interval?: BatchExportIntervalEnum;
/** Whether the batch export is paused. */
paused?: boolean;
- /** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */
- hogql_query?: string;
+ /**
+ * HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'.
+ * @nullable
+ */
+ hogql_query?: string | null;
/** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */
filters?: unknown;
/**
diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.ts
index ed81ab325b3c..9351c4554e05 100644
--- a/services/mcp/src/generated/batch_exports/api.ts
+++ b/services/mcp/src/generated/batch_exports/api.ts
@@ -61,7 +61,7 @@ export const BatchExportsCreateBody = () => zod
.describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql')
.optional()
.describe(
- 'Which data model to export (events, persons, sessions).\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
+ 'Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
),
destination: zod
.union([
@@ -455,6 +455,12 @@ export const BatchExportsCreateBody = () => zod
'How often the batch export should run.\n\n\* `hour` - hour\n\* `day` - day\n\* `week` - week\n\* `every 5 minutes` - every 5 minutes\n\* `every 15 minutes` - every 15 minutes'
),
paused: zod.boolean().optional().describe('Whether the batch export is paused.'),
+ hogql_query: zod
+ .string()
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
timezone: zod
.string()
.nullish()
@@ -528,7 +534,7 @@ export const BatchExportsPartialUpdateBody = () => zod
.describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql')
.optional()
.describe(
- 'Which data model to export (events, persons, sessions).\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
+ 'Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'
),
destination: zod
.union([
@@ -928,6 +934,12 @@ export const BatchExportsPartialUpdateBody = () => zod
'How often the batch export should run.\n\n\* `hour` - hour\n\* `day` - day\n\* `week` - week\n\* `every 5 minutes` - every 5 minutes\n\* `every 15 minutes` - every 15 minutes'
),
paused: zod.boolean().optional().describe('Whether the batch export is paused.'),
+ hogql_query: zod
+ .string()
+ .nullish()
+ .describe(
+ "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ ),
timezone: zod
.string()
.nullish()
diff --git a/services/mcp/src/tools/generated/batch_exports.ts b/services/mcp/src/tools/generated/batch_exports.ts
index 05a7589b3178..f62f7dd0c80d 100644
--- a/services/mcp/src/tools/generated/batch_exports.ts
+++ b/services/mcp/src/tools/generated/batch_exports.ts
@@ -32,6 +32,9 @@ const batchExportCreate = (): ToolBase<ReturnType<typeof BatchExportCreateSchema
if (params.paused !== undefined) {
body['paused'] = params.paused
}
+ if (params.hogql_query !== undefined) {
+ body['hogql_query'] = params.hogql_query
+ }
if (params.timezone !== undefined) {
body['timezone'] = params.timezone
}
@@ -113,6 +116,9 @@ const batchExportUpdate = (): ToolBase<ReturnType<typeof BatchExportUpdateSchema
if (params.paused !== undefined) {
body['paused'] = params.paused
}
+ if (params.hogql_query !== undefined) {
+ body['hogql_query'] = params.hogql_query
+ }
if (params.timezone !== undefined) {
body['timezone'] = params.timezone
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
index 78ef9f5be1cc..dd2b20273441 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
@@ -538,13 +538,24 @@
],
"description": "Destination configuration. Required integration_id is enforced per destination type."
},
+ "hogql_query": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ },
"interval": {
"description": "How often the batch export should run.\n\n* `hour` - hour\n* `day` - day\n* `week` - week\n* `every 5 minutes` - every 5 minutes\n* `every 15 minutes` - every 15 minutes",
"enum": ["hour", "day", "week", "every 5 minutes", "every 15 minutes"],
"type": "string"
},
"model": {
- "description": "Which data model to export (events, persons, sessions).\n\n* `events` - Events\n* `persons` - Persons\n* `sessions` - Sessions\n* `hogql` - Hogql",
+ "description": "Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n* `events` - Events\n* `persons` - Persons\n* `sessions` - Sessions\n* `hogql` - Hogql",
"enum": ["events", "persons", "sessions", "hogql"],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
index e3d05ca44bbc..f6264d7263d2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
@@ -537,6 +537,17 @@
],
"description": "Destination configuration. Required integration_id is enforced per destination type."
},
+ "hogql_query": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "HogQL SELECT query. With model 'hogql', its results are the data exported by every run. The query may reference the {data_interval_start} and {data_interval_end} placeholders, replaced with each run's data interval bounds, for example: WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}. Without them every run exports all rows the query returns. With model 'events', it defines a custom schema of columns to export instead. Required when model is 'hogql'."
+ },
"id": {
"description": "A UUID string identifying this batch export.",
"type": "string"
@@ -547,7 +558,7 @@
"type": "string"
},
"model": {
- "description": "Which data model to export (events, persons, sessions).\n\n* `events` - Events\n* `persons` - Persons\n* `sessions` - Sessions\n* `hogql` - Hogql",
+ "description": "Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.\n\n* `events` - Events\n* `persons` - Persons\n* `sessions` - Sessions\n* `hogql` - Hogql",
"enum": ["events", "persons", "sessions", "hogql"],
"type": "string"
},
diff --git a/services/mcp/tests/unit/batch-exports-generated.test.ts b/services/mcp/tests/unit/batch-exports-generated.test.ts
new file mode 100644
index 000000000000..603b3b6f1115
--- /dev/null
+++ b/services/mcp/tests/unit/batch-exports-generated.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/batch_exports'
+import type { Context } from '@/tools/types'
+
+describe('Generated batch export tools', () => {
+ it.each([
+ ['batch-export-create', 'POST'],
+ ['batch-export-update', 'PATCH'],
+ ])('%s forwards the HogQL query', async (name, method) => {
+ const request = vi.fn().mockResolvedValue({})
+ const context = {
+ api: { request },
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+ const hogqlQuery = 'SELECT event FROM events WHERE timestamp < {data_interval_end}'
+ const tool = GENERATED_TOOLS[name]!()
+ const params = tool.schema.parse({
+ id: '00000000-0000-4000-8000-000000000001',
+ name: 'Test export',
+ model: 'hogql',
+ interval: 'hour',
+ destination: { type: 'BigQuery', integration_id: 1, config: { dataset_id: 'exports' } },
+ hogql_query: hogqlQuery,
+ })
+
+ await tool.handler(context, params)
+
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({ method, body: expect.objectContaining({ hogql_query: hogqlQuery }) })
+ )
+ })
+})