Skip to content

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

feat(batch-exports): Add count_rows endpoint for hogql exports (#90977)

Tomás Farías Santana7b2da91589b0
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index ec762f87eea5..58e4a0f00adf 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1813,3 +1813,13 @@ class SupportSlackOAuthCallbackThrottle(IPThrottle):
scope = "support_slack_oauth_callback"
rate = "30/minute"
+
+
+class BatchExportsCountRowsSustainedRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ scope = "batch_exports_count_rows_sustained"
+ rate = "120/hour"
+
+
+class BatchExportsCountRowsBurstRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ scope = "batch_exports_count_rows_burst"
+ rate = "20/minute"
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e59a237fdda4..8df450062cbe 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -676,6 +676,8 @@ SPECTACULAR_SETTINGS = {
None,
],
"ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model",
+ # Shared by FileDownloadHogQLRequest.model and FileDownloadCountRowsRequest.model.
+ "FileDownloadHogQLModelEnum": ["hogql"],
"RecurrenceIntervalEnum": "products.reminders.backend.models.reminder.Reminder.RecurrenceInterval",
"ScannerModelEnum": "products.replay_vision.backend.models.replay_scanner.ScannerModel",
"ScannerTypeEnum": "products.replay_vision.backend.models.replay_scanner.ScannerType",
diff --git a/products/batch_exports/backend/api/file_download.py b/products/batch_exports/backend/api/file_download.py
index 2dd3a5a5867d..49dd5f7745d8 100644
--- a/products/batch_exports/backend/api/file_download.py
+++ b/products/batch_exports/backend/api/file_download.py
@@ -14,14 +14,22 @@ import structlog
import posthoganalytics
from botocore.client import Config
from botocore.exceptions import ClientError
-from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema
+from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema
from rest_framework import mixins, response, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationError
+from rest_framework.throttling import BaseThrottle
+
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.query import execute_hogql_query
from posthog.api.log_entries import LogEntryMixin
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models import Team
+from posthog.rate_limit import BatchExportsCountRowsBurstRateThrottle, BatchExportsCountRowsSustainedRateThrottle
from posthog.temporal.common.client import sync_connect
from products.batch_exports.backend.hogql_source import (
@@ -40,6 +48,8 @@ from products.batch_exports.backend.service import (
cancel_running_batch_export_run,
start_file_download_batch_export,
)
+from products.batch_exports.backend.temporal.record_batch_model import HogQLQueryRecordBatchModel
+from products.batch_exports.backend.temporal.sql.common import get_user_hogql_batch_export_query_settings
SESSION = boto3.Session()
FILE_DOWNLOAD_MAX_RANGE = dt.timedelta(weeks=1)
@@ -119,6 +129,26 @@ class FileDownloadHogQLRequestSerializer(serializers.Serializer):
hogql_query = serializers.CharField(help_text=HOGQL_QUERY_HELP_TEXT)
+class FileDownloadCountRowsRequestSerializer(serializers.Serializer):
+ """Request shape for counting the rows a file download batch export would produce."""
+
+ model = serializers.ChoiceField(
+ choices=["hogql"],
+ help_text="Model to count rows for. Only 'hogql' is supported.",
+ )
+ hogql_query = serializers.CharField(help_text=HOGQL_QUERY_HELP_TEXT)
+
+
+class FileDownloadCountRowsResponseSerializer(serializers.Serializer):
+ """Typed output for view set `count_rows`."""
+
+ 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.",
+ )
+
+
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(
@@ -136,6 +166,43 @@ def check_hogql_batch_exports_enabled(team: Team) -> None:
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 "
+ "complete and/or may produce a very large file to download. Narrow the query with a WHERE "
+ "clause to count and export less data if you can't tolerate the additional exeuction time "
+ "and/or file size."
+)
+
+
+def count_rows_for_hogql_batch_export(team: Team, hogql_query: str, timeout: int = 30) -> int:
+ """Count the rows a HogQL query would produce.
+
+ Raises:
+ UnsupportedHogQLQueryError: If the query cannot power a batch export.
+ """
+ validate_hogql_query_for_batch_export(hogql_query, team)
+
+ record_batch_model = HogQLQueryRecordBatchModel(team_id=team.pk, hogql_query=hogql_query)
+ query_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),
+ team=team,
+ query_type="HogQLBatchExportCountRowsQuery",
+ settings=query_settings,
+ )
+ return query_response.results[0][0] if query_response.results else 0
+
+
class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):
"""Request shape for a FileDownload batch export on demand."""
@@ -339,6 +406,13 @@ class FileDownloadBatchExportOnDemandViewSet(
return FileDownloadBatchExportOnDemandSerializer
+ def get_throttles(self) -> list[BaseThrottle]:
+ # `count_rows` runs a ClickHouse query per request, so it needs tighter limits than
+ # the default throttles.
+ if self.action == "count_rows":
+ return [BatchExportsCountRowsBurstRateThrottle(), BatchExportsCountRowsSustainedRateThrottle()]
+ return super().get_throttles()
+
@extend_schema(
request=PolymorphicProxySerializer(
component_name="CreateFileDownloadRequest",
@@ -546,6 +620,44 @@ class FileDownloadBatchExportOnDemandViewSet(
return response.Response({"status": batch_export_run.status})
+ @action(
+ methods=["POST"],
+ detail=False,
+ # User queries could impact production limits and billing. So, we
+ # require write permissions despite being a "read" operation.
+ required_scopes=["batch_export:write"],
+ request=FileDownloadCountRowsRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=FileDownloadCountRowsResponseSerializer,
+ description="Number of rows the export would produce if started now.",
+ ),
+ 400: OpenApiResponse(
+ description="The request or the HogQL query is invalid, or counting timed out because "
+ "the query is too complex or the count is too large, which can mean the export would "
+ "be very large."
+ ),
+ 403: OpenApiResponse(description="HogQL batch exports are not enabled for this team."),
+ },
+ )
+ @validated_request(request_serializer=FileDownloadCountRowsRequestSerializer)
+ def count_rows(self, request: ValidatedRequest, *args, **kwargs) -> response.Response:
+ """Count the rows a HogQL batch export would produce if started now."""
+ check_hogql_batch_exports_enabled(self.team)
+
+ try:
+ count = count_rows_for_hogql_batch_export(self.team, request.validated_data["hogql_query"])
+ except UnsupportedHogQLQueryError as e:
+ raise ValidationError({"hogql_query": str(e)}) from e
+ except (ExposedHogQLError, ExposedCHQueryError) as e:
+ raise ValidationError(str(e), getattr(e, "code_name", None)) from e
+ except ClickHouseQueryTimeOut as e:
+ # For a count, a timeout is feedback about the user's query, so report it as a 400
+ # with guidance instead of the generic 504.
+ raise ValidationError(COUNT_ROWS_TIMEOUT_MESSAGE, "timeout_exceeded") from e
+
+ return response.Response({"count": count})
+
def _generate_s3_pre_signed_url(
bucket: str,
diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.py
index 2663ada71de3..dbdbd5553bef 100644
--- a/products/batch_exports/backend/hogql_source.py
+++ b/products/batch_exports/backend/hogql_source.py
@@ -51,10 +51,12 @@ def create_hogql_context_for_batch_export(team: "Team", values: dict[str, typing
"""Build the HogQLContext batch exports use to resolve and print a query.
Both API-side validation and worker-side execution must build the context the same
- way (team-default modifiers, full database, no top-level LIMIT), otherwise a query
- that validates could resolve differently when it runs. This builder is the single
- source of truth for those semantics. It reads from Postgres, so worker code must
- call it off the event loop.
+ way, otherwise a query that validates could resolve differently when it runs. This
+ builder is the single source of truth for those semantics: the database is built
+ with team-default modifiers, the context keeps plain default modifiers for printing
+ (`Database.create_for` team-defaults a copy, not this context's instance), and no
+ top-level LIMIT is applied. It reads from Postgres, so worker code must call it off
+ the event loop.
"""
context = HogQLContext(
team=team,
diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.py
index e5ccc8f74837..cf36270ee592 100644
--- a/products/batch_exports/backend/temporal/record_batch_model.py
+++ b/products/batch_exports/backend/temporal/record_batch_model.py
@@ -376,6 +376,15 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):
"""
return parse_hogql_select_for_batch_export(self.hogql_query)
+ def get_count_hogql_query(
+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime
+ ) -> ast.SelectQuery:
+ """Return a HogQL query counting the rows this model would export."""
+ return ast.SelectQuery(
+ select=[parse_expr("count() AS count")],
+ select_from=ast.JoinExpr(table=self.get_hogql_query(data_interval_start, data_interval_end)),
+ )
+
def get_clickhouse_request_settings(self) -> dict[str, str]:
# Sent with the request instead of set on the query AST, because the user query may
# not parse to a simple `ast.SelectQuery` (e.g. a UNION parses to an
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
index 0c6aa59440b3..d3d341bed98a 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
@@ -19,10 +19,12 @@ from asgiref.sync import sync_to_async
from rest_framework import status
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models.scoping import team_scope
from posthog.temporal.tests.utils.events import generate_test_events, insert_event_values_in_clickhouse
from products.batch_exports.backend.api.file_download import (
+ COUNT_ROWS_TIMEOUT_MESSAGE,
_calculate_expiration_for_file_download,
_generate_s3_pre_signed_url,
_get_file_download_for_run,
@@ -875,3 +877,126 @@ class TestFileDownloadHogQL:
exported_rows = sorted((row["event"], row["distinct_id"], row["browser"]) for row in table.to_pylist())
expected_rows = sorted((e["event"], e["distinct_id"], "Chrome") for e in hogql_export_test_events)
assert exported_rows == expected_rows
+
+ @pytest.mark.parametrize(
+ "hogql_query,expected_count",
+ [
+ pytest.param(
+ "SELECT event AS event, distinct_id AS distinct_id FROM events",
+ 10,
+ id="plain-select-scoped-to-team",
+ ),
+ pytest.param(
+ "SELECT count() AS event_count FROM events",
+ 1,
+ 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,
+ id="union-all",
+ ),
+ pytest.param(
+ "SELECT event AS event FROM events LIMIT 4",
+ 4,
+ id="user-limit-caps-the-count",
+ ),
+ ],
+ )
+ @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):
+ await async_client.aforce_login(user)
+
+ response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",
+ {"model": "hogql", "hogql_query": hogql_query},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"count": expected_count}
+
+ @pytest.mark.parametrize(
+ "body,expected_error_fragment",
+ [
+ pytest.param(
+ {"model": "hogql"},
+ "This field is required",
+ id="missing-query",
+ ),
+ pytest.param(
+ {"model": "events", "hogql_query": "SELECT event AS event FROM events"},
+ "is not a valid choice",
+ id="unsupported-model",
+ ),
+ pytest.param(
+ {"model": "hogql", "hogql_query": "this is not hogql"},
+ "Failed to parse HogQL query",
+ id="unparseable-query",
+ ),
+ pytest.param(
+ {"model": "hogql", "hogql_query": "SELECT event AS event FROM events WHERE {filters}"},
+ "Placeholders are not supported",
+ id="placeholder-query",
+ ),
+ pytest.param(
+ {"model": "hogql", "hogql_query": "SELECT count() FROM events"},
+ "must be a field or have an alias",
+ id="unaliased-expression-column",
+ ),
+ pytest.param(
+ {"model": "hogql", "hogql_query": "SELECT x AS x FROM no_such_table"},
+ "no_such_table",
+ id="unknown-table",
+ ),
+ ],
+ )
+ @pytest.mark.usefixtures("enable_hogql_flag")
+ @pytest.mark.django_db(transaction=True)
+ async def test_count_rows_rejects_invalid_requests(
+ self, async_client: AsyncClient, team, user, body, expected_error_fragment
+ ):
+ 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",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert expected_error_fragment in response.content.decode()
+ assert await sync_to_async(lambda: BatchExportSource.objects.for_team(team.pk).count())() == 0
+
+ @pytest.mark.django_db(transaction=True)
+ async def test_count_rows_rejected_when_flag_disabled(self, async_client: AsyncClient, team, user):
+ await async_client.aforce_login(user)
+
+ with unittest.mock.patch(self.HOGQL_FLAG_PATCH_TARGET, return_value=False) as mock_flag:
+ response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",
+ {"model": "hogql", "hogql_query": "SELECT event AS event FROM events"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert mock_flag.call_args[0][0] == "hogql-batch-exports"
+
+ @pytest.mark.usefixtures("enable_hogql_flag")
+ @pytest.mark.django_db(transaction=True)
+ async def test_count_rows_timeout_reports_potentially_large_export(self, async_client: AsyncClient, team, user):
+ await async_client.aforce_login(user)
+
+ with unittest.mock.patch(
+ "products.batch_exports.backend.api.file_download.execute_hogql_query",
+ side_effect=ClickHouseQueryTimeOut(),
+ ):
+ response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",
+ {"model": "hogql", "hogql_query": "SELECT event AS event FROM events"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert COUNT_ROWS_TIMEOUT_MESSAGE in response.content.decode()
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index 6ac21f1ea101..d3189db097ab 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -1880,6 +1880,39 @@ export interface FileDownloadBatchExportOnDemandApi {
data_interval_end?: string
}
+/**
+ * * `hogql` - hogql
+ */
+export type FileDownloadHogQLModelEnumApi =
+ (typeof FileDownloadHogQLModelEnumApi)[keyof typeof FileDownloadHogQLModelEnumApi]
+
+export const FileDownloadHogQLModelEnumApi = {
+ Hogql: 'hogql',
+} as const
+
+/**
+ * Request shape for counting the rows a file download batch export would produce.
+ */
+export interface FileDownloadCountRowsRequestApi {
+ /** Model to count rows for. Only 'hogql' is supported.
+ *
+ * * `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_query: string
+}
+
+/**
+ * Typed output for view set `count_rows`.
+ */
+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.
+ * @minimum 0
+ */
+ count: number
+}
+
/**
* * `events` - events
*/
@@ -1910,16 +1943,6 @@ export const FileDownloadSessionsRequestModelEnumApi = {
Sessions: 'sessions',
} as const
-/**
- * * `hogql` - hogql
- */
-export type FileDownloadHogQLRequestModelEnumApi =
- (typeof FileDownloadHogQLRequestModelEnumApi)[keyof typeof FileDownloadHogQLRequestModelEnumApi]
-
-export const FileDownloadHogQLRequestModelEnumApi = {
- Hogql: 'hogql',
-} as const
-
/**
* * `Starting` - Starting
* * `Running` - Running
diff --git a/products/batch_exports/frontend/generated/api.ts b/products/batch_exports/frontend/generated/api.ts
index b8782a22e514..25afac642f0f 100644
--- a/products/batch_exports/frontend/generated/api.ts
+++ b/products/batch_exports/frontend/generated/api.ts
@@ -23,6 +23,8 @@ import type {
FileDownloadBatchExportOnDemandApi,
FileDownloadBatchExportsListParams,
FileDownloadBatchExportsLogsRetrieveParams,
+ FileDownloadCountRowsRequestApi,
+ FileDownloadCountRowsResponseApi,
PaginatedBatchExportBackfillListApi,
PaginatedBatchExportListApi,
PaginatedBatchExportRunListApi,
@@ -654,3 +656,23 @@ export const fileDownloadBatchExportsLogsRetrieve = async (
method: 'GET',
})
}
+
+export const getFileDownloadBatchExportsCountRowsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/file_download_batch_exports/count_rows/`
+}
+
+/**
+ * Count the rows a HogQL batch export would produce if started now.
+ */
+export const fileDownloadBatchExportsCountRowsCreate = async (
+ projectId: string,
+ fileDownloadCountRowsRequestApi: FileDownloadCountRowsRequestApi,
+ options?: RequestInit
+): Promise<FileDownloadCountRowsResponseApi> => {
+ return apiMutator<FileDownloadCountRowsResponseApi>(getFileDownloadBatchExportsCountRowsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(fileDownloadCountRowsRequestApi),
+ })
+}
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index 38279c40378a..a5a26ccebc0a 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -3591,3 +3591,20 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod
data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),
})
.describe('Request shape for a FileDownload batch export on demand.')
+
+/**
+ * Count the rows a HogQL batch export would produce if started now.
+ */
+export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod
+ .object({
+ model: zod
+ .enum(['hogql'])
+ .describe('\* `hogql` - hogql')
+ .describe("Model to count rows for. Only 'hogql' is supported.\n\n\* `hogql` - hogql"),
+ 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.'
+ ),
+ })
+ .describe('Request shape for counting the rows a file download batch export would produce.')
diff --git a/products/batch_exports/mcp/tools.yaml b/products/batch_exports/mcp/tools.yaml
index 7a410db3fc32..1144ebadce98 100644
--- a/products/batch_exports/mcp/tools.yaml
+++ b/products/batch_exports/mcp/tools.yaml
@@ -190,6 +190,26 @@ tools:
description: >
Cancel a running or starting on-demand file download export. When the status is not Starting or Running
calling this will fail. Returns the status of the export after cancelling, which is always Cancelled.
+ file-download-batch-exports-count-rows-create:
+ operation: file_download_batch_exports_count_rows_create
+ enabled: true
+ scopes:
+ - batch_export:write
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Count rows a HogQL file download export would produce
+ description: >
+ Count the rows a HogQL file download export would produce if started now, without starting an export. Only
+ the hogql model is supported; it is in closed beta and enabled per team, and this returns a permission error
+ naming HogQL batch exports when the team does not have it enabled, in which case tell the user they can
+ contact PostHog support to request access. Counting runs the full query on ClickHouse, so it can take a
+ while and can fail with a timeout for heavy unbounded queries. If the user wishes to estimate the size of an
+ export, use it before file-download-batch-exports-create to check a hogql_query returns the amount of data
+ the user expects, and tighten its WHERE clause when the count is much larger than expected. Running count
+ queries is potentially as expensive as running the actual export query, so consider whether this is worth
+ it.
file-download-batch-exports-create:
operation: file_download_batch_exports_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 880555568f56..b720e510e9f0 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5227,6 +5227,20 @@
"readOnlyHint": false
}
},
+ "file-download-batch-exports-count-rows-create": {
+ "description": "Count the rows a HogQL file download export would produce if started now, without starting an export. Only the hogql model is supported; it is in closed beta and enabled per team, and this returns a permission error naming HogQL batch exports when the team does not have it enabled, in which case tell the user they can contact PostHog support to request access. Counting runs the full query on ClickHouse, so it can take a while and can fail with a timeout for heavy unbounded queries. If the user wishes to estimate the size of an export, use it before file-download-batch-exports-create to check a hogql_query returns the amount of data the user expects, and tighten its WHERE clause when the count is much larger than expected. Running count queries is potentially as expensive as running the actual export query, so consider whether this is worth it.",
+ "category": "Data pipelines",
+ "feature": "batch_exports",
+ "summary": "Count rows a HogQL file download export would produce",
+ "title": "Count rows a HogQL file download export would produce",
+ "required_scopes": ["batch_export:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"file-download-batch-exports-create": {
"description": "Start an on-demand batch export that prepares downloadable files for events, persons, sessions, or the results of a HogQL query. For events, persons and sessions, provide data_interval_start and data_interval_end as ISO 8601 datetimes; the interval must be at most one week, and for events, include and exclude filter event names. The hogql model is in closed beta and is enabled per team: it takes a hogql_query instead of a data interval, and returns a permission error naming HogQL batch exports when the team does not have it enabled, in which case tell the user they can contact PostHog support to request access. Limit hogql_query with a WHERE clause to export only the data the user asked for, because user queries run under stricter resource limits than the other models. Use file-download-batch-exports-retrieve with the returned id to poll until status is Completed, then follow the downloading-batch-export-files skill to download the files through the existing REST download endpoint.",
"category": "Data pipelines",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 26f7d7e45460..e38260a5c611 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5396,6 +5396,20 @@
"readOnlyHint": false
}
},
+ "file-download-batch-exports-count-rows-create": {
+ "description": "Count the rows a HogQL file download export would produce if started now, without starting an export. Only the hogql model is supported; it is in closed beta and enabled per team, and this returns a permission error naming HogQL batch exports when the team does not have it enabled, in which case tell the user they can contact PostHog support to request access. Counting runs the full query on ClickHouse, so it can take a while and can fail with a timeout for heavy unbounded queries. If the user wishes to estimate the size of an export, use it before file-download-batch-exports-create to check a hogql_query returns the amount of data the user expects, and tighten its WHERE clause when the count is much larger than expected. Running count queries is potentially as expensive as running the actual export query, so consider whether this is worth it.",
+ "category": "Data pipelines",
+ "feature": "batch_exports",
+ "summary": "Count rows a HogQL file download export would produce",
+ "title": "Count rows a HogQL file download export would produce",
+ "required_scopes": ["batch_export:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"file-download-batch-exports-create": {
"description": "Start an on-demand batch export that prepares downloadable files for events, persons, sessions, or the results of a HogQL query. For events, persons and sessions, provide data_interval_start and data_interval_end as ISO 8601 datetimes; the interval must be at most one week, and for events, include and exclude filter event names. The hogql model is in closed beta and is enabled per team: it takes a hogql_query instead of a data interval, and returns a permission error naming HogQL batch exports when the team does not have it enabled, in which case tell the user they can contact PostHog support to request access. Limit hogql_query with a WHERE clause to export only the data the user asked for, because user queries run under stricter resource limits than the other models. Use file-download-batch-exports-retrieve with the returned id to poll until status is Completed, then follow the downloading-batch-export-files skill to download the files through the existing REST download endpoint.",
"category": "Data pipelines",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 46a415a94f6e..ac87220bd52d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39883,23 +39883,46 @@ export namespace Schemas {
}
/**
- * * `events` - events
+ * * `hogql` - hogql
*/
- export type FileDownloadEventsRequestModelEnum = typeof FileDownloadEventsRequestModelEnum[keyof typeof FileDownloadEventsRequestModelEnum];
+ export type FileDownloadHogQLModelEnum = typeof FileDownloadHogQLModelEnum[keyof typeof FileDownloadHogQLModelEnum];
- export const FileDownloadEventsRequestModelEnum = {
- Events: 'events',
+ export const FileDownloadHogQLModelEnum = {
+ Hogql: 'hogql',
} as const;
/**
- * * `hogql` - hogql
+ * Request shape for counting the rows a file download batch export would produce.
*/
- export type FileDownloadHogQLRequestModelEnum = typeof FileDownloadHogQLRequestModelEnum[keyof typeof FileDownloadHogQLRequestModelEnum];
+ export interface FileDownloadCountRowsRequest {
+ /** Model to count rows for. Only 'hogql' is supported.
+ *
+ * * `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_query: string;
+ }
+ /**
+ * Typed output for view set `count_rows`.
+ */
+ 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.
+ * @minimum 0
+ */
+ count: number;
+ }
- export const FileDownloadHogQLRequestModelEnum = {
- Hogql: 'hogql',
+ /**
+ * * `events` - events
+ */
+ export type FileDownloadEventsRequestModelEnum = typeof FileDownloadEventsRequestModelEnum[keyof typeof FileDownloadEventsRequestModelEnum];
+
+
+ export const FileDownloadEventsRequestModelEnum = {
+ Events: 'events',
} as const;
/**
diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.ts
index c5839fcf52a8..43a6975f0190 100644
--- a/services/mcp/src/generated/batch_exports/api.ts
+++ b/services/mcp/src/generated/batch_exports/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1173,3 +1173,28 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod
data_interval_end: zod.iso.datetime({ offset: true }).optional().describe('End of the data interval to export'),
})
.describe('Request shape for a FileDownload batch export on demand.')
+
+/**
+ * Count the rows a HogQL batch export would produce if started now.
+ */
+export const FileDownloadBatchExportsCountRowsCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod
+ .object({
+ model: zod
+ .enum(['hogql'])
+ .describe('\* `hogql` - hogql')
+ .describe("Model to count rows for. Only 'hogql' is supported.\n\n\* `hogql` - hogql"),
+ 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.'
+ ),
+ })
+ .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.ts
index f2960be88042..d5d9a787a91e 100644
--- a/services/mcp/src/tools/generated/batch_exports.ts
+++ b/services/mcp/src/tools/generated/batch_exports.ts
@@ -11,6 +11,7 @@ import {
BatchExportsRetrieveParams,
FileDownloadBatchExportsCancelCreateBody,
FileDownloadBatchExportsCancelCreateParams,
+ FileDownloadBatchExportsCountRowsCreateBody,
FileDownloadBatchExportsCreateBody,
FileDownloadBatchExportsRetrieveParams,
} from '@/generated/batch_exports/api'
@@ -213,6 +214,32 @@ const fileDownloadBatchExportsCancelCreate = (): ToolBase<
},
})
+const FileDownloadBatchExportsCountRowsCreateSchema = FileDownloadBatchExportsCountRowsCreateBody
+
+const fileDownloadBatchExportsCountRowsCreate = (): ToolBase<
+ typeof FileDownloadBatchExportsCountRowsCreateSchema,
+ Schemas.FileDownloadCountRowsResponse
+> => ({
+ name: 'file-download-batch-exports-count-rows-create',
+ schema: FileDownloadBatchExportsCountRowsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof FileDownloadBatchExportsCountRowsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.model !== undefined) {
+ body['model'] = params.model
+ }
+ if (params.hogql_query !== undefined) {
+ body['hogql_query'] = params.hogql_query
+ }
+ const result = await context.api.request<Schemas.FileDownloadCountRowsResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/file_download_batch_exports/count_rows/`,
+ body,
+ })
+ return result
+ },
+})
+
const FileDownloadBatchExportsCreateSchema = FileDownloadBatchExportsCreateBody
const fileDownloadBatchExportsCreate = (): ToolBase<typeof FileDownloadBatchExportsCreateSchema, unknown> => ({
@@ -276,6 +303,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'batch-export-update': batchExportUpdate,
'batch-exports-list': batchExportsList,
'file-download-batch-exports-cancel-create': fileDownloadBatchExportsCancelCreate,
+ 'file-download-batch-exports-count-rows-create': fileDownloadBatchExportsCountRowsCreate,
'file-download-batch-exports-create': fileDownloadBatchExportsCreate,
'file-download-batch-exports-retrieve': fileDownloadBatchExportsRetrieve,
}
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.json
new file mode 100644
index 000000000000..a80d13f8f951
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "description": "Request shape for counting the rows a file download batch export would produce.",
+ "properties": {
+ "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.",
+ "type": "string"
+ },
+ "model": {
+ "description": "Model to count rows for. Only 'hogql' is supported.\n\n* `hogql` - hogql",
+ "enum": ["hogql"],
+ "type": "string"
+ }
+ },
+ "required": ["model", "hogql_query"],
+ "type": "object"
+}