:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: File download batch export API (#58110)
Tomás Farías Santana011cf51a9ad3
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 8386702af0ef..034ae42aca0c 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -22,6 +22,7 @@ from posthog.api.sdk_doctor import SdkDoctorViewSetfrom posthog.api.wizard import http as wizardfrom posthog.approvals import api as approval_apifrom posthog.batch_exports import http as batch_exports+from posthog.batch_exports.api import file_downloadfrom posthog.settings import CLOUD_DEPLOYMENT, DEBUG, EE_AVAILABLE, TESTimport products.logs.backend.api as logs@@ -490,12 +491,21 @@ environment_batch_exports_router, legacy_project_batch_exports_router = (r"batch_exports", batch_exports.BatchExportViewSet, "environment_batch_exports", ["team_id"]))++register_grandfathered_environment_nested_viewset(+ r"file_download_batch_exports",+ file_download.FileDownloadBatchExportOnDemandViewSet,+ "environment_file_download_batch_exports",+ ["team_id"],+)+environment_batch_exports_router.register(r"runs", batch_exports.BatchExportRunViewSet, "environment_batch_export_runs", ["team_id", "batch_export_id"])legacy_project_batch_exports_router.register(r"runs", batch_exports.BatchExportRunViewSet, "project_batch_export_runs", ["team_id", "batch_export_id"])+environment_batch_exports_router.register(r"backfills",batch_exports.BatchExportBackfillViewSet,diff --git a/posthog/batch_exports/api/file_download.py b/posthog/batch_exports/api/file_download.pynew file mode 100644index 000000000000..1e63a2ef8917--- /dev/null+++ b/posthog/batch_exports/api/file_download.py@@ -0,0 +1,492 @@+import json+import time+import uuid+import datetime as dt+import posixpath++from django.conf import settings+from django.db import transaction+from 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 PolymorphicProxySerializer, extend_schema+from rest_framework import mixins, response, serializers, status, viewsets+from rest_framework.exceptions import NotFound, ValidationError++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 products.batch_exports.backend.service import start_file_download_batch_export++SESSION = boto3.Session()+FILE_DOWNLOAD_MAX_RANGE = dt.timedelta(weeks=1)+LOGGER = structlog.get_logger(__name__)+++class FileDownloadDestinationFileConfigSerializer(serializers.Serializer):+ """Typed configuration for a FileDownload batch-export destination."""++ format = serializers.ChoiceField(choices=["Parquet", "JSONLines"], default="Parquet", help_text="File format")+ compression = serializers.ChoiceField(+ choices=["zstd", "gzip", "brotli", "lz4", "snappy"],+ required=False,+ default=None,+ allow_null=True,+ help_text="Compress the file with a supported compression format",+ )+ max_size_mb = serializers.IntegerField(+ required=False,+ default=None,+ allow_null=True,+ min_value=0,+ help_text="Split download into multiple files of at most this size in MB",+ )+++class FileDownloadEventsRequestSerializer(serializers.Serializer):+ """Typed configuration for the events model."""++ file = FileDownloadDestinationFileConfigSerializer()+ model = serializers.ChoiceField(choices=["events"])+ include = serializers.ListField(child=serializers.CharField(), required=False)+ exclude = serializers.ListField(child=serializers.CharField(), required=False)+ data_interval_start = serializers.DateTimeField(default_timezone=dt.UTC)+ data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)+++class FileDownloadPersonsRequestSerializer(serializers.Serializer):+ """Typed configuration for the persons model."""++ file = FileDownloadDestinationFileConfigSerializer()+ model = serializers.ChoiceField(choices=["persons"])+ data_interval_start = serializers.DateTimeField(default_timezone=dt.UTC)+ data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)+++class FileDownloadSessionsRequestSerializer(serializers.Serializer):+ """Typed configuration for the sessions model."""++ file = FileDownloadDestinationFileConfigSerializer()+ model = serializers.ChoiceField(choices=["sessions"])+ data_interval_start = serializers.DateTimeField(default_timezone=dt.UTC)+ data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)+++class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):+ """Request shape for a FileDownload batch export on demand."""++ file = FileDownloadDestinationFileConfigSerializer()+ model = serializers.ChoiceField(choices=["events", "persons", "sessions"])++ # Only specific to events+ include = serializers.ListField(child=serializers.CharField(), required=False)+ exclude = serializers.ListField(child=serializers.CharField(), required=False)++ # Run attributes+ data_interval_start = serializers.DateTimeField(default_timezone=dt.UTC)+ data_interval_end = serializers.DateTimeField(default_timezone=dt.UTC)++ def validate(self, data):+ if data["data_interval_start"] > data["data_interval_end"]:+ raise ValidationError("'data_interval_end' must occur after 'data_interval_start'")++ if data["data_interval_end"] - data["data_interval_start"] > FILE_DOWNLOAD_MAX_RANGE:+ raise ValidationError("data interval range too big")++ return 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")++ data_interval_start = validated_data.pop("data_interval_start")+ data_interval_end = validated_data.pop("data_interval_end")++ model = validated_data["model"]+ 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)+ batch_export = BatchExportOnDemand(team_id=team_id, destination=destination, **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()+ batch_export.save()+ batch_export_run.save()++ return batch_export_run+++class CreateOutputSerializer(serializers.Serializer):+ """Typed output for view set `create`."""++ id = serializers.UUIDField()+++class RetrieveBasicOutputSerializer(serializers.Serializer):+ """Typed output for view set `retrieve` with any of the statuses without extra output."""++ status = serializers.ChoiceField(choices=["Starting", "Running", "Cancelled"])+++class RetrieveCompletedOutputSerializer(serializers.Serializer):+ """Typed output for view set `retrieve` with completed status."""++ status = serializers.ChoiceField(choices=["Completed"])+ files = serializers.ListField(child=serializers.UUIDField())+++class RetrieveFailedOutputSerializer(serializers.Serializer):+ """Typed output for view set `retrieve` with any of the failed statuses."""++ status = serializers.ChoiceField(choices=["Failed", "FailedRetryable", "FailedBilling", "Terminated", "TimedOut"])+ error = serializers.CharField()+++class RetrieveOutputSerializer(serializers.Serializer):+ """Retrieve serializer with all fields optional except status.++ The actual conditional shape is described by the polymorphic schema in+ @extend_schema. This serializer exists as a runtime/fallback type.+ """++ status = serializers.ChoiceField(choices=BatchExportRun.Status.choices)+ error = serializers.CharField(required=False)+ files = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ )+++@extend_schema(tags=["batch_exports"])+class FileDownloadBatchExportOnDemandViewSet(+ TeamAndOrgViewSetMixin, LogEntryMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, 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 = FileDownloadBatchExportOnDemandSerializer+ log_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"}++ @extend_schema(+ request=PolymorphicProxySerializer(+ component_name="CreateFileDownloadRequest",+ serializers={+ "events": FileDownloadEventsRequestSerializer,+ "persons": FileDownloadPersonsRequestSerializer,+ "sessions": FileDownloadSessionsRequestSerializer,+ },+ resource_type_field_name="model",+ ),+ responses={202: CreateOutputSerializer},+ )+ def create(self, request, *args, **kwargs):+ """Create and start a batch export on demand run to download a file."""+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ instance = serializer.save()++ 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,+ 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),+ )+ except Exception:+ LOGGER.exception("batch_export_on_demand.fail_to_start")++ instance.latest_error = "Failed to start"+ instance.status = BatchExportRun.Status.FAILED+ instance.save()++ return response.Response(+ {+ "detail": "The batch export failed to start. Check our status page for any ongoing incidents and try again later."+ },+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )++ return response.Response({"id": instance.id}, status=status.HTTP_202_ACCEPTED)++ @extend_schema(+ responses={+ 200: PolymorphicProxySerializer(+ component_name="RetrieveFileDownloadResponse",+ serializers={+ "Starting": RetrieveBasicOutputSerializer,+ "Running": RetrieveBasicOutputSerializer,+ "Cancelled": RetrieveBasicOutputSerializer,+ "Completed": RetrieveCompletedOutputSerializer,+ "Failed": RetrieveFailedOutputSerializer,+ "FailedRetryable": RetrieveFailedOutputSerializer,+ "FailedBilling": RetrieveFailedOutputSerializer,+ "TimedOut": RetrieveFailedOutputSerializer,+ "Terminated": RetrieveFailedOutputSerializer,+ },+ resource_type_field_name="status",+ )+ },+ )+ def retrieve(self, *args, **kwargs) -> response.Response:+ """Get a run of a batch export on demand.++ If the underlying batch export run has completed, we return keys to the+ generated file downloads so that users may download them by making a request+ to /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++ files = {}+ 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)+ ]++ if not ids:+ # 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["files"] = ids++ return response.Response({"status": run_status, **files, **error})++ @action(+ methods=["GET"], detail=True, url_path=r"download(?:/(?P<part>[^/.]+))?", required_scopes=["batch_export:read"]+ )+ def download(self, request, part=None, *args, **kwargs) -> HttpResponseRedirect:+ """Download a file (or a part) from this batch export run.++ Users can provide a part component with an id or index, or no part component at+ all:+ * If part id is included: The file download matching the id is downloaded.+ * If part index is included: The file download matching the index (as ordered+ by key) is downloaded.+ * If no part component is present: If there is only one file downloaded, that+ is 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,+ )++ response = HttpResponseRedirect(redirect_to=pre_signed_url)+ response["Cache-Control"] = "no-store"++ return response+++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/posthog/batch_exports/http.py b/posthog/batch_exports/http.pyindex 9b2fa7d4e23d..fa5610536fd9 100644--- a/posthog/batch_exports/http.py+++ b/posthog/batch_exports/http.py@@ -158,7 +158,7 @@ class RunsCursorPagination(CursorPagination):@extend_schema(tags=["batch_exports"])class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ReadOnlyModelViewSet):scope_object = "batch_export"- queryset = BatchExportRun.objects.all()+ queryset = BatchExportRun.objects.select_related("batch_export__destination").all()serializer_class = BatchExportRunSerializerpagination_class = RunsCursorPaginationfilter_rewrite_rules = {"team_id": "batch_export__team_id"}@@ -1131,6 +1131,7 @@ class BatchExportSerializer(serializers.ModelSerializer):destination = BatchExportDestination(**destination_data)batch_export = BatchExport(team_id=team_id, destination=destination, **validated_data)+sync_batch_export(batch_export, created=True)with transaction.atomic():diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.pyindex b8398a9437a5..a6c06896b59c 100644--- a/posthog/settings/batch_exports.py+++ b/posthog/settings/batch_exports.py@@ -101,3 +101,7 @@ BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM: int = get_from_env(BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN", "role")BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET", "bucket")BATCH_EXPORTS_FILE_DOWNLOAD_REGION: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOAD_REGION", "us-east-1")+# Keep this expiration below the role's MaxSessionDuration+BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS: int = get_from_env(+ "BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS", 3600, type_cast=int+)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex d6ce3d6ea833..12a3ecf682f2 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -499,6 +499,7 @@ SPECTACULAR_SETTINGS = {"workflow_variable",],"AssigneeTypeEnum": ["user", "role"],+ "FileFormatEnum": ["Parquet", "JSONLines"],"ErrorTrackingIssueOrderByEnum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],"OrderByEnum": ["latest", "earliest"],"PropertyGroupTypeEnum": ["cohort", "person", "group"],diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex c81d41812db8..228cf945ca96 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -22,12 +22,19 @@ from temporalio.client import (ScheduleRange,ScheduleSpec,ScheduleState,+ WorkflowHandle,)from posthog.hogql.database.database import Databasefrom posthog.hogql.hogql import HogQLContext-from posthog.batch_exports.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun+from posthog.batch_exports.models import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportOnDemand,+ BatchExportRun,+)from posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.schedule import (a_pause_schedule,@@ -818,6 +825,46 @@ async def start_backfill_batch_export_workflow(return workflow_id+@async_to_sync+async def start_batch_export_workflow(+ temporal: Client, name: str, workflow_id: str, inputs: BaseBatchExportInputs+) -> WorkflowHandle:+ """Async call to start a batch export workflow."""+ handle = await temporal.start_workflow(+ name,+ inputs,+ id=workflow_id,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ )++ return handle+++def start_file_download_batch_export(+ batch_export: BatchExportOnDemand,+ workflow_id: str,+ data_interval_start: dt.datetime,+ data_interval_end: dt.datetime,+ batch_export_run_id: UUID | None = None,+ compression: str | None = None,+ format: str = "Parquet",+ max_size_mb: int = 0,+) -> None:+ inputs = FileDownloadBatchExportInputs(+ batch_export_id=batch_export.id,+ batch_export_run_id=batch_export_run_id,+ team_id=batch_export.team_id,+ data_interval_start=data_interval_start.isoformat(),+ data_interval_end=data_interval_end.isoformat(),+ compression=compression,+ file_format=format,+ max_file_size_mb=max_size_mb,+ )+ temporal = sync_connect()++ start_batch_export_workflow(temporal, "file-download-export", workflow_id, inputs)++def create_batch_export_run(batch_export_id: UUID,data_interval_start: str | None,@@ -1193,6 +1240,7 @@ class BatchExportInsertInputs:batch_export_id: str | None = Nonedestination_default_fields: list[BatchExportField] | None = Nonestage_folder: str | None = None+ on_demand: bool = Falsedef get_is_backfill(self) -> bool:"""Needed for backwards compatibility with existing batch exports.diff --git a/products/batch_exports/backend/temporal/__init__.py b/products/batch_exports/backend/temporal/__init__.pyindex fd6b342a735c..4dae968c56e6 100644--- a/products/batch_exports/backend/temporal/__init__.py+++ b/products/batch_exports/backend/temporal/__init__.py@@ -18,6 +18,11 @@ from products.batch_exports.backend.temporal.destinations.databricks_batch_exporDatabricksBatchExportWorkflow,insert_into_databricks_activity_from_stage,)+from products.batch_exports.backend.temporal.destinations.file_download_batch_export import (+ FileDownloadBatchExportWorkflow,+ export_to_file_download_bucket_with_temporary_credentials,+ generate_file_downloads,+)from products.batch_exports.backend.temporal.destinations.http_batch_export import (HttpBatchExportWorkflow,insert_into_http_activity,@@ -67,12 +72,15 @@ WORKFLOWS = [HttpBatchExportWorkflow,BatchExportMonitoringWorkflow,WorkflowsBatchExportWorkflow,+ FileDownloadBatchExportWorkflow,]ACTIVITIES = [backfill_schedule,create_batch_export_backfill_model,get_backfill_info,+ generate_file_downloads,+ export_to_file_download_bucket_with_temporary_credentials,start_batch_export_run,finish_batch_export_run,update_batch_export_backfill_model,diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex e137bd991bd1..a86b652c6ba9 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -581,6 +581,7 @@ class FinishBatchExportRunInputs:failure_check_window: int = 50bytes_exported: int | None = Nonerecords_failed: int | None = None+ on_demand: bool = False@activity.defn@@ -594,7 +595,9 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:'failure_check_window' exceeds 'failure_threshold' and attempt to pause the batch export ifthat's the case. Also, a notification is sent to users on every failure."""- bind_contextvars(team_id=inputs.team_id, batch_export_id=inputs.batch_export_id, status=inputs.status)+ bind_contextvars(+ team_id=inputs.team_id, batch_export_id=inputs.batch_export_id, status=inputs.status, on_demand=inputs.on_demand+ )logger = LOGGER.bind()external_logger = EXTERNAL_LOGGER.bind()@@ -604,6 +607,7 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:"batch_export_id","failure_threshold","failure_check_window",+ "on_demand",)update_params = {key: valuediff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.pyindex 1bc9e05fab2c..5a4d568f8c30 100644--- a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py@@ -43,6 +43,8 @@ FILE_DOWNLOAD_PREFIX = (NON_RETRYABLE_ERROR_TYPES = ()+SESSION = aioboto3.Session()+class Credentials(typing.NamedTuple):aws_access_key_id: str@@ -98,9 +100,7 @@ async def _get_temporary_credentials_for_bucket_prefix(`_get_temporary_credentials_for_multipart_upload` or`_get_temporary_credentials_to_head_object` as needed."""- session = aioboto3.Session()-- async with session.client("sts") as sts:+ async with SESSION.client("sts") as sts:for attempt in range(1, max_attempts + 1):try:response = await sts.assume_role(@@ -173,7 +173,6 @@ FileDownloadIds = list[uuid.UUID]@activity.defn-@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)async def generate_file_downloads(inputs: GenerateFileDownloadsInputs) -> FileDownloadIds:"""Generate file downloads for given keys."""existing = [@@ -325,8 +324,10 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):interval_delta = data_interval_end_dt - data_interval_start_dt+ on_demand = Falseif inputs.batch_export_run_id is not None:run_id = str(inputs.batch_export_run_id)+ on_demand = Trueelse:start_batch_export_run_inputs = StartBatchExportRunInputs(team_id=inputs.team_id,@@ -363,6 +364,7 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):data_interval_start=data_interval_start_dt.isoformat() if not should_backfill_from_beginning else None,data_interval_end=data_interval_end_dt.isoformat(),destination_default_fields=s3_default_fields(),+ on_demand=on_demand,),s3_bucket=S3Bucket(name=settings.BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET,@@ -397,7 +399,7 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(initial_interval=dt.timedelta(seconds=1),maximum_interval=dt.timedelta(seconds=60),- maximum_attempts=0,+ maximum_attempts=3,),)diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex c801227d4f4c..0f76eedbf49d 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -42,6 +42,7 @@ class _BatchExportInputsProtocol(typing.Protocol):batch_export_id: str | None = Nonedestination_default_fields: list[BatchExportField] | None = Nonestage_folder: str | None = None+ on_demand: bool = Falseclass _ComposedBatchExportInputsProtocol(typing.Protocol):@@ -117,6 +118,7 @@ async def execute_batch_export_using_internal_stage(batch_export_id=batch_export_inputs.batch_export_id,status=BatchExportRun.Status.COMPLETED,team_id=batch_export_inputs.team_id,+ on_demand=batch_export_inputs.on_demand,)if TEST:diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/conftest.pyindex 6fa27473a2c7..c795bf7ac06d 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/conftest.py@@ -90,26 +90,29 @@ async def aws_role_arn(session, bucket_name, role_name):async with session.client("iam") as iam, session.client("sts") as sts:identity = await sts.get_caller_identity()identity_role_name = identity["Arn"].split("/")[-2]- resp = await iam.create_role(- RoleName=role_name,- MaxSessionDuration=3600,- # Allow the current account to assume the role- AssumeRolePolicyDocument=json.dumps(- {- "Version": "2012-10-17",- "Statement": [- {- "Effect": "Allow",- "Principal": {- "AWS": f"arn:aws:iam::{identity['Account']}:role/aws-reserved/sso.amazonaws.com/{identity_role_name}",- },- "Action": "sts:AssumeRole",- }- ],- }- ),- Description="Role assumed by the file download batch export during testing",- )+ try:+ resp = await iam.create_role(+ RoleName=role_name,+ MaxSessionDuration=3600,+ # Allow the current account to assume the role+ AssumeRolePolicyDocument=json.dumps(+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {+ "AWS": f"arn:aws:iam::{identity['Account']}:role/aws-reserved/sso.amazonaws.com/{identity_role_name}",+ },+ "Action": "sts:AssumeRole",+ }+ ],+ }+ ),+ Description="Role assumed by the file download batch export during testing",+ )+ except botocore.exceptions.ClientError:+ raise pytest.skip("Could not create test role")s3_policy = {"Version": "2012-10-17",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.pynew file mode 100644index 000000000000..4dd3f86cd172--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py@@ -0,0 +1,389 @@+import time+import uuid+import asyncio+import datetime as dt+from urllib.parse import urlsplit++import pytest+import freezegun++from django.conf import settings+from django.test import AsyncClient, override_settings++import aiohttp+import pyarrow as pa+import pyarrow.parquet as pq+from asgiref.sync import sync_to_async+from rest_framework import status+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.batch_exports.api.file_download import (+ _calculate_expiration_for_file_download,+ _generate_s3_pre_signed_url,+ _get_file_download_for_run,+)+from posthog.models import BatchExportDestination, BatchExportFileDownload, BatchExportOnDemand, BatchExportRun+from posthog.models.scoping import team_scope++from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWS++pytestmark = [+ pytest.mark.asyncio,+ pytest.mark.django_db,+]+++async def test_can_generate_s3_pre_signed_url(s3_client, s3_bucket, aws_role_arn):+ """Test we can generate a S3 pre signed URL for some test data."""+ key = f"batch-exports/{str(uuid.uuid4())}"+ test_data = b"test-data"+ await s3_client.put_object(Bucket=s3_bucket, Key=key, Body=test_data)++ url = _generate_s3_pre_signed_url(+ s3_bucket, key, role_arn=aws_role_arn, session_name="unit-test", max_attempts=10, delay=2+ )++ async with aiohttp.ClientSession() as session:+ async with session.get(url) as response:+ response.raise_for_status()+ result = await response.read()++ assert result == test_data++[email protected]_db(transaction=True)+async def test_get_file_download_for_run(team, 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.COMPLETED,+ )+ file_downloads = []+ for index in range(5):+ file_download = await BatchExportFileDownload.objects.acreate(+ team=team,+ batch_export_run=run,+ key=f"batch-exports/{index}",+ )+ file_downloads.append(file_download)++ no_part_file = await sync_to_async(_get_file_download_for_run)(run)+ index_first_file = await sync_to_async(_get_file_download_for_run)(run, 0)+ id_first_file = await sync_to_async(_get_file_download_for_run)(run, str(file_downloads[0].id))++ assert no_part_file == index_first_file == id_first_file == file_downloads[0]++ for index, file_download in enumerate(file_downloads[1:], start=1):+ index_file = await sync_to_async(_get_file_download_for_run)(run, index)+ id_file = await sync_to_async(_get_file_download_for_run)(run, str(file_download.id))++ assert index_file == id_file == file_downloads[index]++[email protected]_time()+async def test_calculate_expiration_for_file_download(ateam):+ """Test calculating the expiration time given a file download."""+ destination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config={})+ batch_export = BatchExportOnDemand(team_id=ateam.pk, destination=destination, model="events")++ now = dt.datetime.now(dt.UTC)+ batch_export_run = BatchExportRun(+ status=BatchExportRun.Status.STARTING,+ batch_export_on_demand=batch_export,+ data_interval_start=now - dt.timedelta(days=1),+ data_interval_end=now,+ )++ expected = dt.timedelta(hours=24)+ file_download = BatchExportFileDownload(+ team_id=ateam.pk, batch_export_run=batch_export_run, expires_at=now + expected+ )++ default_expiration = expected + dt.timedelta(seconds=1)+ expiration = _calculate_expiration_for_file_download(file_download, default_expiration=dt.timedelta(hours=25))++ assert expiration == expected++ default_expiration = expected - dt.timedelta(seconds=1)+ expiration = _calculate_expiration_for_file_download(file_download, default_expiration=default_expiration)++ assert expiration == default_expiration+++def team(base_test_mixin_fixture):+ return base_test_mixin_fixture.team+++def ateam(team):+ """Override the async-team fixture to use login-capable team.++ This is used by `generate_test_data`, so it needs to be the same team so that data+ is generated correctly.+ """+ return team+++def override_file_download_settings(aws_role_arn, s3_bucket):+ with override_settings(+ BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN=aws_role_arn,+ BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET=s3_bucket,+ BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS=900, # Minimum+ ):+ yield++[email protected]_db(transaction=True)+async def test_file_download_retrieve_returns_error(+ async_client: AsyncClient, temporal_client, team, user, data_interval_start, data_interval_end, generate_test_data+):+ 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.FAILED,+ latest_error="some error message",+ )++ await async_client.aforce_login(user)++ status_response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}",+ )+ data = status_response.json()+ assert data["status"] == "Failed", status_response.json()+ assert data.get("error", None) is not None+ assert data["error"] == "some error message"++[email protected]_db(transaction=True)+async def test_file_download_retrieve_returns_files(+ async_client: AsyncClient,+ temporal_client,+ 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.COMPLETED,+ )++ file_downloads = []+ for index in range(5):+ file_download = await BatchExportFileDownload.objects.acreate(+ team=team,+ batch_export_run=run,+ key=f"batch-exports/{index}",+ )+ file_downloads.append(file_download)++ await async_client.aforce_login(user)++ status_response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}",+ )+ data = status_response.json()+ assert data["status"] == "Completed", status_response.json()+ assert data["files"] == [str(file_download.id) for file_download in file_downloads]++[email protected]("override_file_download_settings")[email protected]_db(transaction=True)+async def test_file_download_download_fails_when_not_completed(+ async_client: AsyncClient, temporal_client, team, user, data_interval_start, data_interval_end, generate_test_data+):+ 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")++ await async_client.aforce_login(user)++ for run_status in (BatchExportRun.Status.RUNNING, BatchExportRun.Status.STARTING, BatchExportRun.Status.FAILED):+ run = await BatchExportRun.objects.acreate(+ batch_export_on_demand=batch_export,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ status=run_status,+ )++ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ if run_status == BatchExportRun.Status.FAILED:+ assert b"has failed" in response.content+ else:+ assert b"still in progress" in response.content++[email protected]("override_file_download_settings")[email protected]_db(transaction=True)+async def test_file_download_download(+ async_client: AsyncClient, temporal_client, team, user, data_interval_start, data_interval_end, generate_test_data+):+ 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,+ )+ file_downloads = []+ for index in range(5):+ file_download = await BatchExportFileDownload.objects.acreate(+ team=team,+ batch_export_run=run,+ key=f"batch-exports/{index}",+ )+ file_downloads.append(file_download)++ await async_client.aforce_login(user)++ # The first file is special as it should also be the one returned when no part is+ # passed.+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download",+ )+ no_part_pre_signed_url = urlsplit(response["Location"])++ first_file = file_downloads[0]+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download/{first_file.id}",+ )+ first_file_pre_signed_url = urlsplit(response["Location"])++ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download/0",+ )+ first_index_pre_signed_url = urlsplit(response["Location"])++ # URLs won't be exactly the same as the signature is newly generated on each+ # request, but the path to the file should be the same.+ assert (+ "/batch-exports/0"+ == f"/{first_file.key}"+ == first_index_pre_signed_url.path+ == first_file_pre_signed_url.path+ == no_part_pre_signed_url.path+ )++ for index, file_download in enumerate(file_downloads[1:], start=1):+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download/{file_download.id}",+ )+ file_pre_signed_url = urlsplit(response["Location"])++ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/download/{index}",+ )+ index_pre_signed_url = urlsplit(response["Location"])++ assert (+ f"/batch-exports/{index}"+ == f"/{file_download.key}"+ == file_pre_signed_url.path+ == index_pre_signed_url.path+ )++[email protected]("override_file_download_settings")[email protected]_db(transaction=True)+async def test_file_download_end_to_end(+ async_client: AsyncClient, temporal_client, team, user, data_interval_start, data_interval_end, generate_test_data+):+ await async_client.aforce_login(user)++ async with Worker(+ temporal_client,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ workflows=WORKFLOWS,+ activities=ACTIVITIES,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {+ "format": "Parquet",+ "compression": "zstd",+ },+ "model": "events",+ "data_interval_start": data_interval_start,+ "data_interval_end": data_interval_end,+ },+ content_type="application/json",+ )+ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()++ data = response.json()+ run_id = data["id"]++ timeout = 60+ start = time.monotonic()+ files = None+ while True:+ status_response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run_id}",+ )+ data = status_response.json()+ assert data["status"] in ("Starting", "Running", "Completed"), status_response.json()+ assert data.get("error", None) is None++ if data["status"] == "Completed":+ assert "files" in data+ files = data["files"]+ break++ now = time.monotonic()+ if now - start > timeout:+ raise TimeoutError("Batch export run took too long to complete")++ await asyncio.sleep(2)++ assert len(files) == 1+ response = await async_client.get(+ f"/api/projects/{team.pk}/file_download_batch_exports/{run_id}/download/{files[0]}",+ )+ assert response.status_code == 302+ pre_signed_url = response["Location"]++ async with aiohttp.ClientSession() as s:+ async with s.get(pre_signed_url) as resp:+ content = await resp.read()++ assert resp.status == 200, f"Invalid status: {resp.status}: {content!r}"++ table = pq.read_table(pa.BufferReader(content))+ events, _ = generate_test_data++ assert len(table) == len(events)+ assert "event" in table.column_namesdiff --git a/products/batch_exports/backend/tests/temporal/utils/s3.py b/products/batch_exports/backend/tests/temporal/utils/s3.pyindex d6b44e2a6079..798560960f6f 100644--- a/products/batch_exports/backend/tests/temporal/utils/s3.py+++ b/products/batch_exports/backend/tests/temporal/utils/s3.py@@ -27,11 +27,12 @@ async def read_parquet_from_s3(json_columns,) -> list:credentials = s3_client._request_signer._credentials # type: ignore+ frozen = await credentials.get_frozen_credentials()endpoint_url = s3_client.meta.endpoint_urls3 = fs.S3FileSystem(- access_key=credentials.access_key,- secret_key=credentials.secret_key,- session_token=credentials.token,+ access_key=frozen.access_key,+ secret_key=frozen.secret_key,+ session_token=frozen.token,endpoint_override=endpoint_url,)diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 744da007b6e8..c80aaebec8f5 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1295,6 +1295,223 @@ export interface PatchedBatchExportRequestApi {offset_hour?: number | null}+/**+ * Typed configuration for a FileDownload batch-export destination.+ */+export interface FileDownloadDestinationFileConfigApi {+ /** File format++ * `Parquet` - Parquet+ * `JSONLines` - JSONLines */+ format?: FileFormatEnumApi+ /** Compress the file with a supported compression format++ * `zstd` - zstd+ * `gzip` - gzip+ * `brotli` - brotli+ * `lz4` - lz4+ * `snappy` - snappy */+ compression?: CompressionEnumApi | null+ /**+ * Split download into multiple files of at most this size in MB+ * @minimum 0+ * @nullable+ */+ max_size_mb?: number | null+}++export type FileDownloadEventsRequestApiModel =+ (typeof FileDownloadEventsRequestApiModel)[keyof typeof FileDownloadEventsRequestApiModel]++export const FileDownloadEventsRequestApiModel = {+ Events: 'events',+} as const++/**+ * Typed configuration for the events model.+ */+export interface FileDownloadEventsRequestApi {+ file: FileDownloadDestinationFileConfigApi+ model: FileDownloadEventsRequestApiModel+ include?: string[]+ exclude?: string[]+ data_interval_start: string+ data_interval_end: string+}++export type FileDownloadPersonsRequestApiModel =+ (typeof FileDownloadPersonsRequestApiModel)[keyof typeof FileDownloadPersonsRequestApiModel]++export const FileDownloadPersonsRequestApiModel = {+ Persons: 'persons',+} as const++/**+ * Typed configuration for the persons model.+ */+export interface FileDownloadPersonsRequestApi {+ file: FileDownloadDestinationFileConfigApi+ model: FileDownloadPersonsRequestApiModel+ data_interval_start: string+ data_interval_end: string+}++export type FileDownloadSessionsRequestApiModel =+ (typeof FileDownloadSessionsRequestApiModel)[keyof typeof FileDownloadSessionsRequestApiModel]++export const FileDownloadSessionsRequestApiModel = {+ Sessions: 'sessions',+} as const++/**+ * Typed configuration for the sessions model.+ */+export interface FileDownloadSessionsRequestApi {+ file: FileDownloadDestinationFileConfigApi+ model: FileDownloadSessionsRequestApiModel+ data_interval_start: string+ data_interval_end: string+}++export type CreateFileDownloadRequestApi =+ | FileDownloadEventsRequestApi+ | FileDownloadPersonsRequestApi+ | FileDownloadSessionsRequestApi++/**+ * Typed output for view set `create`.+ */+export interface CreateOutputApi {+ id: string+}++export type RetrieveBasicOutputApiStatus =+ (typeof RetrieveBasicOutputApiStatus)[keyof typeof RetrieveBasicOutputApiStatus]++export const RetrieveBasicOutputApiStatus = {+ Starting: 'Starting',+ Running: 'Running',+ Cancelled: 'Cancelled',+} as const++/**+ * Typed output for view set `retrieve` with any of the statuses without extra output.+ */+export interface RetrieveBasicOutputApi {+ status: RetrieveBasicOutputApiStatus+}++export type RetrieveCompletedOutputApiStatus =+ (typeof RetrieveCompletedOutputApiStatus)[keyof typeof RetrieveCompletedOutputApiStatus]++export const RetrieveCompletedOutputApiStatus = {+ Completed: 'Completed',+} as const++/**+ * Typed output for view set `retrieve` with completed status.+ */+export interface RetrieveCompletedOutputApi {+ status: RetrieveCompletedOutputApiStatus+ files: string[]+}++export type RetrieveFailedOutputApiStatus =+ (typeof RetrieveFailedOutputApiStatus)[keyof typeof RetrieveFailedOutputApiStatus]++export const RetrieveFailedOutputApiStatus = {+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ TimedOut: 'TimedOut',+ Terminated: 'Terminated',+} as const++/**+ * Typed output for view set `retrieve` with any of the failed statuses.+ */+export interface RetrieveFailedOutputApi {+ status: RetrieveFailedOutputApiStatus+ error: string+}++export type RetrieveFileDownloadResponseApi =+ | RetrieveBasicOutputApi+ | RetrieveCompletedOutputApi+ | RetrieveFailedOutputApi++/**+ * * `events` - events+ */+export type FileDownloadEventsRequestModelEnumApi =+ (typeof FileDownloadEventsRequestModelEnumApi)[keyof typeof FileDownloadEventsRequestModelEnumApi]++export const FileDownloadEventsRequestModelEnumApi = {+ Events: 'events',+} as const++/**+ * * `persons` - persons+ */+export type FileDownloadPersonsRequestModelEnumApi =+ (typeof FileDownloadPersonsRequestModelEnumApi)[keyof typeof FileDownloadPersonsRequestModelEnumApi]++export const FileDownloadPersonsRequestModelEnumApi = {+ Persons: 'persons',+} as const++/**+ * * `sessions` - sessions+ */+export type FileDownloadSessionsRequestModelEnumApi =+ (typeof FileDownloadSessionsRequestModelEnumApi)[keyof typeof FileDownloadSessionsRequestModelEnumApi]++export const FileDownloadSessionsRequestModelEnumApi = {+ Sessions: 'sessions',+} as const++/**+ * * `Starting` - Starting+ * `Running` - Running+ * `Cancelled` - Cancelled+ */+export type RetrieveBasicOutputStatusEnumApi =+ (typeof RetrieveBasicOutputStatusEnumApi)[keyof typeof RetrieveBasicOutputStatusEnumApi]++export const RetrieveBasicOutputStatusEnumApi = {+ Starting: 'Starting',+ Running: 'Running',+ Cancelled: 'Cancelled',+} as const++/**+ * * `Completed` - Completed+ */+export type RetrieveCompletedOutputStatusEnumApi =+ (typeof RetrieveCompletedOutputStatusEnumApi)[keyof typeof RetrieveCompletedOutputStatusEnumApi]++export const RetrieveCompletedOutputStatusEnumApi = {+ Completed: 'Completed',+} as const++/**+ * * `Failed` - Failed+ * `FailedRetryable` - FailedRetryable+ * `FailedBilling` - FailedBilling+ * `Terminated` - Terminated+ * `TimedOut` - TimedOut+ */+export type RetrieveFailedOutputStatusEnumApi =+ (typeof RetrieveFailedOutputStatusEnumApi)[keyof typeof RetrieveFailedOutputStatusEnumApi]++export const RetrieveFailedOutputStatusEnumApi = {+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ Terminated: 'Terminated',+ TimedOut: 'TimedOut',+} as const+/*** * `Databricks` - Databricks*/@@ -1421,3 +1638,35 @@ export type BatchExportsLogsRetrieveParams = {*/search?: string}++export type FileDownloadBatchExportsLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string+}diff --git a/products/batch_exports/frontend/generated/api.ts b/products/batch_exports/frontend/generated/api.tsindex 814e6de56e97..0ae8909d90fc 100644--- a/products/batch_exports/frontend/generated/api.ts+++ b/products/batch_exports/frontend/generated/api.ts@@ -18,10 +18,14 @@ import type {BatchExportsLogsRetrieveParams,BatchExportsRunsListParams,BatchExportsRunsLogsRetrieveParams,+ CreateFileDownloadRequestApi,+ CreateOutputApi,+ FileDownloadBatchExportsLogsRetrieveParams,PaginatedBatchExportBackfillListApi,PaginatedBatchExportListApi,PaginatedBatchExportRunListApi,PatchedBatchExportRequestApi,+ RetrieveFileDownloadResponseApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -499,3 +503,103 @@ export const batchExportsTestRetrieve = async (projectId: string, options?: Requmethod: 'GET',})}++export const getFileDownloadBatchExportsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/file_download_batch_exports/`+}++/**+ * Create and start a batch export on demand run to download a file.+ */+export const fileDownloadBatchExportsCreate = async (+ projectId: string,+ createFileDownloadRequestApi?: CreateFileDownloadRequestApi,+ options?: RequestInit+): Promise<CreateOutputApi> => {+ return apiMutator<CreateOutputApi>(getFileDownloadBatchExportsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createFileDownloadRequestApi),+ })+}++export const getFileDownloadBatchExportsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/file_download_batch_exports/${id}/`+}++/**+ * Get a run of a batch export on demand.++If the underlying batch export run has completed, we return keys to the+generated file downloads so that users may download them by making a request+to /download.+ */+export const fileDownloadBatchExportsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<RetrieveFileDownloadResponseApi> => {+ return apiMutator<RetrieveFileDownloadResponseApi>(getFileDownloadBatchExportsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getFileDownloadBatchExportsDownloadRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/file_download_batch_exports/${id}/download/`+}++/**+ * Download a file (or a part) from this batch export run.++Users can provide a part component with an id or index, or no part component at+all:+* If part id is included: The file download matching the id is downloaded.+* If part index is included: The file download matching the index (as ordered+ by key) is downloaded.+* If no part component is present: If there is only one file downloaded, that+ is downloaded. Otherwise the first one as sorted by key is downloaded.+ */+export const fileDownloadBatchExportsDownloadRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getFileDownloadBatchExportsDownloadRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getFileDownloadBatchExportsLogsRetrieveUrl = (+ projectId: string,+ id: string,+ params?: FileDownloadBatchExportsLogsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/file_download_batch_exports/${id}/logs/?${stringifiedParams}`+ : `/api/projects/${projectId}/file_download_batch_exports/${id}/logs/`+}++export const fileDownloadBatchExportsLogsRetrieve = async (+ projectId: string,+ id: string,+ params?: FileDownloadBatchExportsLogsRetrieveParams,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getFileDownloadBatchExportsLogsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 995a35b94e47..7745cc58bd45 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -1589,3 +1589,122 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod),}).describe('Serializer for a BatchExport model.')++/**+ * Create and start a batch export on demand run to download a file.+ */+export const fileDownloadBatchExportsCreateBodyOneFileFormatDefault = `Parquet`+export const fileDownloadBatchExportsCreateBodyOneFileMaxSizeMbMin = 0++export const fileDownloadBatchExportsCreateBodyTwoFileFormatDefault = `Parquet`+export const fileDownloadBatchExportsCreateBodyTwoFileMaxSizeMbMin = 0++export const fileDownloadBatchExportsCreateBodyThreeFileFormatDefault = `Parquet`+export const fileDownloadBatchExportsCreateBodyThreeFileMaxSizeMbMin = 0++export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([+ zod+ .object({+ file: zod+ .object({+ format: zod+ .enum(['JSONLines', 'Parquet'])+ .describe('\* `JSONLines` - JSONLines\n\* `Parquet` - Parquet')+ .default(fileDownloadBatchExportsCreateBodyOneFileFormatDefault)+ .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(fileDownloadBatchExportsCreateBodyOneFileMaxSizeMbMin)+ .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']),+ 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('Typed configuration for the events model.'),+ zod+ .object({+ file: zod+ .object({+ format: zod+ .enum(['JSONLines', 'Parquet'])+ .describe('\* `JSONLines` - JSONLines\n\* `Parquet` - Parquet')+ .default(fileDownloadBatchExportsCreateBodyTwoFileFormatDefault)+ .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(fileDownloadBatchExportsCreateBodyTwoFileMaxSizeMbMin)+ .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(['persons']),+ data_interval_start: zod.iso.datetime({ offset: true }),+ data_interval_end: zod.iso.datetime({ offset: true }),+ })+ .describe('Typed configuration for the persons model.'),+ zod+ .object({+ file: zod+ .object({+ format: zod+ .enum(['JSONLines', 'Parquet'])+ .describe('\* `JSONLines` - JSONLines\n\* `Parquet` - Parquet')+ .default(fileDownloadBatchExportsCreateBodyThreeFileFormatDefault)+ .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(fileDownloadBatchExportsCreateBodyThreeFileMaxSizeMbMin)+ .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(['sessions']),+ data_interval_start: zod.iso.datetime({ offset: true }),+ data_interval_end: zod.iso.datetime({ offset: true }),+ })+ .describe('Typed configuration for the sessions model.'),+])diff --git a/products/batch_exports/mcp/tools.yaml b/products/batch_exports/mcp/tools.yamlindex 01f0014d077c..e2637b296355 100644--- a/products/batch_exports/mcp/tools.yaml+++ b/products/batch_exports/mcp/tools.yaml@@ -176,3 +176,15 @@ tools:batch-exports-update:operation: batch_exports_updateenabled: false+ file-download-batch-exports-create:+ operation: file_download_batch_exports_create+ enabled: false+ file-download-batch-exports-download-retrieve:+ operation: file_download_batch_exports_download_retrieve+ enabled: false+ file-download-batch-exports-logs-retrieve:+ operation: file_download_batch_exports_logs_retrieve+ enabled: false+ file-download-batch-exports-retrieve:+ operation: file_download_batch_exports_retrieve+ enabled: falsediff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex fe26acb54538..7f6c27b2005c 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -21,6 +21,9 @@ tools:domains-scim-logs-retrieve:operation: domains_scim_logs_retrieveenabled: false+ file-download-batch-exports-logs-retrieve:+ operation: file_download_batch_exports_logs_retrieve+ enabled: falsehog-flow-templates-logs-retrieve:operation: hog_flow_templates_logs_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 43cdd7c563ad..4c6bb40ca61d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8193,6 +8193,86 @@ export namespace Schemas {GithubRepo: 'github_repo',} as const;+ /**+ * Typed configuration for a FileDownload batch-export destination.+ */+ export interface FileDownloadDestinationFileConfig {+ /** File format++ * `Parquet` - Parquet+ * `JSONLines` - JSONLines */+ format?: FileFormatEnum;+ /** Compress the file with a supported compression format++ * `zstd` - zstd+ * `gzip` - gzip+ * `brotli` - brotli+ * `lz4` - lz4+ * `snappy` - snappy */+ compression?: CompressionEnum | null;+ /**+ * Split download into multiple files of at most this size in MB+ * @minimum 0+ * @nullable+ */+ max_size_mb?: number | null;+ }++ export type FileDownloadEventsRequestModel = typeof FileDownloadEventsRequestModel[keyof typeof FileDownloadEventsRequestModel];+++ export const FileDownloadEventsRequestModel = {+ Events: 'events',+ } as const;++ /**+ * Typed configuration for the events model.+ */+ export interface FileDownloadEventsRequest {+ file: FileDownloadDestinationFileConfig;+ model: FileDownloadEventsRequestModel;+ include?: string[];+ exclude?: string[];+ data_interval_start: string;+ data_interval_end: string;+ }++ export type FileDownloadPersonsRequestModel = typeof FileDownloadPersonsRequestModel[keyof typeof FileDownloadPersonsRequestModel];+++ export const FileDownloadPersonsRequestModel = {+ Persons: 'persons',+ } as const;++ /**+ * Typed configuration for the persons model.+ */+ export interface FileDownloadPersonsRequest {+ file: FileDownloadDestinationFileConfig;+ model: FileDownloadPersonsRequestModel;+ data_interval_start: string;+ data_interval_end: string;+ }++ export type FileDownloadSessionsRequestModel = typeof FileDownloadSessionsRequestModel[keyof typeof FileDownloadSessionsRequestModel];+++ export const FileDownloadSessionsRequestModel = {+ Sessions: 'sessions',+ } as const;++ /**+ * Typed configuration for the sessions model.+ */+ export interface FileDownloadSessionsRequest {+ file: FileDownloadDestinationFileConfig;+ model: FileDownloadSessionsRequestModel;+ data_interval_start: string;+ data_interval_end: string;+ }++ export type CreateFileDownloadRequest = FileDownloadEventsRequest | FileDownloadPersonsRequest | FileDownloadSessionsRequest;+/*** * `cost` - cost* `latency` - latency@@ -8278,6 +8358,13 @@ export namespace Schemas {representative_email: string;}+ /**+ * Typed output for view set `create`.+ */+ export interface CreateOutput {+ id: string;+ }+/*** * `zoom` - zoom* `teams` - teams@@ -16937,6 +17024,36 @@ export namespace Schemas {readonly modified_by: number | null;}+ /**+ * * `events` - events+ */+ export type FileDownloadEventsRequestModelEnum = typeof FileDownloadEventsRequestModelEnum[keyof typeof FileDownloadEventsRequestModelEnum];+++ export const FileDownloadEventsRequestModelEnum = {+ Events: 'events',+ } as const;++ /**+ * * `persons` - persons+ */+ export type FileDownloadPersonsRequestModelEnum = typeof FileDownloadPersonsRequestModelEnum[keyof typeof FileDownloadPersonsRequestModelEnum];+++ export const FileDownloadPersonsRequestModelEnum = {+ Persons: 'persons',+ } as const;++ /**+ * * `sessions` - sessions+ */+ export type FileDownloadSessionsRequestModelEnum = typeof FileDownloadSessionsRequestModelEnum[keyof typeof FileDownloadSessionsRequestModelEnum];+++ export const FileDownloadSessionsRequestModelEnum = {+ Sessions: 'sessions',+ } as const;+export interface FileSystem {readonly id: string;path: string;@@ -34523,6 +34640,100 @@ export namespace Schemas {password: string;}+ export type RetrieveBasicOutputStatus = typeof RetrieveBasicOutputStatus[keyof typeof RetrieveBasicOutputStatus];+++ export const RetrieveBasicOutputStatus = {+ Starting: 'Starting',+ Running: 'Running',+ Cancelled: 'Cancelled',+ } as const;++ /**+ * Typed output for view set `retrieve` with any of the statuses without extra output.+ */+ export interface RetrieveBasicOutput {+ status: RetrieveBasicOutputStatus;+ }++ /**+ * * `Starting` - Starting+ * `Running` - Running+ * `Cancelled` - Cancelled+ */+ export type RetrieveBasicOutputStatusEnum = typeof RetrieveBasicOutputStatusEnum[keyof typeof RetrieveBasicOutputStatusEnum];+++ export const RetrieveBasicOutputStatusEnum = {+ Starting: 'Starting',+ Running: 'Running',+ Cancelled: 'Cancelled',+ } as const;++ export type RetrieveCompletedOutputStatus = typeof RetrieveCompletedOutputStatus[keyof typeof RetrieveCompletedOutputStatus];+++ export const RetrieveCompletedOutputStatus = {+ Completed: 'Completed',+ } as const;++ /**+ * Typed output for view set `retrieve` with completed status.+ */+ export interface RetrieveCompletedOutput {+ status: RetrieveCompletedOutputStatus;+ files: string[];+ }++ /**+ * * `Completed` - Completed+ */+ export type RetrieveCompletedOutputStatusEnum = typeof RetrieveCompletedOutputStatusEnum[keyof typeof RetrieveCompletedOutputStatusEnum];+++ export const RetrieveCompletedOutputStatusEnum = {+ Completed: 'Completed',+ } as const;++ export type RetrieveFailedOutputStatus = typeof RetrieveFailedOutputStatus[keyof typeof RetrieveFailedOutputStatus];+++ export const RetrieveFailedOutputStatus = {+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ TimedOut: 'TimedOut',+ Terminated: 'Terminated',+ } as const;++ /**+ * Typed output for view set `retrieve` with any of the failed statuses.+ */+ export interface RetrieveFailedOutput {+ status: RetrieveFailedOutputStatus;+ error: string;+ }++ /**+ * * `Failed` - Failed+ * `FailedRetryable` - FailedRetryable+ * `FailedBilling` - FailedBilling+ * `Terminated` - Terminated+ * `TimedOut` - TimedOut+ */+ export type RetrieveFailedOutputStatusEnum = typeof RetrieveFailedOutputStatusEnum[keyof typeof RetrieveFailedOutputStatusEnum];+++ export const RetrieveFailedOutputStatusEnum = {+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ Terminated: 'Terminated',+ TimedOut: 'TimedOut',+ } as const;++ export type RetrieveFileDownloadResponse = RetrieveBasicOutput | RetrieveCompletedOutput | RetrieveFailedOutput;+export interface ReviewQueueCreate {/*** Human-readable queue name.@@ -38128,6 +38339,38 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsFileDownloadBatchExportsLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string;+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string;+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string;+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string;+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string;+ };+export type EnvironmentsFileSystemListParams = {/*** Number of results to return per page.@@ -43308,6 +43551,38 @@ export namespace Schemas {groups?: string;};+ export type FileDownloadBatchExportsLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string;+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string;+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string;+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string;+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string;+ };+export type FileSystemListParams = {/*** Number of results to return per page.