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: Support cancelling file download batch exports (#60029)

Tomás Farías Santanab24c25d99038
diff --git a/posthog/batch_exports/api/file_download.py b/posthog/batch_exports/api/file_download.py
index 1e63a2ef8917..65b2a0d0e3c6 100644
--- a/posthog/batch_exports/api/file_download.py
+++ b/posthog/batch_exports/api/file_download.py
@@ -21,8 +21,9 @@ from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models import BatchExportDestination, BatchExportFileDownload, BatchExportOnDemand, BatchExportRun
+from posthog.temporal.common.client import sync_connect
-from products.batch_exports.backend.service import start_file_download_batch_export
+from products.batch_exports.backend.service import cancel_running_batch_export_run, start_file_download_batch_export
SESSION = boto3.Session()
FILE_DOWNLOAD_MAX_RANGE = dt.timedelta(weeks=1)
@@ -347,6 +348,26 @@ class FileDownloadBatchExportOnDemandViewSet(
return response
+ @action(methods=["POST"], detail=True, required_scopes=["batch_export:write"])
+ def cancel(self, request, *args, **kwargs) -> response.Response:
+ """Cancel an ongoing file-download batch export."""
+ batch_export_run: BatchExportRun = self.get_object()
+
+ if batch_export_run.status not in (BatchExportRun.Status.RUNNING, BatchExportRun.Status.STARTING):
+ raise ValidationError(f"Cannot cancel a run that is in '{batch_export_run.status}' status")
+
+ temporal = sync_connect()
+ try:
+ cancel_running_batch_export_run(temporal, batch_export_run)
+ except Exception as e:
+ # It could be the case that the run is already cancelled but our database hasn't been updated yet. In
+ # this case, we can just ignore the error but log it for visibility (in case there is an actual issue).
+ LOGGER.warning("file_download_batch_export.cancel.failed", exc_info=e)
+
+ batch_export_run.refresh_from_db()
+
+ return response.Response({"status": batch_export_run.status})
+
def _generate_s3_pre_signed_url(
bucket: str,
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 4dd3f86cd172..af8748f36c9e 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
@@ -6,6 +6,7 @@ from urllib.parse import urlsplit
import pytest
import freezegun
+import unittest.mock
from django.conf import settings
from django.test import AsyncClient, override_settings
@@ -387,3 +388,45 @@ async def test_file_download_end_to_end(
assert len(table) == len(events)
assert "event" in table.column_names
+
+
[email protected]_db(transaction=True)
+async def test_file_download_cancel_mocked(
+ async_client: AsyncClient,
+ team,
+ user,
+ data_interval_start,
+ data_interval_end,
+):
+ destination = await BatchExportDestination.objects.acreate(
+ type=BatchExportDestination.Destination.FILE_DOWNLOAD, config={}
+ )
+ with team_scope(team_id=team.pk, canonical=True):
+ batch_export = await BatchExportOnDemand.objects.acreate(team=team, destination=destination, model="events")
+ run = await BatchExportRun.objects.acreate(
+ batch_export_on_demand=batch_export,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ status=BatchExportRun.Status.RUNNING,
+ )
+
+ await async_client.aforce_login(user)
+
+ mocked_client = unittest.mock.MagicMock()
+ mocked_handle = unittest.mock.AsyncMock()
+ mocked_client.get_workflow_handle.return_value = mocked_handle
+
+ with unittest.mock.patch("posthog.batch_exports.api.file_download.sync_connect") as mocked_connect:
+ mocked_connect.return_value = mocked_client
+ status_response = await async_client.post(
+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/cancel",
+ )
+
+ mocked_client.get_workflow_handle.assert_called_once_with(workflow_id=run.workflow_id)
+ mocked_handle.cancel.assert_called_once()
+
+ data = status_response.json()
+ assert data["status"] == "Cancelled", status_response.json()
+
+ await run.arefresh_from_db()
+ assert run.status == BatchExportRun.Status.CANCELLED
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index c80aaebec8f5..c6065bd245ae 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -1440,6 +1440,32 @@ export type RetrieveFileDownloadResponseApi =
| RetrieveCompletedOutputApi
| RetrieveFailedOutputApi
+/**
+ * * `events` - events
+ * `persons` - persons
+ * `sessions` - sessions
+ */
+export type FileDownloadBatchExportOnDemandModelEnumApi =
+ (typeof FileDownloadBatchExportOnDemandModelEnumApi)[keyof typeof FileDownloadBatchExportOnDemandModelEnumApi]
+
+export const FileDownloadBatchExportOnDemandModelEnumApi = {
+ Events: 'events',
+ Persons: 'persons',
+ Sessions: 'sessions',
+} as const
+
+/**
+ * Request shape for a FileDownload batch export on demand.
+ */
+export interface FileDownloadBatchExportOnDemandApi {
+ file: FileDownloadDestinationFileConfigApi
+ model: FileDownloadBatchExportOnDemandModelEnumApi
+ include?: string[]
+ exclude?: string[]
+ data_interval_start: string
+ data_interval_end: string
+}
+
/**
* * `events` - events
*/
diff --git a/products/batch_exports/frontend/generated/api.ts b/products/batch_exports/frontend/generated/api.ts
index 0ae8909d90fc..2d3c00574a18 100644
--- a/products/batch_exports/frontend/generated/api.ts
+++ b/products/batch_exports/frontend/generated/api.ts
@@ -20,6 +20,7 @@ import type {
BatchExportsRunsLogsRetrieveParams,
CreateFileDownloadRequestApi,
CreateOutputApi,
+ FileDownloadBatchExportOnDemandApi,
FileDownloadBatchExportsLogsRetrieveParams,
PaginatedBatchExportBackfillListApi,
PaginatedBatchExportListApi,
@@ -546,6 +547,27 @@ export const fileDownloadBatchExportsRetrieve = async (
})
}
+export const getFileDownloadBatchExportsCancelCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/file_download_batch_exports/${id}/cancel/`
+}
+
+/**
+ * Cancel an ongoing file-download batch export.
+ */
+export const fileDownloadBatchExportsCancelCreate = async (
+ projectId: string,
+ id: string,
+ fileDownloadBatchExportOnDemandApi: FileDownloadBatchExportOnDemandApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getFileDownloadBatchExportsCancelCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(fileDownloadBatchExportOnDemandApi),
+ })
+}
+
export const getFileDownloadBatchExportsDownloadRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/file_download_batch_exports/${id}/download/`
}
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index 7745cc58bd45..5bec25828713 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -1708,3 +1708,48 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([
})
.describe('Typed configuration for the sessions model.'),
])
+
+/**
+ * Cancel an ongoing file-download batch export.
+ */
+export const fileDownloadBatchExportsCancelCreateBodyFileFormatDefault = `Parquet`
+export const fileDownloadBatchExportsCancelCreateBodyFileMaxSizeMbMin = 0
+
+export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zod
+ .object({
+ file: zod
+ .object({
+ format: zod
+ .enum(['JSONLines', 'Parquet'])
+ .describe('\* `JSONLines` - JSONLines\n\* `Parquet` - Parquet')
+ .default(fileDownloadBatchExportsCancelCreateBodyFileFormatDefault)
+ .describe('File format\n\n\* `Parquet` - Parquet\n\* `JSONLines` - JSONLines'),
+ compression: zod
+ .union([
+ zod
+ .enum(['brotli', 'gzip', 'lz4', 'snappy', 'zstd'])
+ .describe(
+ '\* `brotli` - brotli\n\* `gzip` - gzip\n\* `lz4` - lz4\n\* `snappy` - snappy\n\* `zstd` - zstd'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Compress the file with a supported compression format\n\n\* `zstd` - zstd\n\* `gzip` - gzip\n\* `brotli` - brotli\n\* `lz4` - lz4\n\* `snappy` - snappy'
+ ),
+ max_size_mb: zod
+ .number()
+ .min(fileDownloadBatchExportsCancelCreateBodyFileMaxSizeMbMin)
+ .nullish()
+ .describe('Split download into multiple files of at most this size in MB'),
+ })
+ .describe('Typed configuration for a FileDownload batch-export destination.'),
+ model: zod
+ .enum(['events', 'persons', 'sessions'])
+ .describe('\* `events` - events\n\* `persons` - persons\n\* `sessions` - sessions'),
+ include: zod.array(zod.string()).optional(),
+ exclude: zod.array(zod.string()).optional(),
+ data_interval_start: zod.iso.datetime({ offset: true }),
+ data_interval_end: zod.iso.datetime({ offset: true }),
+ })
+ .describe('Request shape for a FileDownload batch export on demand.')
diff --git a/products/batch_exports/mcp/tools.yaml b/products/batch_exports/mcp/tools.yaml
index e2637b296355..74f2af591c92 100644
--- a/products/batch_exports/mcp/tools.yaml
+++ b/products/batch_exports/mcp/tools.yaml
@@ -176,6 +176,9 @@ tools:
batch-exports-update:
operation: batch_exports_update
enabled: false
+ file-download-batch-exports-cancel-create:
+ operation: file_download_batch_exports_cancel_create
+ enabled: false
file-download-batch-exports-create:
operation: file_download_batch_exports_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6873563205fe..11dca953ae52 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17199,6 +17199,32 @@ export namespace Schemas {
readonly modified_by: number | null;
}
+ /**
+ * * `events` - events
+ * `persons` - persons
+ * `sessions` - sessions
+ */
+ export type FileDownloadBatchExportOnDemandModelEnum = typeof FileDownloadBatchExportOnDemandModelEnum[keyof typeof FileDownloadBatchExportOnDemandModelEnum];
+
+
+ export const FileDownloadBatchExportOnDemandModelEnum = {
+ Events: 'events',
+ Persons: 'persons',
+ Sessions: 'sessions',
+ } as const;
+
+ /**
+ * Request shape for a FileDownload batch export on demand.
+ */
+ export interface FileDownloadBatchExportOnDemand {
+ file: FileDownloadDestinationFileConfig;
+ model: FileDownloadBatchExportOnDemandModelEnum;
+ include?: string[];
+ exclude?: string[];
+ data_interval_start: string;
+ data_interval_end: string;
+ }
+
/**
* * `events` - events
*/