: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
refactor(api): Disallow custom queries for events (#113898)
Tomás Farías Santana98c7ad5c9b3c
diff --git a/products/batch_exports/backend/presentation/views/batch_export/exports.py b/products/batch_exports/backend/presentation/views/batch_export/exports.pyindex 723c47b65185..92bdbfb127bf 100644--- a/products/batch_exports/backend/presentation/views/batch_export/exports.py+++ b/products/batch_exports/backend/presentation/views/batch_export/exports.py@@ -62,6 +62,7 @@ from products.batch_exports.backend.presentation.views.destination_tests importfrom products.batch_exports.backend.presentation.views.utils import (HOGQL_MODIFIERS_HELP_TEXT,HogQLModifiersField,+ check_high_frequency_batch_exports_enabled,check_hogql_batch_exports_enabled,)from products.batch_exports.backend.service import (@@ -93,7 +94,6 @@ HOGQL_QUERY_HELP_TEXT = ("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'.")@@ -117,7 +117,7 @@ class BatchExportRequestSerializer(serializers.Serializer):name = serializers.CharField(help_text="Human-readable name for the batch export.")model = serializers.ChoiceField(choices=BatchExport.Model.choices,- required=False,+ default=serializers.CreateOnlyDefault(BatchExport.Model.EVENTS), # type: ignore[arg-type]help_text=("Which data model to export: events, persons, sessions, or hogql. ""The hogql model exports the results of hogql_query."@@ -243,6 +243,14 @@ class _DatabaseFieldFinder(TraversingVisitor):class BatchExportSerializer(serializers.ModelSerializer):"""Serializer for a BatchExport model."""+ model = serializers.ChoiceField(+ choices=BatchExport.Model.choices,+ default=serializers.CreateOnlyDefault(BatchExport.Model.EVENTS), # type: ignore[arg-type]+ help_text=(+ "Which data model to export: events, persons, sessions, or hogql. "+ "The hogql model exports the results of hogql_query."+ ),+ )destination = destination_views.BatchExportDestinationSerializer(help_text="Destination configuration (type, config, and optional integration).")@@ -313,103 +321,182 @@ class BatchExportSerializer(serializers.ModelSerializer):read_only_fields = ["id", "team_id", "created_at", "last_updated_at", "latest_runs", "schema"]def validate(self, attrs: dict) -> dict:- """Validate the batch export configuration."""- # HTTP batch exports only support the events model+ """Validate this batch export.++ Delegates to validation functions that require the full attrs to complete+ validation.+ """+ attrs = self._validate_interval_offset(attrs)++ model = self._get_model(attrs)destination = attrs.get("destination")if destination and destination.get("type") == BatchExportDestination.Destination.HTTP:- model = attrs.get("model")- if model is not None and model != "events":+ if model != BatchExport.Model.EVENTS:raise serializers.ValidationError("HTTP batch exports only support the events model")- # Convert offset_day and offset_hour to interval_offset- interval = attrs.get("interval")- if interval is not None:- # Check if offset fields are in the request (for PATCH, distinguish between absent and None)- offset_day_provided = "offset_day" in attrs- offset_hour_provided = "offset_hour" in attrs- offset_day = attrs.pop("offset_day", None)- offset_hour = attrs.pop("offset_hour", None)-- if interval == "day":- # For daily exports, only offset_hour is used- if offset_day_provided and offset_day is not None:- raise serializers.ValidationError("offset_day should not be specified for daily intervals")-- if offset_hour_provided:- # User explicitly provided offset_hour (even if None)- attrs["interval_offset"] = offset_hour * 3600 if offset_hour is not None else None- elif not self.partial:- # PUT or new instance: default to None if not provided- attrs["interval_offset"] = None- # otherwise if a PATCH and offset_hour is not provided, don't set interval_offset in attrs- # to preserve existing value- elif interval == "week":- # For weekly exports, both offset_day and offset_hour are used- if offset_day_provided or offset_hour_provided:- day = offset_day or 0- hour = offset_hour or 0- attrs["interval_offset"] = day * 86400 + hour * 3600- elif not self.partial:- # PUT or new instance: default to None if not provided- attrs["interval_offset"] = None- # otherwise if a PATCH and offset fields not provided, don't set interval_offset in attrs- # to preserve existing value+ self._validate_attribute_only_supported_for_model(attrs, name="filters", model=BatchExport.Model.EVENTS)+ self._validate_attribute_only_supported_for_model(attrs, name="hogql_modifiers", model=BatchExport.Model.HOGQL)++ # TODO: Once these teams are migrated, remove this.+ if model == BatchExport.Model.EVENTS and (hogql_query := attrs.get("hogql_query")) is not None:+ is_grandfathered_team_id = BatchExport.objects.filter(+ schema__isnull=False, team=self.context["get_team"]()+ ).exists()+ if is_grandfathered_team_id:+ attrs["hogql_query"] = self._validate_events_hogql_query(hogql_query)else:- # For other intervals, reset interval_offset to None- # Also validate that offset fields are not provided- if offset_day_provided and offset_day is not None:- raise serializers.ValidationError("offset_day is not applicable for non-daily/weekly intervals")- if offset_hour_provided and offset_hour is not None:- raise serializers.ValidationError("offset_hour is not applicable for non-daily/weekly intervals")- attrs["interval_offset"] = None+ self._validate_attribute_only_supported_for_model(+ attrs, name="hogql_query", model=BatchExport.Model.HOGQL+ )+ else:+ self._validate_attribute_only_supported_for_model(attrs, name="hogql_query", model=BatchExport.Model.HOGQL)- self._validate_model_query(attrs)+ if model == BatchExport.Model.HOGQL:+ self._validate_hogql_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+ def _validate_interval_offset(self, attrs: dict) -> dict:+ interval = attrs.get("interval")- 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 interval is None:+ return attrs- if model == BatchExport.Model.HOGQL:- self._validate_hogql(attrs)+ # Convert offset_day and offset_hour to interval_offset+ # Check if offset fields are in the request (for PATCH, distinguish between absent and None)+ offset_day_provided = "offset_day" in attrs+ offset_hour_provided = "offset_hour" in attrs+ offset_day = attrs.pop("offset_day", None)+ offset_hour = attrs.pop("offset_hour", None)++ if interval == "day":+ # For daily exports, only offset_hour is used+ if offset_day_provided and offset_day is not None:+ raise serializers.ValidationError(+ {"offset_day": "offset_day should not be specified for daily intervals"}+ )++ if offset_hour_provided:+ # User explicitly provided offset_hour (even if None)+ attrs["interval_offset"] = offset_hour * 3600 if offset_hour is not None else None+ elif not self.partial:+ # PUT or new instance: default to None if not provided+ attrs["interval_offset"] = None+ # otherwise if a PATCH and offset_hour is not provided, don't set interval_offset in attrs+ # to preserve existing value+ elif interval == "week":+ # For weekly exports, both offset_day and offset_hour are used+ if offset_day_provided or offset_hour_provided:+ day = offset_day or 0+ hour = offset_hour or 0+ attrs["interval_offset"] = day * 86400 + hour * 3600+ elif not self.partial:+ # PUT or new instance: default to None if not provided+ attrs["interval_offset"] = None+ # otherwise if a PATCH and offset fields not provided, don't set interval_offset in attrs+ # to preserve existing value+ else:+ # For other intervals, reset interval_offset to None+ # Also validate that offset fields are not provided+ if offset_day_provided and offset_day is not None:+ raise serializers.ValidationError(+ {"offset_day": "offset_day is not applicable for non-daily/weekly intervals"}+ )+ if offset_hour_provided and offset_hour is not None:+ raise serializers.ValidationError(+ {"offset_hour": "offset_hour is not applicable for non-daily/weekly intervals"}+ )+ attrs["interval_offset"] = None++ return attrs++ def _get_model(self, attrs: dict[str, typing.Any]) -> str:+ """Return this batch export's model, from `attrs` or current instance."""+ if self.instance is None:+ this_model: str = attrs["model"] # Has a default, must be present+ else:+ # NOTE: We validate that model cannot change in validate_model, so+ # whether is present in attrs or not is irrelevant.+ this_model = self.instance.model+ return this_model++ def _validate_attribute_only_supported_for_model(+ self, attrs: dict[str, typing.Any], *, name: str, model: str+ ) -> None:+ """Validates attribute `name` is only provided for supported `model`.++ Raises:+ ValidationError: When this batch export's model is not `model` and+ a non-None `name` attribute value was included in the request.+ """+ if attrs.get(name) is None:return- if attrs.get("hogql_modifiers") is not None:+ this_model = self._get_model(attrs)+ if this_model != model:raise serializers.ValidationError(- {"hogql_modifiers": "'hogql_modifiers' are only supported when 'model' is 'hogql'"}+ {name: f"'{name}' is only supported for '{model}' not '{this_model}' model"})- 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_hogql_query(self, attrs: dict[str, typing.Any]) -> None:+ """Validate `hogql_query` for this batch export.++ Raises:+ ValidationError: When any of the following:+ 1. No hogql_query was passed for a HogQL model.+ 2. When a non-None hogql_query for a HogQL model is unsupported.+ """+ source = self.instance.source if self.instance is not None else None+ saved_query = source.hogql_query if source is not None else None++ hogql_query = attrs.get("hogql_query", saved_query)+ if hogql_query is None:+ raise serializers.ValidationError({"hogql_query": "'hogql_query' is required when 'model' is 'hogql'"})++ user = self.context["request"].user+ team = self.context["get_team"]()+ hogql_modifiers = self._get_hogql_modifiers(attrs)+ try:+ validate_hogql_query_for_batch_export(hogql_query, team, user=user, modifiers=hogql_modifiers)+ except UnsupportedHogQLQueryError as e:+ raise serializers.ValidationError({"hogql_query": str(e)}) from e++ def _get_hogql_modifiers(self, attrs: dict[str, typing.Any]) -> HogQLQueryModifiers | None:+ if "hogql_modifiers" in attrs:+ if attrs["hogql_modifiers"] is None:+ modifiers: HogQLQueryModifiers | None = None+ else:+ # Modifiers were already validated and loaded by the field+ field = typing.cast(HogQLModifiersField, self.fields["hogql_modifiers"])+ modifiers = field.loaded+ else:+ source = self.instance.source if self.instance is not None else None+ # Modifiers are valid if present in the db, even if the function+ # re-validates them anyways.+ modifiers = load_hogql_modifiers(source.hogql_modifiers if source is not None else None)++ return modifiers++ def validate_model(self, model: str) -> str:+ """Validate the model is new or not changing when provided."""+ if model == BatchExport.Model.HOGQL:+ team = self.context["get_team"]()+ check_hogql_batch_exports_enabled(team=team)++ if self.instance is None:+ return model++ current_model = self.instance.model+ if model != current_model:+ raise serializers.ValidationError("Changing models is not supported. Create a new batch export instead.")++ return modeldef 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"]-if interval not in ("hour", "day", "week"):- team = Team.objects.get(id=team_id)-- if not posthoganalytics.feature_enabled(- "high-frequency-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("Higher frequency batch exports are not enabled for this team.")+ team = self.context["get_team"]()+ check_high_frequency_batch_exports_enabled(team=team)return intervaldef validate_timezone(self, timezone: str | None) -> str | None:@@ -778,7 +865,7 @@ 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+ model = validated_data["model"]hogql_query = validated_data.pop("hogql_query", None)hogql_modifiers = validated_data.pop("hogql_modifiers", None)@@ -843,35 +930,6 @@ class BatchExportSerializer(serializers.ModelSerializer):schema.pop("hogql_query", None)return schema- 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 or modifiers missing from the request keep the ones 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- 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'"})-- try:- modifiers = load_hogql_modifiers(- attrs.get("hogql_modifiers", source.hogql_modifiers if source is not None else None)- )- except UnsupportedHogQLQueryError as e:- raise serializers.ValidationError({"hogql_modifiers": str(e)}) from e-- user = self.context["request"].user- try:- validate_hogql_query_for_batch_export(hogql_query, team, user=user, modifiers=modifiers)- 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.diff --git a/products/batch_exports/backend/presentation/views/utils.py b/products/batch_exports/backend/presentation/views/utils.pyindex 56a8d588a7d0..5149236d675f 100644--- a/products/batch_exports/backend/presentation/views/utils.py+++ b/products/batch_exports/backend/presentation/views/utils.py@@ -35,10 +35,29 @@ def check_hogql_batch_exports_enabled(team: Team) -> None:raise PermissionDenied("HogQL batch exports are not enabled for this team.")+def check_high_frequency_batch_exports_enabled(team: Team) -> None:+ """Raise if high-frequency batch exports are not enabled for the team."""+ if not posthoganalytics.feature_enabled(+ "high-frequency-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("Higher frequency batch exports are not enabled for this team.")++@extend_schema_field(HogQLQueryModifiers) # type: ignore[arg-type]class HogQLModifiersField(serializers.JSONField):"""HogQL modifiers, validated against `HogQLQueryModifiers` and stored as a plain dict."""+ loaded: HogQLQueryModifiers | None = None+def to_internal_value(self, data: typing.Any) -> dict[str, typing.Any]:value = super().to_internal_value(data)try:@@ -49,4 +68,6 @@ class HogQLModifiersField(serializers.JSONField):location = ".".join(str(part) for part in error["loc"])messages.append(f"{location}: {error['msg']}" if location else error["msg"])raise serializers.ValidationError(messages) from e+ else:+ self.loaded = modifiersreturn modifiers.model_dump(mode="json", exclude_none=True)diff --git a/products/batch_exports/backend/tests/api/conftest.py b/products/batch_exports/backend/tests/api/conftest.pyindex 6ecd1c42ae03..3e50785ab38f 100644--- a/products/batch_exports/backend/tests/api/conftest.py+++ b/products/batch_exports/backend/tests/api/conftest.py@@ -1,4 +1,5 @@import logging+from collections.abc import Iteratorimport pytestfrom unittest import mock@@ -14,12 +15,18 @@ from temporalio.client import ()from temporalio.service import RPCError+from posthog.models import Teamfrom posthog.models.integration import Integrationfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.codec import EncryptionCodecfrom products.batch_exports.backend.models.batch_export import BATCH_EXPORT_INTERVAL_TO_START_JITTER, BatchExport-from products.batch_exports.backend.tests.api.fixtures import create_organization, create_team, create_user+from products.batch_exports.backend.tests.api.fixtures import (+ create_destination,+ create_organization,+ create_team,+ create_user,+)from products.batch_exports.backend.tests.api.operations import start_test_worker@@ -98,6 +105,26 @@ def user(organization):return create_user("[email protected]", "Test User", organization)+def grandfathered_batch_export(team: Team, request: pytest.FixtureRequest) -> Iterator[BatchExport]:+ export_team = team if getattr(request, "param", True) else create_team(team.organization)+ destination = create_destination()+ batch_export = BatchExport.objects.create(+ team=export_team,+ name="Legacy custom schema export",+ destination=destination,+ interval="hour",+ schema={+ "fields": [{"expression": "events.uuid", "alias": "uuid"}],+ "values": {},+ "hogql_query": "SELECT uuid FROM events",+ },+ )+ yield batch_export+ batch_export.delete()+ destination.delete()++@pytest.fixturedef aws_s3_integration(team, user):return Integration.objects.create(diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex ca23741b0826..a66752584d7d 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -83,6 +83,7 @@ def test_create_batch_export_with_interval_schedule(data = response.json()+ assert data["model"] == "events"assert data["destination"] == batch_export_data["destination"]# We should match on top level fields.@@ -464,8 +465,18 @@ FROM events"""+ "grandfathered_batch_export", [True, False], indirect=True, ids=["grandfathered", "other-team"]+)def test_create_batch_export_with_custom_schema(- client: HttpClient, temporal, encryption_codec, organization, team, user, s3_batch_export_data+ client: HttpClient,+ temporal,+ encryption_codec,+ organization,+ team,+ user,+ s3_batch_export_data,+ grandfathered_batch_export,):"""Test creating a BatchExport with a custom schema expressed as a HogQL Query.@@ -485,6 +496,12 @@ def test_create_batch_export_with_custom_schema(batch_export_data,)+ if grandfathered_batch_export.team_id != team.pk:+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "hogql_query"+ assert not BatchExport.objects.filter(team=team).exists()+ return+assert response.status_code == status.HTTP_201_CREATED, response.json()data = response.json()@@ -571,6 +588,7 @@ def test_create_batch_export_with_custom_schema(),],)[email protected]("grandfathered_batch_export")def test_create_batch_export_fails_with_invalid_query(client: HttpClient,invalid_query,@@ -714,7 +732,7 @@ def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(({"filters": [{"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}]},"filters",- "'filters' are not supported when 'model' is 'hogql'",+ "'filters' is only supported for 'events' not 'hogql' model",),({"hogql_modifiers": {"notAModifier": True}},@@ -724,7 +742,7 @@ def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(({"model": "events", "hogql_modifiers": {"convertToProjectTimezone": False}},"hogql_modifiers",- "'hogql_modifiers' are only supported when 'model' is 'hogql'",+ "'hogql_modifiers' is only supported for 'hogql' not 'events' model",),],ids=[diff --git a/products/batch_exports/backend/tests/api/test_serializers.py b/products/batch_exports/backend/tests/api/test_serializers.pyindex 7114a5168860..c2dc69bd110c 100644--- a/products/batch_exports/backend/tests/api/test_serializers.py+++ b/products/batch_exports/backend/tests/api/test_serializers.py@@ -4,7 +4,7 @@ from typing import castfrom posthog.test.base import BaseTest, materializedfrom unittest.mock import patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom rest_framework import serializers@@ -16,6 +16,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.models import Organization, PropertyDefinition, Teamfrom posthog.models.integration import Integration+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.presentation.views.batch_export.destinations import BatchExportDestinationSerializerfrom products.batch_exports.backend.presentation.views.batch_export.exports import (BatchExportSerializer,@@ -23,6 +24,31 @@ from products.batch_exports.backend.presentation.views.batch_export.exports impo)+class TestBatchExportModelValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("persons", "filters", []),+ ("sessions", "filters", []),+ ("hogql", "filters", []),+ ("persons", "hogql_query", "SELECT uuid FROM events"),+ ("sessions", "hogql_query", "SELECT uuid FROM events"),+ ("events", "hogql_modifiers", {}),+ ]+ )+ def test_rejects_unsupported_fields(self, model: str, field: str, value: object) -> None:+ serializer = BatchExportSerializer(BatchExport(model=model), data={field: value}, partial=True)++ assert not serializer.is_valid()+ assert field in serializer.errors++ @parameterized.expand([("events",), ("persons",), ("sessions",)])+ def test_patch_without_model_specific_fields(self, model: str) -> None:+ serializer = BatchExportSerializer(BatchExport(model=model), data={"name": "Renamed"}, partial=True)++ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data == {"name": "Renamed"}++def prepare_query(query: str, team_id: int) -> ast.SelectQuery:"""Parse and resolve a HogQL query string into a prepared AST."""return cast(ast.SelectQuery, parse_events_hogql_query(query, team_id=team_id, user=None))diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.pyindex ed2a1cd9fd5b..d5bb3a99818d 100644--- a/products/batch_exports/backend/tests/api/test_update.py+++ b/products/batch_exports/backend/tests/api/test_update.py@@ -53,7 +53,10 @@ def bigquery_integration(team, user):)-def test_can_put_config(client: HttpClient, temporal, encryption_codec, organization, team, user, aws_s3_integration):[email protected]("model", ["events", "persons"])+def test_can_put_config(+ client: HttpClient, temporal, encryption_codec, organization, team, user, aws_s3_integration, model+):destination_data: dict[str, t.Any] = {"type": "AwsS3","integration": aws_s3_integration.id,@@ -68,6 +71,7 @@ def test_can_put_config(client: HttpClient, temporal, encryption_codec, organiza"name": "my-production-s3-bucket-destination","destination": destination_data,"interval": "hour",+ "model": model,"start_at": "2023-07-19T00:00:00+00:00","end_at": "2023-07-20T00:00:00+00:00",}@@ -110,6 +114,7 @@ def test_can_put_config(client: HttpClient, temporal, encryption_codec, organiza# get the batch export and validate e.g. that interval has been updated to daybatch_export = get_batch_export_ok(client, team.pk, batch_export["id"])+ assert batch_export["model"] == modelassert batch_export["interval"] == "day"assert batch_export["timezone"] == "UTC"assert batch_export["offset_day"] is None@@ -651,8 +656,18 @@ def test_put_rejects_destination_type_change(assert refreshed["destination"]["config"]["bucket_name"] == "my-production-s3-bucket"+ "grandfathered_batch_export", [True, False], indirect=True, ids=["grandfathered", "other-team"]+)def test_can_patch_hogql_query(- client: HttpClient, temporal, encryption_codec, organization, team, user, s3_batch_export_data+ client: HttpClient,+ temporal,+ encryption_codec,+ organization,+ team,+ user,+ s3_batch_export_data,+ grandfathered_batch_export,):"""Test we can patch a schema with a HogQL query."""client.force_login(user)@@ -670,6 +685,12 @@ def test_can_patch_hogql_query(}response = patch_batch_export(client, team.pk, batch_export["id"], new_batch_export_data)+ if grandfathered_batch_export.team_id != team.pk:+ 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"])["schema"] is None+ return+assert response.status_code == status.HTTP_200_OK, response.json()response_data: dict[str, t.Any] = get_batch_export_ok(client, team.pk, batch_export["id"])@@ -740,6 +761,7 @@ def test_can_patch_hogql_query(assert args["batch_export_model"]["schema"] == expected_schema[email protected]("grandfathered_batch_export")def test_patch_returns_error_on_unsupported_hogql_query(client: HttpClient, temporal, organization, team, user, aws_s3_integration):@@ -774,8 +796,9 @@ def test_patch_returns_error_on_unsupported_hogql_query(# toInt32 is not a supported HogQL function"hogql_query": "select toInt32(1+1) as n from events",}- response = put_batch_export(client, team.pk, batch_export["id"], new_batch_export_data)+ response = patch_batch_export(client, team.pk, batch_export["id"], new_batch_export_data)assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Unsupported function call 'toInt32(...)'" in response.json()["detail"]@pytest.mark.parametrize("hogql_enabled", [True, False], ids=["enabled", "disabled"])@@ -801,14 +824,6 @@ def test_patch_hogql_model_batch_export(response = patch_batch_export(client, team.pk, batch_export["id"], {"name": "renamed", "last_modified_by": user.pk, "user_id": user.pk})- 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"]- assert BatchExport.objects.get(id=batch_export["id"]).last_modified_by_id == user.pk- 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"@@ -847,7 +862,7 @@ def test_patch_hogql_model_batch_export(}# Modifiers can change without the query, and null removes them.- for hogql_modifiers in ({"convertToProjectTimezone": False}, None):+ for hogql_modifiers in ({"convertToProjectTimezone": False}, {}, None):response = patch_batch_export(client, team.pk, batch_export["id"], {"hogql_modifiers": hogql_modifiers})assert response.status_code == status.HTTP_200_OK, response.json()@@ -948,9 +963,12 @@ def test_patch_hogql_model_batch_export_validates_new_query()[email protected]("from_model,to_model", [("events", "hogql"), ("hogql", "events")])+ "from_model,to_model",+ [("events", "hogql"), ("hogql", "events"), ("events", "persons"), ("persons", "sessions"), ("sessions", "events")],+)@pytest.mark.usefixtures("hogql_batch_exports_enabled")-def test_patch_rejects_model_change_to_or_from_hogql(+def test_patch_rejects_model_change(client: HttpClient,temporal,organization,@@ -963,6 +981,7 @@ def test_patch_rejects_model_change_to_or_from_hogql():client.force_login(user)create_data = hogql_batch_export_data if from_model == "hogql" else s3_batch_export_data+ create_data = {**create_data, "model": from_model}batch_export = create_batch_export_ok(client, team.pk, create_data)response = patch_batch_export(client, team.pk, batch_export["id"], {"model": to_model})diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex e22fdec13cdc..c4e970e31ff7 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -22,12 +22,6 @@ export const BatchExportModelEnumApi = {Hogql: 'hogql',} as const-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]--export const BlankEnumApi = {- '': '',-} as const-/*** * `AwsS3` - Aws S3* * `S3Compatible` - S3 Compatible@@ -882,13 +876,13 @@ export interface BatchExportApi {readonly team_id: number/** A human-readable name for this BatchExport. */name: string- /** Which model this BatchExport is exporting.+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.** * `events` - Events* * `persons` - Persons* * `sessions` - Sessions* * `hogql` - Hogql */- model?: BatchExportModelEnumApi | BlankEnumApi | null+ model?: BatchExportModelEnumApi/** Destination configuration (type, config, and optional integration). */destination: BatchExportDestinationApi/** How often the batch export should run.@@ -923,7 +917,7 @@ export interface BatchExportApi {/** The 10 most recent runs of this batch export, ordered newest first. */readonly latest_runs: readonly BatchExportRunApi[]/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | null@@ -1732,7 +1726,7 @@ export interface BatchExportRequestApi {/** Whether the batch export is paused. */paused?: boolean/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | null@@ -1898,7 +1892,7 @@ export interface PatchedBatchExportRequestApi {/** Whether the batch export is paused. */paused?: boolean/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | nulldiff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex d9e1326cce53..aae8faab59e9 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -447,7 +447,7 @@ export const BatchExportsCreateBody = /* @__PURE__ */ 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([@@ -1398,7 +1398,7 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([@@ -2108,7 +2108,7 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([@@ -2402,18 +2402,11 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod.object({name: zod.string().describe('A human-readable name for this BatchExport.'),model: zod- .union([- zod- .enum(['events', 'persons', 'sessions', 'hogql'])- .describe(- '\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'- ),- zod.enum(['']),- zod.null(),- ])+ .enum(['events', 'persons', 'sessions', 'hogql'])+ .describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql').optional().describe(- 'Which model this BatchExport is exporting.\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.object({@@ -2810,7 +2803,7 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([@@ -3113,18 +3106,11 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod.object({name: zod.string().describe('A human-readable name for this BatchExport.'),model: zod- .union([- zod- .enum(['events', 'persons', 'sessions', 'hogql'])- .describe(- '\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql'- ),- zod.enum(['']),- zod.null(),- ])+ .enum(['events', 'persons', 'sessions', 'hogql'])+ .describe('\* `events` - Events\n\* `persons` - Persons\n\* `sessions` - Sessions\n\* `hogql` - Hogql').optional().describe(- 'Which model this BatchExport is exporting.\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.object({@@ -3531,7 +3517,7 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f4d04bef50cd..e1b08aa39374 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15792,13 +15792,13 @@ export namespace Schemas {readonly team_id: number;/** A human-readable name for this BatchExport. */name: string;- /** Which model this BatchExport is exporting.+ /** Which data model to export: events, persons, sessions, or hogql. The hogql model exports the results of hogql_query.** * `events` - Events* * `persons` - Persons* * `sessions` - Sessions* * `hogql` - Hogql */- model?: BatchExportModelEnum | BlankEnum | null;+ model?: BatchExportModelEnum;/** Destination configuration (type, config, and optional integration). */destination: BatchExportDestination;/** How often the batch export should run.@@ -15833,7 +15833,7 @@ export namespace Schemas {/** The 10 most recent runs of this batch export, ordered newest first. */readonly latest_runs: readonly BatchExportRun[];/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | null;@@ -16682,7 +16682,7 @@ export namespace Schemas {/** Whether the batch export is paused. */paused?: boolean;/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | null;@@ -76115,7 +76115,7 @@ export namespace Schemas {/** Whether the batch export is paused. */paused?: boolean;/**- * 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'.+ * 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. Required when model is 'hogql'.* @nullable*/hogql_query?: string | null;diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.tsindex 79c09f235f36..d0e74fbd1cd8 100644--- a/services/mcp/src/generated/batch_exports/api.ts+++ b/services/mcp/src/generated/batch_exports/api.ts@@ -459,7 +459,7 @@ export const BatchExportsCreateBody = () => 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([@@ -1173,7 +1173,7 @@ export const BatchExportsPartialUpdateBody = () => 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'."+ "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. Required when model is 'hogql'."),hogql_modifiers: zod.union([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.jsonindex 9e08527041ca..788284738869 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@@ -1125,7 +1125,7 @@"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'."+ "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. 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",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.jsonindex deca174e2521..a9d7cfd92061 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@@ -1124,7 +1124,7 @@"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'."+ "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. Required when model is 'hogql'."},"id": {"description": "A UUID string identifying this batch export.",