: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
chore(batch-exports): move file downloads behind the facade (#115577)
Rossa3e934bf18d5
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 1ca6f5d96496..81100ba3bd2c 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -103,6 +103,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.autoresearch.backend.presentation.views.views.AutoresearchSuggestionViewSet","products.autoresearch.backend.presentation.views.views.AutoresearchTrainingRunViewSet","products.batch_exports.backend.presentation.views.batch_export.runs.BatchExportRunViewSet",+ "products.batch_exports.backend.presentation.views.file_download.FileDownloadBatchExportOnDemandViewSet","products.business_knowledge.backend.api.playground.BusinessKnowledgePlaygroundChatViewSet","products.business_knowledge.backend.api.views.KnowledgeGapSuggestionViewSet","products.business_knowledge.backend.api.views.KnowledgeSourceViewSet",diff --git a/products/batch_exports/backend/facade/api.py b/products/batch_exports/backend/facade/api.pyindex 9160a9a60637..c845e4947277 100644--- a/products/batch_exports/backend/facade/api.py+++ b/products/batch_exports/backend/facade/api.py@@ -10,7 +10,9 @@ is visible in one place.(``posthog/test/repo_invariants/test_startup_import_budget.py``) forbids both that moduleand ``temporalio`` on the ``django.setup()`` path. Core config-time consumers import thisfacade, so it reaches the service only through ``_service()``, which imports it at call-time. For the same reason the Temporal client is built in ``_get_temporal_client()``.+time. For the same reason the Temporal client is built in ``_get_temporal_client()``, and+the HogQL and file download modules load through ``_import_hogql_source()`` and+``_import_file_downloads()``.Temporal workflow and activity registration crosses as objects, not data, so it lives in``facade/temporal.py``. The destination clients the warehouse writers reuse live in@@ -30,6 +32,7 @@ from django.db.models.functions import Coalesceimport structlog+from posthog.models import Team, Userfrom posthog.models.integration import Integrationfrom products.batch_exports.backend import destination_tests@@ -53,14 +56,19 @@ __all__ = ["FAILED_BACKFILL_STATUSES","MultipleBatchExportsError","backfill_batch_export",+ "cancel_file_download","count_batch_exports_for_teams",+ "count_hogql_rows","create_batch_export","create_workflows_backfill_export","delete_batch_export","delete_batch_exports_for_teams","describe_destination_test","drop_unknown_hogql_modifiers",+ "find_hogql_interval_placeholders","get_batch_export_by_name",+ "get_file_download_run",+ "get_file_download_url","get_latest_completed_run","get_latest_run","get_run_failure",@@ -68,9 +76,12 @@ __all__ = ["get_teams_with_billable_rows_exported","list_backfills_for_export","list_batch_exports_using_integration",+ "list_file_download_runs","list_latest_failed_runs","list_supported_intervals","run_destination_test_step",+ "start_file_download",+ "validate_hogql_query",]logger = structlog.get_logger(__name__)@@ -109,6 +120,20 @@ def _service() -> ModuleType:return service+def _import_hogql_source() -> ModuleType:+ """Import the HogQL helpers at call time. See the module docstring for why."""+ from products.batch_exports.backend import hogql_source++ return hogql_source+++def _import_file_downloads() -> ModuleType:+ """Import the file download module at call time. See the module docstring for why."""+ from products.batch_exports.backend.logic import file_downloads++ return file_downloads++def _get_temporal_client() -> "Client":"""Connect to Temporal at call time. See the module docstring for why."""from posthog.temporal.common.client import sync_connect@@ -474,3 +499,101 @@ def drop_unknown_hogql_modifiers(stored: Mapping[str, Any]) -> dict[str, Any]:)return drop_unknown(dict(stored))+++def find_hogql_interval_placeholders(hogql_query: str) -> frozenset[str]:+ """Return the interval placeholders a batch export HogQL query references.++ The names are ``data_interval_start`` and ``data_interval_end``. Raises+ ``contracts.UnsupportedHogQLQueryError`` when the query is not a SELECT, or references+ another placeholder.+ """+ hogql_source = _import_hogql_source()+ return frozenset(+ hogql_source.find_interval_placeholders(hogql_source.parse_hogql_select_for_batch_export(hogql_query))+ )+++def validate_hogql_query(+ team_id: int, *, user_id: int, hogql_query: str, hogql_modifiers: Mapping[str, object] | None+) -> None:+ """Check that a HogQL query can power a batch export, with the user's table and property permissions.++ Raises ``contracts.UnsupportedHogQLQueryError`` when it cannot.+ """+ hogql_source = _import_hogql_source()+ hogql_source.validate_hogql_query_for_batch_export(+ hogql_query,+ Team.objects.get(id=team_id),+ user=User.objects.get(id=user_id),+ modifiers=hogql_source.load_hogql_modifiers(dict(hogql_modifiers) if hogql_modifiers is not None else None),+ )+++def count_hogql_rows(+ team_id: int,+ *,+ user_id: int,+ hogql_query: str,+ hogql_modifiers: Mapping[str, object] | None,+ data_interval_start: dt.datetime | None,+ data_interval_end: dt.datetime | None,+) -> int:+ """Count the rows a HogQL batch export would produce if it ran now, over the given bounds.++ The query runs in ClickHouse with a short timeout. Raises+ ``contracts.UnsupportedHogQLQueryError`` when the query cannot power a batch export, and+ lets the HogQL and ClickHouse query errors through: ``ExposedHogQLError``,+ ``ExposedCHQueryError`` and ``ClickHouseQueryTimeOut``.+ """+ return _import_file_downloads().count_rows_for_hogql_batch_export(+ team_id,+ hogql_query,+ user_id=user_id,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ hogql_modifiers=dict(hogql_modifiers) if hogql_modifiers is not None else None,+ )+++def list_file_download_runs(+ team_id: int, *, offset: int, limit: int+) -> tuple[list[contracts.BatchExportRunSummary], int]:+ """Return one page of the team's file download runs, newest first, and how many there are in total."""+ runs, count = _import_file_downloads().list_file_download_runs(team_id, offset=offset, limit=limit)+ return [_to_run_summary(run) for run in runs], count+++def get_file_download_run(team_id: int, run_id: UUID) -> contracts.FileDownloadRun:+ """Return a file download run. Raises ``contracts.FileDownloadNotFoundError`` when the team has no such run."""+ return _import_file_downloads().get_file_download_run(team_id, run_id)+++def start_file_download(team_id: int, *, user_id: int, request: contracts.FileDownloadRequest) -> UUID:+ """Create a file download run and start the workflow that writes its files. Return the run id.++ A team can have only ``BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM`` file downloads+ starting or running. Over that limit, this raises+ ``contracts.TooManyConcurrentFileDownloadsError`` and creates nothing. When the workflow+ does not start, the run is saved as failed and this raises ``contracts.FileDownloadStartError``.+ """+ return _import_file_downloads().start_file_download(team_id, user_id, request)+++def cancel_file_download(team_id: int, run_id: UUID) -> str:+ """Cancel a file download that is starting or running, and return the status of the run after that.++ Raises ``contracts.InvalidFileDownloadRequestError`` when the run is in another status.+ """+ return _import_file_downloads().cancel_file_download(team_id, run_id)+++def get_file_download_url(team_id: int, run_id: UUID, part: str | None) -> str:+ """Return a short-lived URL that downloads one file of a completed file download run.++ ``part`` is a file id, or a file index in download order. Without it, the first file is+ returned. Raises ``contracts.InvalidFileDownloadRequestError`` when the run did not+ complete, the part is not valid or the file has expired, and+ ``contracts.FileDownloadNotFoundError`` when the run or the file does not exist.+ """+ return _import_file_downloads().get_file_download_url(team_id, run_id, part)diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.pyindex f1e2d0e966ee..43f6ba3dd7cc 100644--- a/products/batch_exports/backend/facade/contracts.py+++ b/products/batch_exports/backend/facade/contracts.py@@ -37,6 +37,29 @@ class UnsupportedDestinationTestError(ValueError):"""Raised when a destination type has no connection test."""+class UnsupportedHogQLQueryError(Exception):+ """Raised when a HogQL query cannot be used to power a batch export."""+++class FileDownloadNotFoundError(LookupError):+ """Raised when a file download run, or the file a request names, does not exist for the team.++ The message, when there is one, says which file index is out of range.+ """+++class InvalidFileDownloadRequestError(ValueError):+ """Raised when a file download cannot do what was asked, for example download a run that has not finished."""+++class TooManyConcurrentFileDownloadsError(Exception):+ """Raised when a team already has the maximum number of file downloads starting or running."""+++class FileDownloadStartError(Exception):+ """Raised when the workflow of a new file download does not start. The run is saved as failed."""++@dataclass(frozen=True)class BatchExportRef:"""The bare identity of a batch export, for listing it by name."""@@ -148,6 +171,43 @@ class DestinationTest:steps: tuple[DestinationTestStep, ...]+@dataclass(frozen=True)+class FileDownloadRequest:+ """What to export to a downloadable file, as a person asked for it.++ ``include_events`` and ``exclude_events`` apply to the ``events`` model only. ``hogql_query``+ and ``hogql_modifiers`` apply to the ``hogql`` model only, and that model needs only the+ interval bounds its query references.+ """++ model: str+ format: str+ compression: str | None+ max_size_mb: int | None+ data_interval_start: dt.datetime | None+ data_interval_end: dt.datetime | None+ include_events: tuple[str, ...] | None = None+ exclude_events: tuple[str, ...] | None = None+ hogql_query: str | None = None+ hogql_modifiers: dict[str, object] | None = None+++@dataclass(frozen=True)+class FileDownloadRun:+ """A file download run, with the status a person sees.++ ``files`` holds the ids of the downloadable files, in download order. It is None until the+ run completes and its files are ready. A completed run that exported rows reports+ ``Running`` until then, because its files are written after the run completes.+ """++ id: UUID+ status: str+ error: str | None+ files: tuple[UUID, ...] | None+ records_completed: int | None++@stdlib_dataclass(frozen=True)class AWSCredentials:"""An AWS key pair, optionally temporary.diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.pyindex dc66f0fd7aa9..45bdf60c2e09 100644--- a/products/batch_exports/backend/hogql_source.py+++ b/products/batch_exports/backend/hogql_source.py@@ -25,6 +25,8 @@ from posthog.hogql.visitor import CloningVisitorfrom posthog.clickhouse.events_json import UNPARSEABLE_PROPERTIES_KEY+from products.batch_exports.backend.facade.contracts import UnsupportedHogQLQueryError+if typing.TYPE_CHECKING:from posthog.models import Team, User@@ -43,10 +45,6 @@ _SUPPORTED_PLACEHOLDERS = f"{{{DATA_INTERVAL_START_PLACEHOLDER}}} and {{{DATA_INLOGGER = structlog.get_logger(__name__)-class UnsupportedHogQLQueryError(Exception):- """Raised when a HogQL query cannot be used to power a batch export."""--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.diff --git a/products/batch_exports/backend/logic/__init__.py b/products/batch_exports/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/batch_exports/backend/logic/file_downloads.py b/products/batch_exports/backend/logic/file_downloads.pynew file mode 100644index 000000000000..f8c54e85d173--- /dev/null+++ b/products/batch_exports/backend/logic/file_downloads.py@@ -0,0 +1,463 @@+"""File download batch exports: on-demand runs that write their output to files a person downloads.++The facade reaches this module through a call-time import, because it imports ``boto3``, the+service layer and the Temporal client, none of which may load on the ``django.setup()`` path.+"""++import json+import time+import uuid+import datetime as dt+import posixpath+from uuid import UUID++from django.conf import settings+from django.db import connection, transaction+from django.db.models import QuerySet++import boto3+import structlog+from botocore.client import Config+from botocore.exceptions import ClientError++from posthog.hogql.query import execute_hogql_query++from posthog.models import Team, User+from posthog.temporal.common.client import sync_connect++from products.batch_exports.backend.facade import contracts+from products.batch_exports.backend.hogql_source import (+ apply_hogql_batch_export_modifier_defaults,+ load_hogql_modifiers,+ validate_hogql_query_for_batch_export,+)+from products.batch_exports.backend.models.batch_export import (+ BatchExportDestination,+ BatchExportFileDownload,+ BatchExportOnDemand,+ BatchExportRun,+ BatchExportSource,+)+from products.batch_exports.backend.service import (+ BatchExportModel,+ 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()+LOGGER = structlog.get_logger(__name__)+_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY = int.from_bytes(+ # 4 ASCII bytes to fill 32-bit PostgreSQL lock key+ b"FDBE",+ byteorder="big",+)+_FAILED_STATUSES = (+ BatchExportRun.Status.TERMINATED,+ BatchExportRun.Status.TIMEDOUT,+ BatchExportRun.Status.FAILED,+ BatchExportRun.Status.FAILED_RETRYABLE,+ BatchExportRun.Status.FAILED_BILLING,+)+_IN_PROGRESS_STATUSES = (BatchExportRun.Status.RUNNING, BatchExportRun.Status.STARTING)+++def _file_download_runs(team_id: int) -> QuerySet[BatchExportRun]:+ return (+ BatchExportRun.objects.select_related("batch_export_on_demand__destination", "batch_export_on_demand__team")+ .exclude(batch_export_on_demand__deleted=True)+ .filter(+ batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,+ batch_export_on_demand__team_id=team_id,+ )+ .order_by("-created_at", "-id")+ )+++def _get_run(team_id: int, run_id: UUID) -> BatchExportRun:+ try:+ return _file_download_runs(team_id).get(id=run_id)+ except BatchExportRun.DoesNotExist as e:+ raise contracts.FileDownloadNotFoundError() from e+++def _to_file_download_run(batch_export_run: BatchExportRun) -> contracts.FileDownloadRun:+ run_status = batch_export_run.status+ files: tuple[UUID, ...] | None = None++ if run_status == BatchExportRun.Status.COMPLETED:+ if batch_export_run.batch_export_on_demand is None:+ raise RuntimeError("Batch export on demand must be defined on this run")++ ids = tuple(+ BatchExportFileDownload.objects.filter(+ batch_export_run=batch_export_run, team=batch_export_run.batch_export_on_demand.team+ )+ .order_by("key")+ .values_list("id", flat=True)+ )++ has_data = batch_export_run.records_completed is not None and batch_export_run.records_completed > 0+ if not ids and has_data:+ # There is currently a small delay between the run being set to completed+ # and the file downloads being generated, so we account for that and keep+ # showing running status.+ run_status = BatchExportRun.Status.RUNNING+ else:+ files = ids++ return contracts.FileDownloadRun(+ id=batch_export_run.id,+ status=run_status,+ error=batch_export_run.latest_error,+ files=files,+ records_completed=batch_export_run.records_completed,+ )+++def list_file_download_runs(team_id: int, *, offset: int, limit: int) -> tuple[list[BatchExportRun], int]:+ runs = _file_download_runs(team_id)+ return list(runs[offset : offset + limit]), runs.count()+++def get_file_download_run(team_id: int, run_id: UUID) -> contracts.FileDownloadRun:+ return _to_file_download_run(_get_run(team_id, run_id))+++def _build_run(team_id: int, user_id: int, request: contracts.FileDownloadRequest) -> BatchExportRun:+ config: dict[str, object] = {+ "format": request.format,+ "compression": request.compression,+ "max_size_mb": request.max_size_mb,+ }++ source = None+ if request.model == "hogql":+ source = BatchExportSource(+ team_id=team_id,+ hogql_query=request.hogql_query,+ hogql_modifiers=request.hogql_modifiers,+ )++ if request.include_events is not None and request.model == "events":+ config["include_events"] = list(request.include_events)++ if request.exclude_events is not None and request.model == "events":+ config["exclude_events"] = list(request.exclude_events)++ destination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config=config)+ batch_export = BatchExportOnDemand(+ team_id=team_id,+ destination=destination,+ source=source,+ last_modified_by_id=user_id,+ model=request.model,+ )+ batch_export_run = BatchExportRun(+ status=BatchExportRun.Status.STARTING,+ batch_export_on_demand=batch_export,+ data_interval_start=request.data_interval_start,+ data_interval_end=request.data_interval_end,+ )++ destination.save()+ if source is not None:+ source.save()+ batch_export.save()+ batch_export_run.save()++ return batch_export_run+++def start_file_download(team_id: int, user_id: int, request: contracts.FileDownloadRequest) -> UUID:+ with transaction.atomic():+ # Concurrent requests after the first one to obtain a lock will wait here+ # until transaction is done. This prevents creating batch exports over the+ # limit. Note we use our own 32-bit lock key additional to team_id to avoid+ # conflicts with other parts of the application which may have also+ # obtained a lock based on team_id.+ # NOTE: If team_id ever becomes a 64-bit int update this.+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(%s::integer, %s::integer)",+ (_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY, team_id),+ )++ current_count = BatchExportRun.objects.filter(+ status__in=_IN_PROGRESS_STATUSES,+ batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,+ batch_export_on_demand__team_id=team_id,+ batch_export_on_demand__deleted=False,+ ).count()++ if current_count >= settings.BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM:+ raise contracts.TooManyConcurrentFileDownloadsError()++ instance = _build_run(team_id, user_id, request)++ batch_export_on_demand = instance.batch_export_on_demand+ assert batch_export_on_demand is not None+ source = batch_export_on_demand.source+ destination_config = batch_export_on_demand.destination.config+ try:+ start_file_download_batch_export(+ batch_export_on_demand,+ instance.workflow_id,+ batch_export_run_id=instance.id,+ data_interval_start=instance.data_interval_start,+ data_interval_end=instance.data_interval_end,+ batch_export_model=BatchExportModel(+ name=request.model,+ schema=None,+ hogql_query=source.hogql_query if source is not None else None,+ user_id=batch_export_on_demand.last_modified_by_id if request.model == "hogql" else None,+ hogql_modifiers=source.hogql_modifiers if source is not None else None,+ ),+ compression=destination_config.get("compression", None),+ format=destination_config.get("format", "Parquet"),+ max_size_mb=destination_config.get("max_size_mb", 0),+ include_events=destination_config.get("include_events", None),+ exclude_events=destination_config.get("exclude_events", None),+ )+ except Exception as e:+ LOGGER.exception("batch_export_on_demand.fail_to_start")++ instance.latest_error = "Failed to start"+ instance.status = BatchExportRun.Status.FAILED+ instance.save()++ raise contracts.FileDownloadStartError() from e++ return instance.id+++def cancel_file_download(team_id: int, run_id: UUID) -> str:+ batch_export_run = _get_run(team_id, run_id)++ if batch_export_run.status not in _IN_PROGRESS_STATUSES:+ raise contracts.InvalidFileDownloadRequestError(+ 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 batch_export_run.status+++def get_file_download_url(team_id: int, run_id: UUID, part: str | None) -> str:+ batch_export_run = _get_run(team_id, run_id)++ if batch_export_run.status in _IN_PROGRESS_STATUSES:+ raise contracts.InvalidFileDownloadRequestError("Batch export run is still in progress")++ if batch_export_run.status in _FAILED_STATUSES:+ raise contracts.InvalidFileDownloadRequestError("Batch export run has failed")++ if batch_export_run.status == BatchExportRun.Status.CANCELLED:+ raise contracts.InvalidFileDownloadRequestError("Batch export run was cancelled")++ file_download = _get_file_download_for_run(batch_export_run, part)++ default_expiration = dt.timedelta(seconds=settings.BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS)+ expiration = _calculate_expiration_for_file_download(file_download, default_expiration=default_expiration)++ return _generate_s3_pre_signed_url(+ settings.BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET,+ file_download.key,+ role_arn=settings.BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN,+ session_name=f"batch-exports-file-download-{file_download.id}",+ expiration=int(expiration.total_seconds()),+ max_attempts=10 if settings.TEST else 1,+ )+++def count_rows_for_hogql_batch_export(+ team_id: int,+ hogql_query: str,+ timeout: int = 30,+ *,+ user_id: int,+ data_interval_start: dt.datetime | None = None,+ data_interval_end: dt.datetime | None = None,+ hogql_modifiers: dict[str, object] | None = None,+) -> int:+ """Count the rows a HogQL query would produce.++ Raises:+ UnsupportedHogQLQueryError: If the query cannot power a batch export.+ """+ team = Team.objects.get(id=team_id)+ user = User.objects.get(id=user_id)+ modifiers = load_hogql_modifiers(hogql_modifiers)+ validate_hogql_query_for_batch_export(hogql_query, team, user=user, modifiers=modifiers)++ record_batch_model = HogQLQueryRecordBatchModel(team_id=team.pk, hogql_query=hogql_query, user_id=user.pk)+ query_settings = get_user_hogql_batch_export_query_settings()+ query_settings.max_execution_time = timeout++ # `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(data_interval_start, data_interval_end),+ team=team,+ user=user,+ query_type="HogQLBatchExportCountRowsQuery",+ settings=query_settings,+ modifiers=apply_hogql_batch_export_modifier_defaults(team, modifiers),+ )+ return query_response.results[0][0] if query_response.results else 0+++def _generate_s3_pre_signed_url(+ bucket: str,+ key: str,+ role_arn: str,+ session_name: str,+ expiration: int = 3600,+ max_attempts: int = 1,+ delay: int = 1,+):+ """Generate a pre-signed URL for given bucket and key.++ The URL will be signed with temporary credentials after assuming the given role.+ The credentials will be scoped to only support a s3:GetObject action on the given+ bucket, key.++ Temporary credentials and the download URL have individual expiration times,+ meaning that the lower of the two is the one that counts as users need both valid+ credentials and a valid URL to use the download URL. So, we set the same+ `expiration` to both. Keep in mind that temporary credentials may only be assumed+ for up to a limit configured in the role itself.+ """+ if max_attempts <= 0:+ raise ValueError("`max_attempts` must be positive")++ filename = posixpath.basename(key)++ if not filename:+ # Should never happen, our keys always end with a filename+ raise ValueError(f"Cannot derive filename from S3 key: {key!r}")++ sts = SESSION.client("sts")++ for attempt in range(1, max_attempts + 1):+ # It may take a few moments for access to be granted, so we retry in a loop+ # This is only relevant for test environments in which roles are created in the+ # moment. Long-lived roles in production should succeed on the first attempt.+ try:+ response = sts.assume_role(+ RoleArn=role_arn,+ RoleSessionName=session_name,+ DurationSeconds=expiration,+ Policy=json.dumps(+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["s3:GetObject"],+ "Resource": f"arn:aws:s3:::{bucket}/{key}",+ },+ ],+ }+ ),+ )+ except ClientError as e:+ code = e.response["Error"]["Code"]+ if code != "AccessDenied" or attempt == max_attempts:+ raise+ time.sleep(delay * (2 ** (attempt - 1))) # With default delay: 1s, 2s, 4s, 8s, ...+ else:+ break++ assumed_session = boto3.Session(+ aws_access_key_id=response["Credentials"]["AccessKeyId"],+ aws_secret_access_key=response["Credentials"]["SecretAccessKey"],+ aws_session_token=response["Credentials"]["SessionToken"],+ )+ s3 = assumed_session.client("s3", config=Config(signature_version="s3v4"))++ return s3.generate_presigned_url(+ "get_object",+ Params={+ "Bucket": bucket,+ "Key": key,+ "ResponseContentDisposition": f'attachment; filename="{filename}"',+ },+ ExpiresIn=expiration,+ )+++def _get_file_download_for_run(+ batch_export_run: BatchExportRun, file_id_or_index: str | int | None = None+) -> BatchExportFileDownload:+ """Attempt to fetch a file download for a given batch export run.++ Optionally, for multi-file batch exports, filter by file id or index.+ """+ if batch_export_run.batch_export_on_demand is None:+ raise RuntimeError("Batch export on demand must be defined on this run")++ try:+ file_download_id = uuid.UUID(file_id_or_index) # type: ignore[arg-type]++ except (ValueError, TypeError, AttributeError):+ file_downloads_query = BatchExportFileDownload.objects.filter(+ batch_export_run=batch_export_run, team=batch_export_run.batch_export_on_demand.team+ ).order_by("key")+ file_downloads: list[BatchExportFileDownload] = list(file_downloads_query)++ try:+ index = int(file_id_or_index) if file_id_or_index is not None else 0+ except (ValueError, TypeError):+ raise contracts.InvalidFileDownloadRequestError(f"Invalid file id or index: '{file_id_or_index}'")++ if index < 0 or index >= len(file_downloads):+ raise contracts.FileDownloadNotFoundError(f"No files with index {index}")++ file_download = file_downloads[index]++ else:+ try:+ file_download = BatchExportFileDownload.objects.get(+ batch_export_run=batch_export_run,+ id=file_download_id,+ team=batch_export_run.batch_export_on_demand.team,+ )+ except BatchExportFileDownload.DoesNotExist as e:+ raise contracts.FileDownloadNotFoundError() from e++ return file_download+++def _calculate_expiration_for_file_download(+ file_download: BatchExportFileDownload, default_expiration: dt.timedelta+) -> dt.timedelta:+ """Calculate the expiration for a file download.++ The provided `default_expiration` will be used as fallback if the file download+ contains no `expires_at`.+ """++ if file_download.expires_at is not None:+ now = dt.datetime.now(dt.UTC)+ remaining = file_download.expires_at - now++ if remaining < dt.timedelta(seconds=0):+ raise contracts.InvalidFileDownloadRequestError("This file download has expired")++ expiration = min(remaining, default_expiration)+ else:+ expiration = default_expiration++ return expirationdiff --git a/products/batch_exports/backend/presentation/views/file_download.py b/products/batch_exports/backend/presentation/views/file_download.pyindex 6c586838f31d..387ac43143c8 100644--- a/products/batch_exports/backend/presentation/views/file_download.py+++ b/products/batch_exports/backend/presentation/views/file_download.py@@ -1,28 +1,24 @@-import json-import timeimport uuidimport datetime as dt-import posixpath-from typing import Any+from typing import Any, cast-from django.conf import settings-from django.db import connection, models, transaction+from django.db import modelsfrom django.http import HttpResponseRedirect-from django.shortcuts import get_object_or_404--import boto3-import structlog-from botocore.client import Config-from botocore.exceptions import ClientError-from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema-from rest_framework import mixins, response, serializers, status, viewsets++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import (+ OpenApiParameter,+ OpenApiResponse,+ PolymorphicProxySerializer,+ extend_schema,+ extend_schema_view,+)+from rest_framework import response, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, NotAuthenticated, NotFound, ValidationError+from rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.throttling import BaseThrottle-from posthog.schema import HogQLQueryModifiers-from posthog.hogql.errors import ExposedHogQLError-from posthog.hogql.query import execute_hogql_queryfrom posthog.api.log_entries import LogEntryMixinfrom posthog.api.mixins import ValidatedRequest, validated_request@@ -30,46 +26,25 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.errors import ExposedCHQueryErrorfrom posthog.exceptions import ClickHouseQueryTimeOut-from posthog.models import Team, User+from posthog.models import Userfrom posthog.rate_limit import BatchExportsCountRowsBurstRateThrottle, BatchExportsCountRowsSustainedRateThrottle-from posthog.temporal.common.client import sync_connect--from products.batch_exports.backend.hogql_source import (- UnsupportedHogQLQueryError,- apply_hogql_batch_export_modifier_defaults,- find_interval_placeholders,- load_hogql_modifiers,- parse_hogql_select_for_batch_export,- validate_hogql_query_for_batch_export,-)-from products.batch_exports.backend.models.batch_export import (- BatchExportDestination,- BatchExportFileDownload,- BatchExportOnDemand,- BatchExportRun,- BatchExportSource,++from products.batch_exports.backend.facade import (+ api as batch_exports_api,+ contracts,)+from products.batch_exports.backend.facade.enums import BatchExportRunStatusfrom products.batch_exports.backend.presentation.views.utils import (HOGQL_MODIFIERS_HELP_TEXT,HogQLModifiersField,check_hogql_batch_exports_enabled,)-from products.batch_exports.backend.service import (- BatchExportModel,- 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)DEFAULT_MAX_SIZE_MB = 1024-LOGGER = structlog.get_logger(__name__)-_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY = int.from_bytes(- # 4 ASCII bytes to fill 32-bit PostgreSQL lock key- b"FDBE",- byteorder="big",+# The viewset declares no queryset, so drf-spectacular cannot read the type of the id from a model.+RUN_ID_PARAMETER = OpenApiParameter(+ "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this batch export run.")@@ -169,8 +144,8 @@ def validate_file_download_interval() -> None:if hogql_query is not None:try:- placeholders = find_interval_placeholders(parse_hogql_select_for_batch_export(hogql_query))- except UnsupportedHogQLQueryError as e:+ placeholders = batch_exports_api.find_hogql_interval_placeholders(hogql_query)+ except contracts.UnsupportedHogQLQueryError as e:raise ValidationError({"hogql_query": str(e)}) from ebounds = {"data_interval_start": data_interval_start, "data_interval_end": data_interval_end}missing = {@@ -253,41 +228,6 @@ COUNT_ROWS_TIMEOUT_MESSAGE = ()-def count_rows_for_hogql_batch_export(- team: Team,- hogql_query: str,- timeout: int = 30,- *,- user: User,- data_interval_start: dt.datetime | None = None,- data_interval_end: dt.datetime | None = None,- modifiers: HogQLQueryModifiers | None = None,-) -> 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, user=user, modifiers=modifiers)-- record_batch_model = HogQLQueryRecordBatchModel(team_id=team.pk, hogql_query=hogql_query, user_id=user.pk)- query_settings = get_user_hogql_batch_export_query_settings()- query_settings.max_execution_time = timeout-- # `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(data_interval_start, data_interval_end),- team=team,- user=user,- query_type="HogQLBatchExportCountRowsQuery",- settings=query_settings,- modifiers=apply_hogql_batch_export_modifier_defaults(team, modifiers),- )- 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,73 +279,17 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):)try:- validate_hogql_query_for_batch_export(- hogql_query,- team,- user=self.context["request"].user,- modifiers=load_hogql_modifiers(data.get("hogql_modifiers")),+ batch_exports_api.validate_hogql_query(+ team.pk,+ user_id=self.context["request"].user.pk,+ hogql_query=hogql_query,+ hogql_modifiers=data.get("hogql_modifiers"),)- except UnsupportedHogQLQueryError as e:+ except contracts.UnsupportedHogQLQueryError as e:raise ValidationError({"hogql_query": str(e)}) from ereturn data- def create(self, validated_data: dict) -> BatchExportRun:- """Create a `BatchExportRun` based on a `BatchExportOnDemand`.-- This also creates the necessary `BatchExportDestination`.- """- team_id = self.context["team_id"]- config = validated_data.pop("file")- model = validated_data["model"]-- source = None- if model == "hogql":- source = BatchExportSource(- team_id=team_id,- hogql_query=validated_data.pop("hogql_query"),- hogql_modifiers=validated_data.pop("hogql_modifiers", None),- )- 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")-- if (include := validated_data.pop("include", None)) is not None and model == "events":- config["include_events"] = include-- if (exclude := validated_data.pop("exclude", None)) is not None and model == "events":- config["exclude_events"] = exclude-- destination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config=config)- user = self.context["request"].user- if not isinstance(user, User):- raise NotAuthenticated()-- batch_export = BatchExportOnDemand(- team_id=team_id,- destination=destination,- source=source,- last_modified_by=user,- **validated_data,- )- batch_export_run = BatchExportRun(- status=BatchExportRun.Status.STARTING,- batch_export_on_demand=batch_export,- data_interval_start=data_interval_start,- data_interval_end=data_interval_end,- )-- with transaction.atomic():- destination.save()- if source is not None:- source.save()- batch_export.save()- batch_export_run.save()-- return batch_export_run-class CreateOutputSerializer(serializers.Serializer):"""Typed output for view set `create`."""@@ -418,7 +302,7 @@ class ListOutputSerializer(serializers.Serializer):id = serializers.UUIDField(help_text="ID of the file download batch export run.")status = serializers.ChoiceField(- choices=BatchExportRun.Status.choices,+ choices=BatchExportRunStatus.choices,help_text="Current status of the file download batch export run.",)@@ -454,7 +338,7 @@ class RetrieveOutputSerializer(serializers.Serializer):@extend_schema. This serializer exists as a runtime/fallback type."""- status = serializers.ChoiceField(choices=BatchExportRun.Status.choices)+ status = serializers.ChoiceField(choices=BatchExportRunStatus.choices)error = serializers.CharField(required=False)files = serializers.ListField(child=serializers.UUIDField(),@@ -475,27 +359,30 @@ class TooManyConcurrentFileDownloads(APIException):default_detail = "Too many concurrent file download batch exports for this team."+def _to_file_download_request(validated_data: dict[str, Any]) -> contracts.FileDownloadRequest:+ file_config = validated_data["file"]+ include = validated_data.get("include")+ exclude = validated_data.get("exclude")+ return contracts.FileDownloadRequest(+ model=validated_data["model"],+ format=file_config["format"],+ compression=file_config["compression"],+ max_size_mb=file_config["max_size_mb"],+ data_interval_start=validated_data.get("data_interval_start"),+ data_interval_end=validated_data.get("data_interval_end"),+ include_events=tuple(include) if include is not None else None,+ exclude_events=tuple(exclude) if exclude is not None else None,+ hogql_query=validated_data.get("hogql_query"),+ hogql_modifiers=validated_data.get("hogql_modifiers"),+ )++@extend_schema(tags=["batch_exports"])-class FileDownloadBatchExportOnDemandViewSet(- TeamAndOrgViewSetMixin,- LogEntryMixin,- mixins.CreateModelMixin,- mixins.RetrieveModelMixin,- mixins.ListModelMixin,- viewsets.GenericViewSet,-):+@extend_schema_view(logs=extend_schema(parameters=[RUN_ID_PARAMETER]))+class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.GenericViewSet):scope_object = "batch_export"- queryset = (- BatchExportRun.objects.select_related("batch_export_on_demand__destination", "batch_export_on_demand__team")- .exclude(batch_export_on_demand__deleted=True)- .filter(batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD)- .order_by("-created_at")- .all()- )serializer_class = FileDownloadBatchExportOnDemandSerializerlog_source = "batch_exports"- # Not linked directly with a team, we need to go through batch export- filter_rewrite_rules = {"team_id": "batch_export_on_demand__team_id"}def get_serializer_class(self) -> type[serializers.Serializer]:if self.action == "list":@@ -510,6 +397,34 @@ class FileDownloadBatchExportOnDemandViewSet(return [BatchExportsCountRowsBurstRateThrottle(), BatchExportsCountRowsSustainedRateThrottle()]return super().get_throttles()+ def dangerously_get_object(self) -> contracts.FileDownloadRun:+ # This replaces the queryset read only. The facade scopes the read to the team, and the+ # object permissions run on the contract as they ran on the model. `logs` reads the run here.+ try:+ run_id = uuid.UUID(str(self.kwargs["pk"]))+ except ValueError:+ raise NotFound()+ try:+ run = batch_exports_api.get_file_download_run(self.team_id, run_id)+ except contracts.FileDownloadNotFoundError as e:+ raise NotFound(*e.args) from e+ self.check_object_permissions(self.request, run)+ return run++ def list(self, request, *args, **kwargs) -> response.Response:+ # The facade slices the page, so the paginator gets its state set directly instead of a queryset.+ paginator = cast(LimitOffsetPagination, self.paginator)+ limit = paginator.get_limit(request)+ offset = paginator.get_offset(request)+ # PAGE_SIZE gives every request a limit.+ assert limit is not None+ runs, count = batch_exports_api.list_file_download_runs(self.team_id, offset=offset, limit=limit)+ paginator.request = request+ paginator.limit = limit+ paginator.offset = offset+ paginator.count = count+ return paginator.get_paginated_response(ListOutputSerializer(runs, many=True).data)+@extend_schema(request=PolymorphicProxySerializer(component_name="CreateFileDownloadRequest",@@ -528,61 +443,18 @@ class FileDownloadBatchExportOnDemandViewSet(serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)- with transaction.atomic():- # Concurrent requests after the first one to obtain a lock will wait here- # until transaction is done. This prevents creating batch exports over the- # limit. Note we use our own 32-bit lock key additional to team_id to avoid- # conflicts with other parts of the application which may have also- # obtained a lock based on team_id.- # NOTE: If team_id ever becomes a 64-bit int update this.- with connection.cursor() as cursor:- cursor.execute(- "SELECT pg_advisory_xact_lock(%s::integer, %s::integer)",- (_FILE_DOWNLOAD_BATCH_EXPORTS_LOCK_KEY, self.team_id),- )-- current_count = BatchExportRun.objects.filter(- status__in=(BatchExportRun.Status.STARTING, BatchExportRun.Status.RUNNING),- batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,- batch_export_on_demand__team_id=self.team_id,- batch_export_on_demand__deleted=False,- ).count()-- if current_count >= settings.BATCH_EXPORT_MAX_CONCURRENT_ON_DEMAND_PER_TEAM:- raise TooManyConcurrentFileDownloads()-- instance = serializer.save()-- source = instance.batch_export_on_demand.source+ if not isinstance(request.user, User):+ raise NotAuthenticated()+try:- start_file_download_batch_export(- instance.batch_export_on_demand,- instance.workflow_id,- batch_export_run_id=instance.id,- data_interval_start=instance.data_interval_start,- data_interval_end=instance.data_interval_end,- batch_export_model=BatchExportModel(- name=instance.batch_export_on_demand.model,- schema=None,- hogql_query=source.hogql_query if source is not None else None,- user_id=instance.batch_export_on_demand.last_modified_by_id- if instance.batch_export_on_demand.model == "hogql"- else None,- hogql_modifiers=source.hogql_modifiers if source is not None else None,- ),- compression=instance.batch_export_on_demand.destination.config.get("compression", None),- format=instance.batch_export_on_demand.destination.config.get("format", "Parquet"),- max_size_mb=instance.batch_export_on_demand.destination.config.get("max_size_mb", 0),- include_events=instance.batch_export_on_demand.destination.config.get("include_events", None),- exclude_events=instance.batch_export_on_demand.destination.config.get("exclude_events", None),+ run_id = batch_exports_api.start_file_download(+ self.team_id,+ user_id=request.user.pk,+ request=_to_file_download_request(serializer.validated_data),)- except Exception:- LOGGER.exception("batch_export_on_demand.fail_to_start")-- instance.latest_error = "Failed to start"- instance.status = BatchExportRun.Status.FAILED- instance.save()-+ except contracts.TooManyConcurrentFileDownloadsError as e:+ raise TooManyConcurrentFileDownloads() from e+ except contracts.FileDownloadStartError:return response.Response({"detail": "The batch export failed to start. Check our status page for any ongoing incidents and try again later."@@ -590,9 +462,10 @@ class FileDownloadBatchExportOnDemandViewSet(status=status.HTTP_500_INTERNAL_SERVER_ERROR,)- return response.Response({"id": instance.id}, status=status.HTTP_202_ACCEPTED)+ return response.Response({"id": run_id}, status=status.HTTP_202_ACCEPTED)@extend_schema(+ parameters=[RUN_ID_PARAMETER],responses={200: PolymorphicProxySerializer(component_name="RetrieveFileDownloadResponse",@@ -618,40 +491,18 @@ class FileDownloadBatchExportOnDemandViewSet(generated file downloads so that users may download them by making a requestto /download."""- batch_export_run: BatchExportRun = self.get_object()-- error = {}- if batch_export_run.latest_error is not None:- error["error"] = batch_export_run.latest_error-- run_status = batch_export_run.status-- completed: dict[str, list[str] | int | None] = {}- if run_status == BatchExportRun.Status.COMPLETED:- if batch_export_run.batch_export_on_demand is None:- raise RuntimeError("Batch export on demand must be defined on this run")-- ids = [- str(id)- for id in BatchExportFileDownload.objects.filter(- batch_export_run=batch_export_run, team=batch_export_run.batch_export_on_demand.team- )- .order_by("key")- .values_list("id", flat=True)- ]-- has_data = batch_export_run.records_completed is not None and batch_export_run.records_completed > 0- if not ids and has_data:- # There is currently a small delay between the run being set to completed- # and the file downloads being generated, so we account for that and keep- # showing running status.- run_status = BatchExportRun.Status.RUNNING- else:- completed["files"] = ids- completed["records_completed"] = batch_export_run.records_completed-- return response.Response({"status": run_status, **completed, **error})+ run = self.get_object()++ body: dict[str, Any] = {"status": run.status}+ if run.files is not None:+ body["files"] = [str(file_id) for file_id in run.files]+ body["records_completed"] = run.records_completed+ if run.error is not None:+ body["error"] = run.error+ return response.Response(body)++ @extend_schema(parameters=[RUN_ID_PARAMETER])@action(methods=["GET"], detail=True, url_path=r"download(?:/(?P<part>[^/.]+))?", required_scopes=["batch_export:read"])@@ -666,62 +517,34 @@ class FileDownloadBatchExportOnDemandViewSet(* If no part component is present: If there is only one file downloaded, thatis downloaded. Otherwise the first one as sorted by key is downloaded."""- batch_export_run: BatchExportRun = self.get_object()-- if batch_export_run.status in (BatchExportRun.Status.RUNNING, BatchExportRun.Status.STARTING):- raise ValidationError("Batch export run is still in progress")-- if batch_export_run.status in (- BatchExportRun.Status.TERMINATED,- BatchExportRun.Status.TIMEDOUT,- BatchExportRun.Status.FAILED,- BatchExportRun.Status.FAILED_RETRYABLE,- BatchExportRun.Status.FAILED_BILLING,- ):- raise ValidationError("Batch export run has failed")-- if batch_export_run.status == BatchExportRun.Status.CANCELLED:- raise ValidationError("Batch export run was cancelled")-- file_download = _get_file_download_for_run(batch_export_run, part)-- default_expiration = dt.timedelta(seconds=settings.BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS)- expiration = _calculate_expiration_for_file_download(file_download, default_expiration=default_expiration)-- pre_signed_url = _generate_s3_pre_signed_url(- settings.BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET,- file_download.key,- role_arn=settings.BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN,- session_name=f"batch-exports-file-download-{file_download.id}",- expiration=int(expiration.total_seconds()),- max_attempts=10 if settings.TEST else 1,- )+ run = self.get_object()++ try:+ pre_signed_url = batch_exports_api.get_file_download_url(self.team_id, run.id, part)+ except contracts.InvalidFileDownloadRequestError as e:+ raise ValidationError(str(e)) from e+ except contracts.FileDownloadNotFoundError as e:+ raise NotFound(*e.args) from eresponse = HttpResponseRedirect(redirect_to=pre_signed_url)response["Cache-Control"] = "no-store"return response- @extend_schema(request=None)+ @extend_schema(request=None, parameters=[RUN_ID_PARAMETER])@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")+ run = self.get_object()- 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)+ run_status = batch_exports_api.cancel_file_download(self.team_id, run.id)+ except contracts.InvalidFileDownloadRequestError as e:+ raise ValidationError(str(e)) from e+ except contracts.FileDownloadNotFoundError as e:+ raise NotFound(*e.args) from e- batch_export_run.refresh_from_db()-- return response.Response({"status": batch_export_run.status})+ return response.Response({"status": run_status})@action(methods=["POST"],@@ -751,15 +574,15 @@ class FileDownloadBatchExportOnDemandViewSet(check_hogql_batch_exports_enabled(self.team)try:- count = count_rows_for_hogql_batch_export(- self.team,- request.validated_data["hogql_query"],- user=request.user,+ count = batch_exports_api.count_hogql_rows(+ self.team_id,+ user_id=request.user.pk,+ hogql_query=request.validated_data["hogql_query"],+ hogql_modifiers=request.validated_data.get("hogql_modifiers"),data_interval_start=request.validated_data.get("data_interval_start"),data_interval_end=request.validated_data.get("data_interval_end"),- modifiers=load_hogql_modifiers(request.validated_data.get("hogql_modifiers")),)- except UnsupportedHogQLQueryError as e:+ except contracts.UnsupportedHogQLQueryError as e:raise ValidationError({"hogql_query": str(e)}) from eexcept (ExposedHogQLError, ExposedCHQueryError) as e:raise ValidationError(str(e), getattr(e, "code_name", None)) from e@@ -769,147 +592,3 @@ class FileDownloadBatchExportOnDemandViewSet(raise ValidationError(COUNT_ROWS_TIMEOUT_MESSAGE, "timeout_exceeded") from ereturn response.Response({"count": count})---def _generate_s3_pre_signed_url(- bucket: str,- key: str,- role_arn: str,- session_name: str,- expiration: int = 3600,- max_attempts: int = 1,- delay: int = 1,-):- """Generate a pre-signed URL for given bucket and key.-- The URL will be signed with temporary credentials after assuming the given role.- The credentials will be scoped to only support a s3:GetObject action on the given- bucket, key.-- Temporary credentials and the download URL have individual expiration times,- meaning that the lower of the two is the one that counts as users need both valid- credentials and a valid URL to use the download URL. So, we set the same- `expiration` to both. Keep in mind that temporary credentials may only be assumed- for up to a limit configured in the role itself.- """- if max_attempts <= 0:- raise ValueError("`max_attempts` must be positive")-- filename = posixpath.basename(key)-- if not filename:- # Should never happen, our keys always end with a filename- raise ValueError(f"Cannot derive filename from S3 key: {key!r}")-- sts = SESSION.client("sts")-- for attempt in range(1, max_attempts + 1):- # It may take a few moments for access to be granted, so we retry in a loop- # This is only relevant for test environments in which roles are created in the- # moment. Long-lived roles in production should succeed on the first attempt.- try:- response = sts.assume_role(- RoleArn=role_arn,- RoleSessionName=session_name,- DurationSeconds=expiration,- Policy=json.dumps(- {- "Version": "2012-10-17",- "Statement": [- {- "Effect": "Allow",- "Action": ["s3:GetObject"],- "Resource": f"arn:aws:s3:::{bucket}/{key}",- },- ],- }- ),- )- except ClientError as e:- code = e.response["Error"]["Code"]- if code != "AccessDenied" or attempt == max_attempts:- raise- time.sleep(delay * (2 ** (attempt - 1))) # With default delay: 1s, 2s, 4s, 8s, ...- else:- break-- assumed_session = boto3.Session(- aws_access_key_id=response["Credentials"]["AccessKeyId"],- aws_secret_access_key=response["Credentials"]["SecretAccessKey"],- aws_session_token=response["Credentials"]["SessionToken"],- )- s3 = assumed_session.client("s3", config=Config(signature_version="s3v4"))-- return s3.generate_presigned_url(- "get_object",- Params={- "Bucket": bucket,- "Key": key,- "ResponseContentDisposition": f'attachment; filename="{filename}"',- },- ExpiresIn=expiration,- )---def _get_file_download_for_run(- batch_export_run: BatchExportRun, file_id_or_index: str | int | None = None-) -> BatchExportFileDownload:- """Attempt to fetch a file download for a given batch export run.-- Optionally, for multi-file batch exports, filter by file id or index.- """- if batch_export_run.batch_export_on_demand is None:- raise RuntimeError("Batch export on demand must be defined on this run")-- try:- file_download_id = uuid.UUID(file_id_or_index) # type: ignore[arg-type]-- except (ValueError, TypeError, AttributeError):- file_downloads_query = BatchExportFileDownload.objects.filter(- batch_export_run=batch_export_run, team=batch_export_run.batch_export_on_demand.team- ).order_by("key")- file_downloads: list[BatchExportFileDownload] = list(file_downloads_query)-- try:- index = int(file_id_or_index) if file_id_or_index is not None else 0- except (ValueError, TypeError):- raise ValidationError(f"Invalid file id or index: '{file_id_or_index}'")-- if index < 0 or index >= len(file_downloads):- raise NotFound(f"No files with index {index}")-- file_download = file_downloads[index]-- else:- file_download = get_object_or_404(- BatchExportFileDownload.objects.filter(- batch_export_run=batch_export_run,- id=file_download_id,- team=batch_export_run.batch_export_on_demand.team,- )- )-- return file_download---def _calculate_expiration_for_file_download(- file_download: BatchExportFileDownload, default_expiration: dt.timedelta-) -> dt.timedelta:- """Calculate the expiration for a file download.-- The provided `default_expiration` will be used as fallback if the file download- contains no `expires_at`.- """-- if file_download.expires_at is not None:- now = dt.datetime.now(dt.UTC)- remaining = file_download.expires_at - now-- if remaining < dt.timedelta(seconds=0):- raise ValidationError("This file download has expired")-- expiration = min(remaining, default_expiration)- else:- expiration = default_expiration-- return expirationdiff --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 f890369d8ec2..bb2a9a1d4097 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@@ -27,6 +27,11 @@ from posthog.models.scoping import team_scopefrom posthog.temporal.tests.utils.events import generate_test_eventsfrom products.access_control.backend.models.property_access_control import PropertyAccessControl+from products.batch_exports.backend.logic.file_downloads import (+ _calculate_expiration_for_file_download,+ _generate_s3_pre_signed_url,+ _get_file_download_for_run,+)from products.batch_exports.backend.models.batch_export import (BatchExportDestination,BatchExportFileDownload,@@ -37,9 +42,6 @@ from products.batch_exports.backend.models.batch_export import (from products.batch_exports.backend.presentation.views.file_download import (COUNT_ROWS_TIMEOUT_MESSAGE,DEFAULT_MAX_SIZE_MB,- _calculate_expiration_for_file_download,- _generate_s3_pre_signed_url,- _get_file_download_for_run,)from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.batch_exports.backend.tests.temporal.destinations.s3.utils import has_valid_credentials@@ -165,7 +167,7 @@ def override_file_download_settings(aws_role_arn, s3_bucket):def mock_start_file_download_export():"""Mock starting the Temporal workflow so create tests don't reach Temporal."""with unittest.mock.patch(- "products.batch_exports.backend.presentation.views.file_download.start_file_download_batch_export"+ "products.batch_exports.backend.logic.file_downloads.start_file_download_batch_export") as mock_start:yield mock_start@@ -304,6 +306,66 @@ async def test_file_download_download_fails_when_not_completed(assert b"still in progress" in response.content+ "part,expected_status,expected_detail",+ [+ ("0", status.HTTP_302_FOUND, None),+ ("1", status.HTTP_400_BAD_REQUEST, "This file download has expired"),+ ("2", status.HTTP_404_NOT_FOUND, "No files with index 2"),+ ("abc", status.HTTP_400_BAD_REQUEST, "Invalid file id or index: 'abc'"),+ ("00000000-0000-4000-8000-000000000000", status.HTTP_404_NOT_FOUND, "Not found."),+ ],+ ids=["live-file", "expired-file", "index-out-of-range", "invalid-part", "unknown-file-id"],+)[email protected]_db(transaction=True)+async def test_file_download_download_resolves_part(+ async_client: AsyncClient,+ team,+ user,+ data_interval_start,+ data_interval_end,+ part: str,+ expected_status: int,+ expected_detail: str | None,+):+ 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.COMPLETED,+ )+ await BatchExportFileDownload.objects.acreate(team=team, batch_export_run=run, key="batch-exports/0")+ await BatchExportFileDownload.objects.acreate(+ team=team,+ batch_export_run=run,+ key="batch-exports/1",+ expires_at=dt.datetime.now(dt.UTC) - dt.timedelta(days=1),+ )++ await async_client.aforce_login(user)++ with unittest.mock.patch(+ "products.batch_exports.backend.logic.file_downloads._generate_s3_pre_signed_url",+ return_value="https://example.com/download",+ ) as pre_sign:+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download/{part}",+ )++ assert response.status_code == expected_status+ if expected_detail is None:+ assert response["Location"] == "https://example.com/download"+ assert response["Cache-Control"] == "no-store"+ assert pre_sign.call_args.args[1] == "batch-exports/0"+ else:+ assert response.json()["detail"] == expected_detail++@requires_aws_credentials@pytest.mark.usefixtures("override_file_download_settings")@pytest.mark.django_db(transaction=True)@@ -487,22 +549,45 @@ async def test_file_download_list_returns_run_ids_and_statuses(status=BatchExportRun.Status.COMPLETED,)+ cancelled_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.CANCELLED,+ )+running_run.created_at = dt.datetime(2026, 1, 1, 1, 1, 0, tzinfo=dt.UTC)await running_run.asave(update_fields=["created_at"])completed_run.created_at = dt.datetime(2026, 1, 1, 1, 1, 1, tzinfo=dt.UTC)await completed_run.asave(update_fields=["created_at"])+ cancelled_run.created_at = completed_run.created_at+ await cancelled_run.asave(update_fields=["created_at"])await async_client.aforce_login(user)+ tied_runs = sorted([completed_run, cancelled_run], key=lambda run: run.id, reverse=True)+ expected = [{"id": str(run.id), "status": run.status} for run in [*tied_runs, running_run]]+response = await async_client.get(f"/api/projects/{team.pk}/file_download_batch_exports")assert response.status_code == status.HTTP_200_OK, response.json()data = response.json()- assert data["count"] == 2- assert data["results"] == [- {"id": str(completed_run.id), "status": BatchExportRun.Status.COMPLETED},- {"id": str(running_run.id), "status": BatchExportRun.Status.RUNNING},- ]+ assert data["count"] == 3+ assert data["results"] == expected++ pages = []+ for offset in range(3):+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports?limit=1&offset={offset}"+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ data = response.json()+ assert data["count"] == 3+ pages.extend(data["results"])++ assert data["next"] is None+ assert data["previous"] is not None+ assert pages == expected@requires_aws_credentials@@ -606,9 +691,7 @@ async def test_file_download_cancel_mocked(mocked_handle = unittest.mock.AsyncMock()mocked_client.get_workflow_handle.return_value = mocked_handle- with unittest.mock.patch(- "products.batch_exports.backend.presentation.views.file_download.sync_connect"- ) as mocked_connect:+ with unittest.mock.patch("products.batch_exports.backend.logic.file_downloads.sync_connect") as mocked_connect:mocked_connect.return_value = mocked_clientstatus_response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/cancel",@@ -1177,9 +1260,7 @@ class TestFileDownloadHogQL:):await async_client.aforce_login(user)- with unittest.mock.patch(- "products.batch_exports.backend.presentation.views.file_download.execute_hogql_query"- ) as execute:+ with unittest.mock.patch("products.batch_exports.backend.logic.file_downloads.execute_hogql_query") as execute:response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports/count_rows",body,@@ -1211,7 +1292,7 @@ class TestFileDownloadHogQL:await async_client.aforce_login(user)with unittest.mock.patch(- "products.batch_exports.backend.presentation.views.file_download.execute_hogql_query",+ "products.batch_exports.backend.logic.file_downloads.execute_hogql_query",side_effect=ClickHouseQueryTimeOut(),):response = await async_client.post(diff --git a/pyproject.toml b/pyproject.tomlindex b28a822c0d29..52f3f3d7882e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -734,11 +734,6 @@ ignore_imports = ["products.batch_exports.backend.presentation.views.batch_export.exports -> products.batch_exports.backend.temporal.sql.events","products.batch_exports.backend.presentation.views.batch_export.runs -> products.batch_exports.backend.models.batch_export","products.batch_exports.backend.presentation.views.batch_export.runs -> products.batch_exports.backend.service",- "products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.hogql_source",- "products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.models.batch_export",- "products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.service",- "products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.temporal.record_batch_model",- "products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.temporal.sql.common",]# routes.py is the one module core reads to assemble a product's API router, so it is the