:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(batch-exports): Support interval placeholders for HogQL (#101766)
Tomás Farías Santana410b4bd708da
diff --git a/products/batch_exports/backend/api/file_download.py b/products/batch_exports/backend/api/file_download.pyindex 7c15b8cfc8d3..3547144d2e3e 100644--- a/products/batch_exports/backend/api/file_download.py+++ b/products/batch_exports/backend/api/file_download.py@@ -3,6 +3,7 @@ import timeimport uuidimport datetime as dtimport posixpath+from typing import Anyfrom django.conf import settingsfrom django.db import connection, models, transaction@@ -11,12 +12,11 @@ from django.shortcuts import get_object_or_404import boto3import structlog-import posthoganalyticsfrom botocore.client import Configfrom botocore.exceptions import ClientErrorfrom drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schemafrom rest_framework import mixins, response, serializers, status, viewsets-from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationError+from rest_framework.exceptions import APIException, NotFound, ValidationErrorfrom rest_framework.throttling import BaseThrottlefrom posthog.hogql.errors import ExposedHogQLError@@ -32,8 +32,11 @@ from posthog.models import Teamfrom posthog.rate_limit import BatchExportsCountRowsBurstRateThrottle, BatchExportsCountRowsSustainedRateThrottlefrom posthog.temporal.common.client import sync_connect+from products.batch_exports.backend.api.utils import check_hogql_batch_exports_enabledfrom products.batch_exports.backend.hogql_source import (UnsupportedHogQLQueryError,+ find_interval_placeholders,+ parse_hogql_select_for_batch_export,validate_hogql_query_for_batch_export,)from products.batch_exports.backend.models.batch_export import (@@ -124,20 +127,79 @@ class FileDownloadSessionsRequestSerializer(serializers.Serializer):HOGQL_QUERY_HELP_TEXT = ("HogQL SELECT query whose results are exported. This model is in closed beta and is enabled ""per team; when it is not enabled, the request fails with a permission error that names HogQL "- "batch exports. Contact PostHog support to request access. Placeholders are not currently "- "supported, and every column in the SELECT clause must be a field or have an alias. It is "- "recommended to limit the query with a WHERE clause, for example bounding timestamp on the "- "events table, both to avoid exporting more rows than expected and because user queries run "- "under stricter resource limits than the other models."+ "batch exports. Contact PostHog support to request access. The query may reference the "+ "{data_interval_start} and {data_interval_end} placeholders. Provide a value for each "+ "placeholder the query references; missing referenced bounds are rejected, not inferred. "+ "When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. "+ "Without placeholders, the query runs unchanged, even if bounds are supplied. Every column "+ "in the SELECT clause must be a field or have an alias. It is recommended to limit the query "+ "with a WHERE clause, for example bounding timestamp on the events table, both to avoid "+ "exporting more rows than expected and because user queries run under stricter resource "+ "limits than the other models.")+DATA_INTERVAL_START_HELP_TEXT = (+ "Start of the export interval. Required for the events, persons, and sessions models. "+ "For HogQL, required only when the query references {data_interval_start}. "+ "A supplied start must not be in the future. "+ "When both bounds are supplied, the interval must span at most seven days."+)+DATA_INTERVAL_END_HELP_TEXT = (+ "End of the export interval. Required for the events, persons, and sessions models. "+ "For HogQL, required only when the query references {data_interval_end}. "+ "A supplied end must not be in the future or precede a supplied start. "+ "Bounds replace HogQL placeholders; they do not add filters to the query."+)+++def validate_file_download_interval(+ data_interval_start: dt.datetime | None,+ data_interval_end: dt.datetime | None,+ *,+ hogql_query: str | None = None,+) -> None:+ if hogql_query is not None:+ try:+ placeholders = find_interval_placeholders(parse_hogql_select_for_batch_export(hogql_query))+ except UnsupportedHogQLQueryError as e:+ raise ValidationError({"hogql_query": str(e)}) from e+ bounds = {"data_interval_start": data_interval_start, "data_interval_end": data_interval_end}+ missing = {+ name: f"'{name}' is required because the query references '{{{name}}}'."+ for name in sorted(placeholders)+ if bounds[name] is None+ }+ if missing:+ raise ValidationError(missing)+ elif data_interval_start is None or data_interval_end is None:+ raise ValidationError("'data_interval_start' and 'data_interval_end' are required. Provide both bounds.")+ if data_interval_start is not None and data_interval_end is not None:+ if data_interval_start > data_interval_end:+ raise ValidationError("'data_interval_end' must occur after 'data_interval_start'")+ if data_interval_end - data_interval_start > FILE_DOWNLOAD_MAX_RANGE:+ raise ValidationError("data interval range too big. Choose an interval of at most seven days.")+ now = dt.datetime.now(dt.UTC)+ if data_interval_start is not None and data_interval_start > now:+ raise ValidationError(+ f"The provided 'data_interval_start' ({data_interval_start.isoformat()}) is in the future"+ )+ if data_interval_end is not None and data_interval_end > now:+ raise ValidationError(f"The provided 'data_interval_end' ({data_interval_end.isoformat()}) is in the future")++class FileDownloadHogQLRequestSerializer(serializers.Serializer):"""Typed configuration for the hogql model."""file = FileDownloadDestinationFileConfigSerializer()model = serializers.ChoiceField(choices=FileDownloadHogQLModel.choices)hogql_query = serializers.CharField(help_text=HOGQL_QUERY_HELP_TEXT)+ data_interval_start = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_START_HELP_TEXT+ )+ data_interval_end = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_END_HELP_TEXT+ )class FileDownloadCountRowsRequestSerializer(serializers.Serializer):@@ -148,6 +210,18 @@ class FileDownloadCountRowsRequestSerializer(serializers.Serializer):help_text="Model to count rows for. Only 'hogql' is supported.",)hogql_query = serializers.CharField(help_text=HOGQL_QUERY_HELP_TEXT)+ data_interval_start = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_START_HELP_TEXT+ )+ data_interval_end = serializers.DateTimeField(+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_END_HELP_TEXT+ )++ def validate(self, data: dict[str, Any]) -> dict[str, Any]:+ validate_file_download_interval(+ data.get("data_interval_start"), data.get("data_interval_end"), hogql_query=data["hogql_query"]+ )+ return dataclass FileDownloadCountRowsResponseSerializer(serializers.Serializer):@@ -155,28 +229,11 @@ class FileDownloadCountRowsResponseSerializer(serializers.Serializer):count = serializers.IntegerField(min_value=0,- help_text="Number of rows the query returns now. A HogQL batch export runs its query as of "- "the time the export starts, so a run started now would export this many rows.",+ help_text="Number of rows the query returns with the supplied interval bounds. "+ "Data arriving between counting and exporting can change the result.",)-def check_hogql_batch_exports_enabled(team: Team) -> None:- """Raise if HogQL-powered batch exports are not enabled for the team."""- if not posthoganalytics.feature_enabled(- "hogql-batch-exports",- str(team.uuid),- groups={"organization": str(team.organization.id)},- group_properties={- "organization": {- "id": str(team.organization.id),- "created_at": team.organization.created_at,- }- },- send_feature_flag_events=False,- ):- raise PermissionDenied("HogQL batch exports are not enabled for this team.")--COUNT_ROWS_TIMEOUT_MESSAGE = ("Timeout exceeded while counting rows. The query may be too complex, or the count may be too ""large to finish within a short time. Running this query in an export may take too long to "@@ -186,7 +243,14 @@ COUNT_ROWS_TIMEOUT_MESSAGE = ()-def count_rows_for_hogql_batch_export(team: Team, hogql_query: str, timeout: int = 30) -> int:+def count_rows_for_hogql_batch_export(+ team: Team,+ hogql_query: str,+ timeout: int = 30,+ *,+ data_interval_start: dt.datetime | None = None,+ data_interval_end: dt.datetime | None = None,+) -> int:"""Count the rows a HogQL query would produce.Raises:@@ -198,15 +262,11 @@ def count_rows_for_hogql_batch_export(team: Team, hogql_query: str, timeout: intquery_settings = get_user_hogql_batch_export_query_settings()query_settings.max_execution_time = timeout- # HogQL exports have no data interval: `create` runs them with a now/now interval.- # TODO: We should support these interval or just make it not required.- now = dt.datetime.now(dt.UTC)-# `execute_hogql_query` resolves modifiers differently than the batch# export, which could potentially affect counts.# TODO: How big is the difference? Is it worth aligning these two?query_response = execute_hogql_query(- query=record_batch_model.get_count_hogql_query(now, now),+ query=record_batch_model.get_count_hogql_query(data_interval_start, data_interval_end),team=team,query_type="HogQLBatchExportCountRowsQuery",settings=query_settings,@@ -227,12 +287,11 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):# Only specific to hogqlhogql_query = serializers.CharField(required=False, help_text=HOGQL_QUERY_HELP_TEXT)- # Run attributes; required for all models except hogql, which runs as of nowdata_interval_start = serializers.DateTimeField(- default_timezone=dt.UTC, required=False, help_text="Start of the data interval to export"+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_START_HELP_TEXT)data_interval_end = serializers.DateTimeField(- default_timezone=dt.UTC, required=False, help_text="End of the data interval to export"+ default_timezone=dt.UTC, required=False, help_text=DATA_INTERVAL_END_HELP_TEXT)def validate(self, data):@@ -242,19 +301,7 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):if data.get("hogql_query") is not None:raise ValidationError("'hogql_query' is only supported when 'model' is 'hogql'")- if data.get("data_interval_start") is None or data.get("data_interval_end") is None:- raise ValidationError(f"'data_interval_start' and 'data_interval_end' are required for '{data['model']}'")-- if data["data_interval_start"] > data["data_interval_end"]:- raise ValidationError("'data_interval_end' must occur after 'data_interval_start'")-- if data["data_interval_end"] - data["data_interval_start"] > FILE_DOWNLOAD_MAX_RANGE:- raise ValidationError("data interval range too big")-- if data["data_interval_end"] > dt.datetime.now(dt.UTC):- raise ValidationError(- f"The provided 'data_interval_end' ({data['data_interval_end'].isoformat()}) is in the future"- )+ validate_file_download_interval(data.get("data_interval_start"), data.get("data_interval_end"))return data@@ -262,14 +309,6 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):team = self.context["get_team"]()check_hogql_batch_exports_enabled(team)- # not sure if we need to be this strict but probably best to be explicit- # TODO: can remove this once we do support data_interval_start/end- if data.get("data_interval_start") is not None or data.get("data_interval_end") is not None:- raise ValidationError(- "'data_interval_start' and 'data_interval_end' are not supported when 'model' is 'hogql': "- "the query runs as of the time the export starts"- )-if data.get("include") is not None or data.get("exclude") is not None:raise ValidationError("'include' and 'exclude' are not supported when 'model' is 'hogql'")@@ -277,8 +316,12 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):if not hogql_query:raise ValidationError("'hogql_query' is required when 'model' is 'hogql'")+ validate_file_download_interval(+ data.get("data_interval_start"), data.get("data_interval_end"), hogql_query=hogql_query+ )+try:- validate_hogql_query_for_batch_export(hogql_query, team)+ validate_hogql_query_for_batch_export(hogql_query, team, user=self.context["request"].user)except UnsupportedHogQLQueryError as e:raise ValidationError({"hogql_query": str(e)}) from e@@ -296,11 +339,8 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):source = Noneif model == "hogql":source = BatchExportSource(team_id=team_id, hogql_query=validated_data.pop("hogql_query"))- # For now, HogQL exports have no data interval: the query runs as of now.- # We set a concrete now/now interval to keep everything downstream (eg workflow ID,- # staging paths) working unchanged. We should perhaps make the data interval optional in- # future.- data_interval_start = data_interval_end = dt.datetime.now(dt.UTC)+ data_interval_start = validated_data.pop("data_interval_start", None)+ data_interval_end = validated_data.pop("data_interval_end", None)else:data_interval_start = validated_data.pop("data_interval_start")data_interval_end = validated_data.pop("data_interval_end")@@ -667,7 +707,12 @@ class FileDownloadBatchExportOnDemandViewSet(check_hogql_batch_exports_enabled(self.team)try:- count = count_rows_for_hogql_batch_export(self.team, request.validated_data["hogql_query"])+ count = count_rows_for_hogql_batch_export(+ self.team,+ request.validated_data["hogql_query"],+ data_interval_start=request.validated_data.get("data_interval_start"),+ data_interval_end=request.validated_data.get("data_interval_end"),+ )except UnsupportedHogQLQueryError as e:raise ValidationError({"hogql_query": str(e)}) from eexcept (ExposedHogQLError, ExposedCHQueryError) as e:diff --git a/products/batch_exports/backend/api/utils.py b/products/batch_exports/backend/api/utils.pynew file mode 100644index 000000000000..11efd1177e9b--- /dev/null+++ b/products/batch_exports/backend/api/utils.py@@ -0,0 +1,21 @@+import posthoganalytics+from rest_framework.exceptions import PermissionDenied++from posthog.models import Team+++def check_hogql_batch_exports_enabled(team: Team) -> None:+ """Raise if HogQL-powered batch exports are not enabled for the team."""+ if not posthoganalytics.feature_enabled(+ "hogql-batch-exports",+ str(team.uuid),+ groups={"organization": str(team.organization.id)},+ group_properties={+ "organization": {+ "id": str(team.organization.id),+ "created_at": team.organization.created_at,+ }+ },+ send_feature_flag_events=False,+ ):+ raise PermissionDenied("HogQL batch exports are not enabled for this team.")diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.pyindex 2801ab8924ca..f165ea4bb3ba 100644--- a/products/batch_exports/backend/hogql_source.py+++ b/products/batch_exports/backend/hogql_source.py@@ -5,6 +5,7 @@ should not import from `products.batch_exports.backend.temporal` or any DRF code"""import typing+import datetime as dtfrom posthog.hogql import astfrom posthog.hogql.context import HogQLContext@@ -13,17 +14,27 @@ from posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.escape_sql import escape_clickhouse_identifierfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_select-from posthog.hogql.placeholders import find_placeholders+from posthog.hogql.placeholders import find_placeholders, replace_placeholdersfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.hogql.visitor import CloningVisitorfrom posthog.clickhouse.events_json import UNPARSEABLE_PROPERTIES_KEYif typing.TYPE_CHECKING:- from posthog.models import Team+ from posthog.models import Team, Userfrom products.batch_exports.backend.service import BatchExportField, BatchExportSchema+DATA_INTERVAL_START_PLACEHOLDER = "data_interval_start"+DATA_INTERVAL_END_PLACEHOLDER = "data_interval_end"++# When validating a query, we need to fill-in some values. Any values would+# work, these are just arbitrary.+_VALIDATION_DATA_INTERVAL_START = dt.datetime(2000, 1, 1, tzinfo=dt.UTC)+_VALIDATION_DATA_INTERVAL_END = dt.datetime(2000, 1, 2, tzinfo=dt.UTC)++_SUPPORTED_PLACEHOLDERS = f"{{{DATA_INTERVAL_START_PLACEHOLDER}}} and {{{DATA_INTERVAL_END_PLACEHOLDER}}}"+class UnsupportedHogQLQueryError(Exception):"""Raised when a HogQL query cannot be used to power a batch export."""@@ -32,11 +43,12 @@ class UnsupportedHogQLQueryError(Exception):def parse_hogql_select_for_batch_export(hogql_query: str) -> ast.SelectQuery | ast.SelectSetQuery:"""Parse a HogQL SELECT query intended to power a batch export.- Placeholders are not currently supported in batch exports, they will be coming soon...+ Only the `{data_interval_start}` and `{data_interval_end}` placeholders are supported, as+ those are the ones a run can resolve with its data interval bounds.Raises:- UnsupportedHogQLQueryError: If the query cannot be parsed as a SELECT or- contains placeholders, which batch exports have no way to resolve.+ UnsupportedHogQLQueryError: If the query cannot be parsed as a SELECT or contains+ placeholders other than the two interval ones.InternalHogQLError: Left to propagate. An internal HogQL engine error is ourbug, not a problem with the user's query, so it should surface as an error(and get alerted on) rather than be reported back as an unsupported query.@@ -46,15 +58,66 @@ def parse_hogql_select_for_batch_export(hogql_query: str) -> ast.SelectQuery | aexcept ExposedHogQLError as e:raise UnsupportedHogQLQueryError(f"Failed to parse HogQL query: {e}") from e- # TODO: support placeholder expressions in batch exportsplaceholders = find_placeholders(parsed)- if placeholders.has_filters or placeholders.placeholder_fields or placeholders.placeholder_expressions:- raise UnsupportedHogQLQueryError("Placeholders are not supported in batch export queries")+ if placeholders.has_filters or placeholders.placeholder_expressions:+ raise UnsupportedHogQLQueryError(+ f"Unsupported placeholder. Only {_SUPPORTED_PLACEHOLDERS} are supported in batch export queries"+ )+ for chain in placeholders.placeholder_fields:+ if chain not in ([DATA_INTERVAL_START_PLACEHOLDER], [DATA_INTERVAL_END_PLACEHOLDER]):+ name = ".".join(str(part) for part in chain)+ raise UnsupportedHogQLQueryError(+ f"Unknown placeholder '{{{name}}}'. "+ f"Only {_SUPPORTED_PLACEHOLDERS} are supported in batch export queries"+ )return parsed-def create_hogql_context_for_batch_export(team: "Team", values: dict[str, typing.Any] | None = None) -> HogQLContext:+def find_interval_placeholders(parsed: ast.SelectQuery | ast.SelectSetQuery) -> set[str]:+ """Return the names of interval placeholders the query references."""+ chains = find_placeholders(parsed).placeholder_fields+ names: set[str] = set()+ if [DATA_INTERVAL_START_PLACEHOLDER] in chains:+ names.add(DATA_INTERVAL_START_PLACEHOLDER)+ if [DATA_INTERVAL_END_PLACEHOLDER] in chains:+ names.add(DATA_INTERVAL_END_PLACEHOLDER)+ return names+++def replace_interval_placeholders(+ parsed: ast.SelectQuery | ast.SelectSetQuery,+ data_interval_start: dt.datetime | None,+ data_interval_end: dt.datetime | None,+) -> ast.SelectQuery | ast.SelectSetQuery:+ """Return a copy of the query with the interval placeholders replaced by their values.++ A referenced bound must have a value, including for beginning-of-time backfills.+ The input query is not modified.+ """+ bounds = {+ DATA_INTERVAL_START_PLACEHOLDER: data_interval_start,+ DATA_INTERVAL_END_PLACEHOLDER: data_interval_end,+ }+ for name in sorted(find_interval_placeholders(parsed)):+ if bounds[name] is None:+ raise UnsupportedHogQLQueryError(+ f"The query references '{{{name}}}', but '{name}' is not defined. "+ "Provide the bound or remove the placeholder from the query."+ )++ return typing.cast(+ ast.SelectQuery | ast.SelectSetQuery,+ replace_placeholders(+ parsed,+ {name: ast.Constant(value=value) for name, value in bounds.items() if value is not None},+ ),+ )+++def create_hogql_context_for_batch_export(+ team: "Team", values: dict[str, typing.Any] | None = None, user: "User | None" = None+) -> HogQLContext:"""Build the HogQLContext batch exports use to resolve and print a query.Both API-side validation and worker-side execution must build the context the same@@ -68,6 +131,7 @@ def create_hogql_context_for_batch_export(team: "Team", values: dict[str, typingcontext = HogQLContext(team=team,team_id=team.id,+ user=user,enable_select_queries=True,limit_top_select=False,values=values if values is not None else {},@@ -97,12 +161,15 @@ def _validate_select_columns_are_named(parsed: ast.SelectQuery | ast.SelectSetQu)-def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team") -> None:+def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", user: "User | None" = None) -> None:"""Validate a HogQL query can power a batch export for the given team.Parses the query, checks output columns are named, and resolves types against theteam's database (catching unknown tables/fields) with the same context the worker- will execute with.+ will execute with. Resolution runs on the query with any interval placeholders+ substituted, exactly as a run does, so misuse that breaks resolution is caught+ here instead of failing every run. A query without placeholders is equally valid:+ it runs as-is, so every run exports all rows the query returns at run time.Raises:UnsupportedHogQLQueryError: If the query cannot power a batch export.@@ -111,7 +178,9 @@ def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team") -> Nonparsed = parse_hogql_select_for_batch_export(hogql_query)_validate_select_columns_are_named(parsed)- context = create_hogql_context_for_batch_export(team)+ parsed = replace_interval_placeholders(parsed, _VALIDATION_DATA_INTERVAL_START, _VALIDATION_DATA_INTERVAL_END)++ context = create_hogql_context_for_batch_export(team, user=user)try:prepare_ast_for_printing(parsed, context=context, dialect="clickhouse", stack=[])except ExposedHogQLError as e:diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex 998d713fcb69..1f2f39ab57b2 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -22,9 +22,12 @@ from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_loggerfrom products.batch_exports.backend.hogql_source import (+ DATA_INTERVAL_END_PLACEHOLDER,UnsupportedHogQLQueryError,create_hogql_context_for_batch_export,+ find_interval_placeholders,parse_hogql_select_for_batch_export,+ replace_interval_placeholders,serialize_batch_export_query,)from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema@@ -362,26 +365,23 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):The query is stored as a raw HogQL string and transpiled to ClickHouse SQL at runtime, so it stays resilient to printer changes.- TODO: Data interval bounds are accepted to satisfy the base class contract but ignored: the- query has no interval semantics yet.+ Referenced interval placeholders use the supplied run bounds. Queries without+ placeholders run unchanged."""- # The query is executed as-is with no data interval, so there is nothing to wait for.- wait_for_data_interval_end = False-def __init__(self, team_id: int, hogql_query: str, batch_export_id: str | None = None):super().__init__(team_id=team_id, batch_export_id=batch_export_id)self.hogql_query = hogql_query+ self.parsed_hogql_query = parse_hogql_select_for_batch_export(hogql_query)+ self.wait_for_data_interval_end = DATA_INTERVAL_END_PLACEHOLDER in find_interval_placeholders(+ self.parsed_hogql_query+ )def get_hogql_query(self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> ast.SelectQuery | ast.SelectSetQuery:- """Return the parsed HogQL query used for this model.-- The data interval bounds are ignored: the query is exported as-is (see the class- docstring). They are accepted to satisfy the base class contract.- """- return parse_hogql_select_for_batch_export(self.hogql_query)+ """Return the query with referenced placeholders replaced by the run's bounds."""+ return replace_interval_placeholders(self.parsed_hogql_query, data_interval_start, data_interval_end)def get_count_hogql_query(self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | Nonediff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.pyindex c17962fa2b88..8580dba3dfd7 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py@@ -622,7 +622,7 @@ async def test_file_download_cancel_mocked(class TestFileDownloadHogQL:"""File download batch exports created from a user-defined HogQL query."""- HOGQL_FLAG_PATCH_TARGET = "products.batch_exports.backend.api.file_download.posthoganalytics.feature_enabled"+ HOGQL_FLAG_PATCH_TARGET = "products.batch_exports.backend.api.utils.posthoganalytics.feature_enabled"@pytest.fixturedef enable_hogql_flag(self):@@ -632,13 +632,8 @@ class TestFileDownloadHogQL:@pytest.fixtureasync def hogql_export_test_events(self, clickhouse_client, team, truncate_clickhouse_tables):- """Insert events for this and another team directly into the events table.-- A hogql export reads the main (sharded) events table with no interval filter, so- the test controls exactly which rows exist there: no duplicates, plus another- team's rows to verify only this team's data is exported.- """- timestamp = dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)+ interval_start = dt.datetime.now(dt.UTC) - dt.timedelta(hours=2)+ timestamp = interval_start + dt.timedelta(minutes=30)events = generate_test_events(count=10,team_id=team.pk,@@ -646,6 +641,9 @@ class TestFileDownloadHogQL:event_name="test-{i}",properties={"$browser": "Chrome"},)+ events[0]["timestamp"] = (interval_start - dt.timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S.%f")+ events[1]["timestamp"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")+ events[-1]["timestamp"] = (interval_start + dt.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S.%f")events_from_other_team = generate_test_events(count=3,team_id=team.pk + random.randint(1, 1000),@@ -698,7 +696,7 @@ class TestFileDownloadHogQL:),pytest.param({"hogql_query": "SELECT event AS event FROM events WHERE {filters}"},- "Placeholders are not supported",+ "Unsupported placeholder",id="placeholder-query",),pytest.param(@@ -712,9 +710,18 @@ class TestFileDownloadHogQL:id="unknown-table",),pytest.param(- {"data_interval_start": "2026-01-01T00:00:00+00:00", "data_interval_end": "2026-01-02T00:00:00+00:00"},- "not supported when 'model' is 'hogql'",- id="intervals-with-hogql",+ {"hogql_query": "SELECT event FROM events WHERE timestamp < {data_interval_end}"},+ "'data_interval_end' is required",+ id="missing-placeholder-bounds",+ ),+ pytest.param(+ {+ "hogql_query": "SELECT event FROM events WHERE timestamp >= {data_interval_start} "+ "AND timestamp < {data_interval_end}",+ "data_interval_start": "2026-01-01T00:00:00+00:00",+ },+ "'data_interval_end' is required",+ id="incomplete-placeholder-bounds",),pytest.param({"include": ["my-event"]},@@ -775,28 +782,42 @@ class TestFileDownloadHogQL:)assert await sync_to_async(lambda: BatchExportSource.objects.for_team(team.pk).count())() == 0+ @pytest.mark.parametrize(+ "query_filter,bounds",+ [+ ("", {}),+ (+ "",+ {"data_interval_start": "2026-01-01T00:00:00+00:00", "data_interval_end": "2026-01-08T00:00:00+00:00"},+ ),+ (+ " WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}",+ {"data_interval_start": "2026-01-01T00:00:00+00:00", "data_interval_end": "2026-01-08T00:00:00+00:00"},+ ),+ (" WHERE timestamp >= {data_interval_start}", {"data_interval_start": "2025-01-01T00:00:00+00:00"}),+ (" WHERE timestamp < {data_interval_end}", {"data_interval_end": "2025-01-01T00:00:00+00:00"}),+ ],+ ids=["unbounded", "bounds-without-placeholders", "bounded", "start-only", "end-only"],+ )@pytest.mark.usefixtures("enable_hogql_flag")@pytest.mark.django_db(transaction=True)- async def test_create(self, async_client: AsyncClient, team, user, mock_start_file_download_export):- """A hogql create request stores the query on a source and threads it to the workflow.-- The run's data interval is faked as now/now: hogql exports have no interval, but- everything downstream formats concrete bounds.- """+ @time_machine.travel("2026-01-08T00:00:00Z", tick=False)+ async def test_create(+ self, async_client: AsyncClient, team, user, mock_start_file_download_export, query_filter, bounds+ ):await async_client.aforce_login(user)- hogql_query = "SELECT event AS event, distinct_id AS distinct_id FROM events"+ hogql_query = "SELECT event AS event, distinct_id AS distinct_id FROM events" + query_filter- before = dt.datetime.now(dt.UTC)response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports",{"file": {"format": "Parquet"},"model": "hogql","hogql_query": hogql_query,+ **bounds,},content_type="application/json",)- after = dt.datetime.now(dt.UTC)assert response.status_code == status.HTTP_202_ACCEPTED, response.json()@@ -805,9 +826,9 @@ class TestFileDownloadHogQL:"batch_export_on_demand__source", "batch_export_on_demand__destination").aget(id=response.json()["id"])- assert run.data_interval_start == run.data_interval_end- assert run.data_interval_end is not None- assert before <= run.data_interval_end <= after+ for name in ("data_interval_start", "data_interval_end"):+ value = bounds.get(name)+ assert getattr(run, name) == (dt.datetime.fromisoformat(value) if value is not None else None)on_demand = run.batch_export_on_demandassert on_demand is not Noneassert on_demand.model == "hogql"@@ -821,18 +842,44 @@ class TestFileDownloadHogQL:assert batch_export_model.name == "hogql"assert batch_export_model.hogql_query == hogql_queryassert mock_start_file_download_export.call_args.kwargs["max_size_mb"] == DEFAULT_MAX_SIZE_MB+ assert mock_start_file_download_export.call_args.kwargs["data_interval_start"] == run.data_interval_start+ assert mock_start_file_download_export.call_args.kwargs["data_interval_end"] == run.data_interval_end@requires_aws_credentials+ @pytest.mark.parametrize(+ "bound_mode", [None, "both", "start", "end"], ids=["unbounded", "bounded", "start-only", "end-only"]+ )@pytest.mark.usefixtures("override_file_download_settings", "enable_hogql_flag")@pytest.mark.django_db(transaction=True)- async def test_end_to_end(self, async_client: AsyncClient, temporal_client, team, user, hogql_export_test_events):- """A hogql export produces a downloadable file whose contents match the query results."""+ async def test_end_to_end(+ self, async_client: AsyncClient, temporal_client, team, user, hogql_export_test_events, bound_mode+ ):await async_client.aforce_login(user)hogql_query = """SELECT event AS event, distinct_id AS distinct_id, properties.$browser AS browserFROM events"""+ bounds = {}+ predicates = []+ expected_events = hogql_export_test_events+ if bound_mode in ("start", "both"):+ predicates.append("timestamp >= {data_interval_start}")+ bounds["data_interval_start"] = hogql_export_test_events[1]["timestamp"] + "+00:00"+ expected_events = expected_events[1:]+ if bound_mode in ("end", "both"):+ predicates.append("timestamp < {data_interval_end}")+ bounds["data_interval_end"] = hogql_export_test_events[-1]["timestamp"] + "+00:00"+ expected_events = expected_events[:-1]+ if predicates:+ hogql_query += " WHERE " + " AND ".join(predicates)+ count_response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",+ {"model": "hogql", "hogql_query": hogql_query, **bounds},+ content_type="application/json",+ )+ assert count_response.status_code == status.HTTP_200_OK, count_response.json()+ assert count_response.json() == {"count": len(expected_events)}async with Worker(temporal_client,@@ -847,6 +894,7 @@ class TestFileDownloadHogQL:"file": {"format": "Parquet", "compression": "zstd"},"model": "hogql","hogql_query": hogql_query,+ **bounds,},content_type="application/json",)@@ -898,42 +946,80 @@ class TestFileDownloadHogQL:assert set(table.column_names) == {"event", "distinct_id", "browser"}exported_rows = sorted((row["event"], row["distinct_id"], row["browser"]) for row in table.to_pylist())- expected_rows = sorted((e["event"], e["distinct_id"], "Chrome") for e in hogql_export_test_events)+ expected_rows = sorted((e["event"], e["distinct_id"], "Chrome") for e in expected_events)assert exported_rows == expected_rows+ assert len(exported_rows) == count_response.json()["count"]@pytest.mark.parametrize(- "hogql_query,expected_count",+ "hogql_query,expected_count,bound_mode",[pytest.param("SELECT event AS event, distinct_id AS distinct_id FROM events",10,+ None,id="plain-select-scoped-to-team",),pytest.param("SELECT count() AS event_count FROM events",1,+ None,id="aggregate-counts-result-rows-not-scanned-rows",),pytest.param("SELECT event AS event FROM events UNION ALL SELECT event AS event FROM events",20,+ None,id="union-all",),pytest.param("SELECT event AS event FROM events LIMIT 4",4,+ None,id="user-limit-caps-the-count",),+ pytest.param(+ "SELECT event AS event, distinct_id AS distinct_id FROM events "+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}",+ 8,+ "both",+ id="explicit-interval-excludes-outside-rows",+ ),+ pytest.param(+ "SELECT event FROM events "+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end} LIMIT 4",+ 4,+ "both",+ id="bounded-query-limit-caps-the-count",+ ),+ pytest.param(+ "SELECT event FROM events WHERE timestamp >= {data_interval_start}",+ 9,+ "start",+ id="start-only",+ ),+ pytest.param(+ "SELECT event FROM events WHERE timestamp < {data_interval_end}",+ 9,+ "end",+ id="end-only",+ ),],)@pytest.mark.usefixtures("enable_hogql_flag", "hogql_export_test_events")@pytest.mark.django_db(transaction=True)- async def test_count_rows(self, async_client: AsyncClient, team, user, hogql_query, expected_count):+ async def test_count_rows(+ self, async_client: AsyncClient, team, user, hogql_query, expected_count, bound_mode, hogql_export_test_events+ ):await async_client.aforce_login(user)+ bounds = {}+ if bound_mode in ("start", "both"):+ bounds["data_interval_start"] = hogql_export_test_events[1]["timestamp"] + "+00:00"+ if bound_mode in ("end", "both"):+ bounds["data_interval_end"] = hogql_export_test_events[-1]["timestamp"] + "+00:00"response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",- {"model": "hogql", "hogql_query": hogql_query},+ {"model": "hogql", "hogql_query": hogql_query, **bounds},content_type="application/json",)@@ -960,7 +1046,7 @@ class TestFileDownloadHogQL:),pytest.param({"model": "hogql", "hogql_query": "SELECT event AS event FROM events WHERE {filters}"},- "Placeholders are not supported",+ "Unsupported placeholder",id="placeholder-query",),pytest.param(@@ -973,6 +1059,11 @@ class TestFileDownloadHogQL:"no_such_table",id="unknown-table",),+ pytest.param(+ {"model": "hogql", "hogql_query": "SELECT event FROM events WHERE timestamp < {data_interval_end}"},+ "'data_interval_end' is required",+ id="missing-placeholder-bounds",+ ),],)@pytest.mark.usefixtures("enable_hogql_flag")@@ -982,14 +1073,16 @@ class TestFileDownloadHogQL:):await async_client.aforce_login(user)- response = await async_client.post(- f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",- body,- content_type="application/json",- )+ with unittest.mock.patch("products.batch_exports.backend.api.file_download.execute_hogql_query") as execute:+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",+ body,+ content_type="application/json",+ )assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()assert expected_error_fragment in response.content.decode()+ execute.assert_not_called()assert await sync_to_async(lambda: BatchExportSource.objects.for_team(team.pk).count())() == 0@pytest.mark.django_db(transaction=True)diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.pyindex adcffb72dd68..f060c4405a2b 100644--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py@@ -347,6 +347,57 @@ class TestHogQLQueryRecordBatchModel:assert f"equals(events.team_id, {ateam.id})" in printed_queryassert "FORMAT ArrowStream" in printed_queryassert "log_comment" in query_parameters+ # without interval placeholders the query runs as-is, as of now+ assert f"toDateTime64('{data_interval_end:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')" not in printed_query+ assert model.wait_for_data_interval_end is False++ async def test_as_query_with_parameters_applies_data_interval(self, ateam, data_interval_start, data_interval_end):+ model = HogQLQueryRecordBatchModel(+ team_id=ateam.id,+ hogql_query=(+ "SELECT event AS event, timestamp AS timestamp FROM events "+ "WHERE event = 'test' AND timestamp >= {data_interval_start} "+ "AND timestamp < {data_interval_end}"+ ),+ )+ printed_query, _ = await model.as_query_with_parameters(data_interval_start, data_interval_end)++ upper_bound = f"toDateTime64('{data_interval_end:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')"+ lower_bound = f"toDateTime64('{data_interval_start:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')"+ assert f"less(timestamp, {upper_bound})" in printed_query+ assert f"greaterOrEquals(timestamp, {lower_bound})" in printed_query+ # the user's own filters are kept+ assert "equals(event, %(hogql_val_" in printed_query+ assert model.wait_for_data_interval_end is True++ async def test_as_query_with_parameters_selects_only_rows_in_data_interval(self, clickhouse_client, ateam):+ await truncate_events(clickhouse_client)+ data_interval_start = dt.datetime(2021, 1, 15, 10, 0, 0, tzinfo=dt.UTC)+ data_interval_end = dt.datetime(2021, 1, 15, 11, 0, 0, tzinfo=dt.UTC)+ events_in_range, _, _ = await generate_test_events_in_clickhouse(+ client=clickhouse_client,+ team_id=ateam.pk,+ start_time=data_interval_start,+ end_time=data_interval_end,+ count=10,+ count_outside_range=5,+ count_other_team=0,+ table="sharded_events",+ )+ model = HogQLQueryRecordBatchModel(+ team_id=ateam.pk,+ hogql_query=(+ "SELECT uuid AS uuid, timestamp AS timestamp FROM events "+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"+ ),+ )++ printed_query, parameters = await model._print_query(+ data_interval_start, data_interval_end, output_format="JSONEachRow"+ )+ rows = await clickhouse_client.read_query_as_jsonl(printed_query, query_parameters=parameters)++ assert {row["uuid"] for row in rows} == {event["uuid"] for event in events_in_range}async def test_as_insert_into_s3_query_with_parameters(self, ateam, data_interval_start, data_interval_end):model = HogQLQueryRecordBatchModel(@@ -404,21 +455,27 @@ class TestHogQLQueryRecordBatchModel:@pytest.mark.parametrize("hogql_query,expected_message",[- ("SELECT event AS event FROM events WHERE {filters}", "Placeholders are not supported"),- ("SELECT event AS event FROM events WHERE event = {placeholder_field}", "Placeholders are not supported"),- ("SELECT event AS event FROM events WHERE event = {concat('a', 'b')}", "Placeholders are not supported"),+ (+ "SELECT event AS event FROM events WHERE {filters}",+ "Unsupported placeholder. Only {data_interval_start} and {data_interval_end} are supported",+ ),+ (+ "SELECT event AS event FROM events WHERE event = {placeholder_field}",+ "Unknown placeholder '{placeholder_field}'",+ ),+ (+ "SELECT event AS event FROM events WHERE event = {concat('a', 'b')}",+ "Unsupported placeholder. Only {data_interval_start} and {data_interval_end} are supported",+ ),("not a valid query", "Failed to parse HogQL query"),("DROP TABLE events", "Failed to parse HogQL query"),],ids=["filters", "placeholder-field", "placeholder-expression", "invalid-syntax", "not-a-select"],)- async def test_get_hogql_query_raises_on_unsupported_query(- self, hogql_query, expected_message, data_interval_start, data_interval_end- ):- model = HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)-+ async def test_construction_raises_on_unsupported_query(self, hogql_query, expected_message):+ # The query is parsed at construction, so an unsupported one fails before any run does.with pytest.raises(UnsupportedHogQLQueryError, match=expected_message):- model.get_hogql_query(data_interval_start, data_interval_end)+ HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)@pytest.mark.parametrize("hogql_query",@@ -429,7 +486,7 @@ class TestHogQLQueryRecordBatchModel:],ids=["top-level", "after-union", "in-cte"],)- async def test_get_hogql_query_rejects_a_settings_clause(self, hogql_query, data_interval_start, data_interval_end):+ async def test_construction_rejects_a_settings_clause(self, hogql_query):"""A user query carrying its own SETTINGS is rejected, wherever that clause appears.The per-query resource limits are sent as request settings, and a query-level SETTINGS clause@@ -437,14 +494,17 @@ class TestHogQLQueryRecordBatchModel:time and bytes-read caps. The parser refusing these is what the limits rest on, and nothingelse asserts it."""- model = HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)-with pytest.raises(UnsupportedHogQLQueryError, match="settingsClause"):- model.get_hogql_query(data_interval_start, data_interval_end)+ HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)async def test_resolve_batch_exports_model_returns_hogql_model(self):batch_export_model = BatchExportModel(- name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"+ name="hogql",+ schema=None,+ hogql_query=(+ "SELECT event AS event, timestamp AS timestamp FROM events "+ "WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}"+ ),)_, record_batch_model, model_name, _, _, _ = resolve_batch_exports_model(@@ -454,6 +514,7 @@ class TestHogQLQueryRecordBatchModel:assert isinstance(record_batch_model, HogQLQueryRecordBatchModel)assert model_name == "hogql"assert record_batch_model.hogql_query == batch_export_model.hogql_query+ assert record_batch_model.wait_for_data_interval_end is Trueasync def test_resolve_batch_exports_model_raises_without_hogql_query(self):"""Without this, a missing query would fall through to the events template path and export the wrong data."""diff --git a/products/batch_exports/backend/tests/test_file_download_interval.py b/products/batch_exports/backend/tests/test_file_download_interval.pynew file mode 100644index 000000000000..c43477761f6e--- /dev/null+++ b/products/batch_exports/backend/tests/test_file_download_interval.py@@ -0,0 +1,152 @@+import datetime as dt++import pytest+import time_machine++from products.batch_exports.backend.api.file_download import (+ FileDownloadBatchExportOnDemandSerializer,+ FileDownloadCountRowsRequestSerializer,+)+++ "hogql_query,required_bounds",+ [+ ("SELECT {data_interval_start} AS bound", {"data_interval_start"}),+ ("SELECT {data_interval_end} AS bound", {"data_interval_end"}),+ (+ "SELECT {data_interval_start} AS start, {data_interval_end} AS end",+ {"data_interval_start", "data_interval_end"},+ ),+ ("SELECT 1 AS value", set()),+ ],+ ids=["start-placeholder", "end-placeholder", "both-placeholders", "no-placeholders"],+)+ "bounds",+ [+ {},+ {"data_interval_start": "2026-01-01T00:00:00Z"},+ {"data_interval_end": "2026-01-02T00:00:00Z"},+ {"data_interval_start": "2026-01-01T00:00:00Z", "data_interval_end": "2026-01-02T00:00:00Z"},+ ],+ ids=["no-bounds", "only-start", "only-end", "both-bounds"],+)+@time_machine.travel("2026-01-08T00:00:00Z", tick=False)+def test_interval_placeholders_require_only_referenced_download_bounds(+ hogql_query: str, required_bounds: set[str], bounds: dict[str, str]+) -> None:+ serializer = FileDownloadCountRowsRequestSerializer(data={"model": "hogql", "hogql_query": hogql_query, **bounds})++ missing = required_bounds - bounds.keys()+ if missing:+ assert not serializer.is_valid()+ assert set(serializer.errors) == missing+ else:+ assert serializer.is_valid(), serializer.errors++[email protected]("with_placeholders", [False, True])+ "bounds,error",+ [+ ({"data_interval_start": None, "data_interval_end": "2026-01-02T00:00:00Z"}, "may not be null"),+ ({"data_interval_start": "2026-01-01T00:00:00Z", "data_interval_end": None}, "may not be null"),+ (+ {"data_interval_start": "2026-01-01T00:00:00Z", "data_interval_end": "2026-01-08T00:00:00Z"},+ None,+ ),+ (+ {"data_interval_start": "2026-01-01T01:00:00+01:00", "data_interval_end": "2026-01-08T00:00:00Z"},+ None,+ ),+ (+ {"data_interval_start": "2026-01-01T00:00:00Z", "data_interval_end": "2026-01-08T00:00:00.000001Z"},+ "at most seven days",+ ),+ (+ {"data_interval_start": "2026-01-02T00:00:00Z", "data_interval_end": "2026-01-01T00:00:00Z"},+ "must occur after",+ ),+ (+ {"data_interval_start": "2026-01-01T00:00:00Z", "data_interval_end": "2026-01-01T00:00:00Z"},+ None,+ ),+ (+ {"data_interval_start": "2026-01-08T00:00:00Z", "data_interval_end": "2026-01-09T00:00:00Z"},+ "in the future",+ ),+ ],+ ids=[+ "null-start",+ "null-end",+ "one-week",+ "timezone",+ "over-one-week",+ "reversed",+ "empty",+ "future",+ ],+)+@time_machine.travel("2026-01-08T00:00:00Z", tick=False)+def test_download_interval_validation(+ with_placeholders: bool, bounds: dict[str, str | None], error: str | None+) -> None:+ query = (+ "SELECT {data_interval_start} AS start, {data_interval_end} AS end"+ if with_placeholders+ else "SELECT 1 AS value"+ )+ serializer = FileDownloadCountRowsRequestSerializer(data={"model": "hogql", "hogql_query": query, **bounds})++ if error is not None:+ assert not serializer.is_valid()+ assert error in str(serializer.errors)+ else:+ assert serializer.is_valid(), serializer.errors+ for name, value in bounds.items():+ assert value is not None+ assert serializer.validated_data[name] == dt.datetime.fromisoformat(value)+++ "placeholder,value,error",+ [+ ("data_interval_start", "2025-01-01T00:00:00Z", None),+ ("data_interval_start", "2026-01-09T00:00:00Z", "in the future"),+ ("data_interval_end", "2025-01-01T00:00:00Z", None),+ ("data_interval_end", "2026-01-09T00:00:00Z", "in the future"),+ ],+ ids=["old-start", "future-start", "old-end", "future-end"],+)+@time_machine.travel("2026-01-08T00:00:00Z", tick=False)+def test_single_download_bound_validation(placeholder: str, value: str, error: str | None) -> None:+ serializer = FileDownloadCountRowsRequestSerializer(+ data={"model": "hogql", "hogql_query": f"SELECT {{{placeholder}}} AS bound", placeholder: value}+ )++ if error:+ assert not serializer.is_valid()+ assert error in str(serializer.errors)+ else:+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data[placeholder] == dt.datetime.fromisoformat(value)++[email protected]("model", ["events", "persons", "sessions"])[email protected]("bound", ["data_interval_start", "data_interval_end"])+def test_non_hogql_downloads_require_both_bounds(model: str, bound: str) -> None:+ serializer = FileDownloadBatchExportOnDemandSerializer(+ data={"model": model, "file": {"format": "Parquet"}, bound: "2026-01-01T00:00:00Z"}+ )++ assert not serializer.is_valid()+ assert "'data_interval_start' and 'data_interval_end' are required" in str(serializer.errors)+++def test_placeholder_like_text_does_not_require_download_bounds() -> None:+ serializer = FileDownloadCountRowsRequestSerializer(+ data={"model": "hogql", "hogql_query": "SELECT '{data_interval_start}' AS value /* {data_interval_end} */"}+ )++ assert serializer.is_valid(), serializer.errorsdiff --git a/products/batch_exports/backend/tests/test_hogql_interval_placeholders.py b/products/batch_exports/backend/tests/test_hogql_interval_placeholders.pynew file mode 100644index 000000000000..a0252e1fad14--- /dev/null+++ b/products/batch_exports/backend/tests/test_hogql_interval_placeholders.py@@ -0,0 +1,101 @@+import datetime as dt++import pytest+from unittest.mock import patch++from temporalio.testing import ActivityEnvironment++from posthog.hogql import ast++from products.batch_exports.backend.hogql_source import (+ UnsupportedHogQLQueryError,+ find_interval_placeholders,+ parse_hogql_select_for_batch_export,+ replace_interval_placeholders,+)+from products.batch_exports.backend.service import BatchExportModel+from products.batch_exports.backend.temporal.pipeline.internal_stage import (+ BatchExportInsertIntoInternalStageInputs,+ insert_into_internal_stage_activity,+)+from products.batch_exports.backend.tests.temporal.utils.mock_clickhouse import MockClickHouseClient++[email protected]("placeholder", ["data_interval_start", "data_interval_end"])+def test_referenced_bound_must_be_defined(placeholder: str) -> None:+ parsed = parse_hogql_select_for_batch_export(f"SELECT {{{placeholder}}} AS bound")+ supplied_bound = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)++ with pytest.raises(UnsupportedHogQLQueryError, match=f"'{placeholder}' is not defined"):+ replace_interval_placeholders(+ parsed,+ None if placeholder == "data_interval_start" else supplied_bound,+ None if placeholder == "data_interval_end" else supplied_bound,+ )++[email protected]("with_end_placeholder", [False, True])+def test_missing_unreferenced_bounds_are_allowed(with_end_placeholder: bool) -> None:+ query = "SELECT {data_interval_end} AS bound" if with_end_placeholder else "SELECT 1 AS bound"+ parsed = parse_hogql_select_for_batch_export(query)+ end = dt.datetime(2026, 1, 1, tzinfo=dt.UTC) if with_end_placeholder else None++ replaced = replace_interval_placeholders(parsed, None, end)++ assert isinstance(replaced, ast.SelectQuery)+ assert isinstance(replaced.select[0], ast.Alias)+ assert isinstance(replaced.select[0].expr, ast.Constant)+ assert replaced.select[0].expr.value == (end if with_end_placeholder else 1)+++def test_each_run_substitutes_its_own_bounds_without_mutating_the_query() -> None:+ parsed = parse_hogql_select_for_batch_export("SELECT {data_interval_start} AS start, {data_interval_end} AS end")+ first_start = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+ for day in range(2):+ start = first_start + dt.timedelta(days=day)+ end = start + dt.timedelta(days=1)+ replaced = replace_interval_placeholders(parsed, start, end)++ assert isinstance(replaced, ast.SelectQuery)+ assert [+ expr.expr.value+ for expr in replaced.select+ if isinstance(expr, ast.Alias) and isinstance(expr.expr, ast.Constant)+ ] == [start, end]+ assert find_interval_placeholders(parsed) == {"data_interval_start", "data_interval_end"}+++ "hogql_query,expected_error",+ [+ (+ "SELECT event FROM events WHERE timestamp >= {data_interval_start}",+ "'data_interval_start' is not defined",+ ),+ ("not a valid query", "Failed to parse HogQL query"),+ ("SELECT event FROM events WHERE timestamp >= {unknown}", "Unknown placeholder '{unknown}'"),+ (None, "no HogQL query was provided"),+ ],+ ids=["missing-start", "malformed-query", "unsupported-placeholder", "missing-query"],+)+async def test_invalid_hogql_returns_non_retryable_staging_error(hogql_query: str | None, expected_error: str) -> None:+ inputs = BatchExportInsertIntoInternalStageInputs(+ team_id=1,+ batch_export_id="00000000-0000-4000-8000-000000000001",+ data_interval_start=None,+ data_interval_end=(dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)).isoformat(),+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query),+ )+ clickhouse = MockClickHouseClient()++ with patch(+ "products.batch_exports.backend.temporal.pipeline.internal_stage.get_client",+ return_value=clickhouse.mock_client_cm,+ ):+ result = await ActivityEnvironment().run(insert_into_internal_stage_activity, inputs)++ assert result.error is not None+ assert result.error.type == "UnsupportedHogQLQueryError"+ assert expected_error in result.error.message+ assert result.records_total is None+ clickhouse.expect_query_count(0)diff --git a/products/batch_exports/backend/tests/test_hogql_source.py b/products/batch_exports/backend/tests/test_hogql_source.pynew file mode 100644index 000000000000..c7bac72c62b4--- /dev/null+++ b/products/batch_exports/backend/tests/test_hogql_source.py@@ -0,0 +1,133 @@+import typing++import pytest++from posthog.sync import database_sync_to_async++from products.batch_exports.backend.hogql_source import (+ UnsupportedHogQLQueryError,+ create_hogql_context_for_batch_export,+ validate_hogql_query_for_batch_export,+)++pytestmark = pytest.mark.django_db+++async def _validate(hogql_query: str, team) -> None:+ # Resolving the query reads from Postgres to build the team database, so run it off the event loop.+ await database_sync_to_async(validate_hogql_query_for_batch_export)(hogql_query, team)+++ "hogql_query",+ [+ "SELECT event AS event, distinct_id AS distinct_id FROM events",+ """+ SELECT event AS event+ FROM events+ UNION ALL+ SELECT event AS event+ FROM events+ """,+ """+ SELECT+ event AS event,+ timestamp AS timestamp+ FROM events+ WHERE+ timestamp >= {data_interval_start}+ AND timestamp < {data_interval_end}+ """,+ # the placeholders may feed any expression, not only a plain comparison+ """+ SELECT event AS event+ FROM events+ WHERE+ timestamp >= {data_interval_start} - INTERVAL 2 DAY+ AND timestamp < {data_interval_end}+ """,+ # each member of a UNION must resolve on its own, and placeholders may appear in any of them+ """+ SELECT+ event AS event,+ timestamp AS timestamp+ FROM events+ WHERE+ timestamp >= {data_interval_start}+ AND timestamp < {data_interval_end}+ UNION ALL+ SELECT+ event AS event,+ timestamp AS timestamp+ FROM events+ WHERE+ timestamp >= {data_interval_start}+ AND timestamp < {data_interval_end}+ """,+ # placeholders inside a CTE are found and replaced too+ """+ WITH bounded AS (+ SELECT event AS event FROM events+ WHERE+ timestamp >= {data_interval_start}+ AND timestamp < {data_interval_end}+ )+ SELECT event AS event FROM bounded+ """,+ ],+ ids=[+ "no-placeholders",+ "union-without-placeholders",+ "bounded-query",+ "placeholder-in-expression",+ "union-with-placeholders",+ "cte-with-placeholders",+ ],+)+async def test_accepts_valid_queries(ateam, hogql_query):+ await _validate(hogql_query, ateam)+++ "hogql_query,expected_message",+ [+ ("SELECT does_not_exist FROM events", "Unable to resolve field: does_not_exist"),+ ("SELECT count() FROM events", "must be a field or have an alias"),+ ("SELECT event AS event FROM events WHERE {filters}", "Unsupported placeholder"),+ ("SELECT event AS event FROM events WHERE event = {concat('a', 'b')}", "Unsupported placeholder"),+ ("SELECT event AS event FROM events WHERE event = {unknown_placeholder}", "Unknown placeholder"),+ # the query must still resolve once the placeholders are substituted+ (+ "SELECT event AS event FROM events WHERE does_not_exist >= {data_interval_start}",+ "Unable to resolve field: does_not_exist",+ ),+ ],+ ids=[+ "unknown-field",+ "unaliased-expression",+ "filters-placeholder",+ "expression-placeholder",+ "unknown-placeholder",+ "unknown-field-in-placeholder-comparison",+ ],+)+async def test_rejects_unsupported_queries(ateam, hogql_query, expected_message):+ with pytest.raises(UnsupportedHogQLQueryError, match=expected_message):+ await _validate(hogql_query, ateam)++[email protected]("team_modifiers", [None, {"convertToProjectTimezone": False}])+def test_create_hogql_context_for_batch_exports(team, team_modifiers: dict[str, typing.Any] | None) -> None:+ if team_modifiers is not None:+ team.modifiers = team_modifiers+ else:+ team_modifiers = {}++ context = create_hogql_context_for_batch_export(team)++ assert context.team == team++ for key, value in team_modifiers.items():+ assert getattr(context.modifiers, key) == value, (+ f"Context modifier '{key}' should be set by team modifier. Expected '{value}', got '{getattr(context.modifiers, key)}'"+ )diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex ed51e6cc526c..f36da413d296 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1782,8 +1782,12 @@ export const FileDownloadHogQLRequestApiModel = {export interface FileDownloadHogQLRequestApi {file: FileDownloadDestinationFileConfigApimodel: FileDownloadHogQLRequestApiModel- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query: string+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */+ data_interval_start?: string+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */+ data_interval_end?: string}export type CreateFileDownloadRequestApi =@@ -1883,11 +1887,11 @@ export interface FileDownloadBatchExportOnDemandApi {model: FileDownloadBatchExportOnDemandModelEnumApiinclude?: string[]exclude?: string[]- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query?: string- /** Start of the data interval to export */+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */data_interval_start?: string- /** End of the data interval to export */+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */data_interval_end?: string}@@ -1909,8 +1913,12 @@ export interface FileDownloadCountRowsRequestApi {** * `hogql` - hogql */model: FileDownloadHogQLModelEnumApi- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query: string+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */+ data_interval_start?: string+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */+ data_interval_end?: string}/**@@ -1918,7 +1926,7 @@ export interface FileDownloadCountRowsRequestApi {*/export interface FileDownloadCountRowsResponseApi {/**- * Number of rows the query returns now. A HogQL batch export runs its query as of the time the export starts, so a run started now would export this many rows.+ * Number of rows the query returns with the supplied interval bounds. Data arriving between counting and exporting can change the result.* @minimum 0*/count: numberdiff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 451a2dc1c89a..aa49f44491c7 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -3668,7 +3668,19 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([hogql_query: zod.string().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'),}).describe('Typed configuration for the hogql model.'),@@ -3722,13 +3734,20 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod.string().optional().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'),data_interval_start: zod.iso.datetime({ offset: true }).optional()- .describe('Start of the data interval to export'),- data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'+ ),}).describe('Request shape for a FileDownload batch export on demand.')@@ -3744,7 +3763,19 @@ export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zodhogql_query: zod.string().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'),}).describe('Request shape for counting the rows a file download batch export would produce.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 37cead3d1fd0..116ee7203552 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22578,8 +22578,12 @@ export namespace Schemas {export interface FileDownloadHogQLRequest {file: FileDownloadDestinationFileConfig;model: FileDownloadHogQLRequestModel;- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query: string;+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */+ data_interval_start?: string;+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */+ data_interval_end?: string;}export type CreateFileDownloadRequest = FileDownloadEventsRequest | FileDownloadPersonsRequest | FileDownloadSessionsRequest | FileDownloadHogQLRequest;@@ -46295,11 +46299,11 @@ export namespace Schemas {model: FileDownloadBatchExportOnDemandModelEnum;include?: string[];exclude?: string[];- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query?: string;- /** Start of the data interval to export */+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */data_interval_start?: string;- /** End of the data interval to export */+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */data_interval_end?: string;}@@ -46321,8 +46325,12 @@ export namespace Schemas {** * `hogql` - hogql */model: FileDownloadHogQLModelEnum;- /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */+ /** HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models. */hogql_query: string;+ /** Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days. */+ data_interval_start?: string;+ /** End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query. */+ data_interval_end?: string;}/**@@ -46330,7 +46338,7 @@ export namespace Schemas {*/export interface FileDownloadCountRowsResponse {/**- * Number of rows the query returns now. A HogQL batch export runs its query as of the time the export starts, so a run started now would export this many rows.+ * Number of rows the query returns with the supplied interval bounds. Data arriving between counting and exporting can change the result.* @minimum 0*/count: number;diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.tsindex 9b24ad28e6ef..ed81ab325b3c 100644--- a/services/mcp/src/generated/batch_exports/api.ts+++ b/services/mcp/src/generated/batch_exports/api.ts@@ -1137,7 +1137,19 @@ export const FileDownloadBatchExportsCreateBody = () => zod.union([hogql_query: zod.string().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'),}).describe('Typed configuration for the hogql model.'),@@ -1216,13 +1228,20 @@ export const FileDownloadBatchExportsCancelCreateBody = () => zod.string().optional().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'),data_interval_start: zod.iso.datetime({ offset: true }).optional()- .describe('Start of the data interval to export'),- data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'+ ),}).describe('Request shape for a FileDownload batch export on demand.')@@ -1246,7 +1265,19 @@ export const FileDownloadBatchExportsCountRowsCreateBody = () => zodhogql_query: zod.string().describe(- 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ 'HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.'+ ),+ data_interval_start: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.'+ ),+ data_interval_end: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.'),}).describe('Request shape for counting the rows a file download batch export would produce.')diff --git a/services/mcp/src/tools/generated/batch_exports.ts b/services/mcp/src/tools/generated/batch_exports.tsindex 50f08e2b8659..05a7589b3178 100644--- a/services/mcp/src/tools/generated/batch_exports.ts+++ b/services/mcp/src/tools/generated/batch_exports.ts@@ -246,6 +246,12 @@ const fileDownloadBatchExportsCountRowsCreate = (): ToolBase<if (params.hogql_query !== undefined) {body['hogql_query'] = params.hogql_query}+ if (params.data_interval_start !== undefined) {+ body['data_interval_start'] = params.data_interval_start+ }+ if (params.data_interval_end !== undefined) {+ body['data_interval_end'] = params.data_interval_end+ }const result = await context.api.request<Schemas.FileDownloadCountRowsResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/file_download_batch_exports/count_rows/`,@@ -281,10 +287,10 @@ const fileDownloadBatchExportsCreate = (): ToolBase<if ('exclude' in params && params.exclude !== undefined) {body['exclude'] = params.exclude}- if ('data_interval_start' in params && params.data_interval_start !== undefined) {+ if (params.data_interval_start !== undefined) {body['data_interval_start'] = params.data_interval_start}- if ('data_interval_end' in params && params.data_interval_end !== undefined) {+ if (params.data_interval_end !== undefined) {body['data_interval_end'] = params.data_interval_end}if ('hogql_query' in params && params.hogql_query !== undefined) {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.jsonindex 1f4f2f971f6c..754ec15a8d32 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-cancel-create.json@@ -2,13 +2,13 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"data_interval_end": {- "description": "End of the data interval to export",+ "description": "End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"},"data_interval_start": {- "description": "Start of the data interval to export",+ "description": "Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"@@ -58,7 +58,7 @@"type": "object"},"hogql_query": {- "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.",+ "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.","type": "string"},"id": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.jsonindex a80d13f8f951..5699f9e6233a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json@@ -2,8 +2,20 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "Request shape for counting the rows a file download batch export would produce.","properties": {+ "data_interval_end": {+ "description": "End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "data_interval_start": {+ "description": "Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },"hogql_query": {- "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.",+ "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.","type": "string"},"model": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.jsonindex bbb47e5590e4..85ae006a8024 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json@@ -193,6 +193,18 @@{"description": "Typed configuration for the hogql model.","properties": {+ "data_interval_end": {+ "description": "End of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_end}. A supplied end must not be in the future or precede a supplied start. Bounds replace HogQL placeholders; they do not add filters to the query.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "data_interval_start": {+ "description": "Start of the export interval. Required for the events, persons, and sessions models. For HogQL, required only when the query references {data_interval_start}. A supplied start must not be in the future. When both bounds are supplied, the interval must span at most seven days.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },"file": {"description": "Typed configuration for a FileDownload batch-export destination.","properties": {@@ -232,7 +244,7 @@"type": "object"},"hogql_query": {- "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. Placeholders are not currently supported, and every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.",+ "description": "HogQL SELECT query whose results are exported. This model is in closed beta and is enabled per team; when it is not enabled, the request fails with a permission error that names HogQL batch exports. Contact PostHog support to request access. The query may reference the {data_interval_start} and {data_interval_end} placeholders. Provide a value for each placeholder the query references; missing referenced bounds are rejected, not inferred. When both bounds are supplied, they must span at most seven days. Neither supplied bound may be in the future. Without placeholders, the query runs unchanged, even if bounds are supplied. Every column in the SELECT clause must be a field or have an alias. It is recommended to limit the query with a WHERE clause, for example bounding timestamp on the events table, both to avoid exporting more rows than expected and because user queries run under stricter resource limits than the other models.","type": "string"},"model": {