Skip to content

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

feat: New file download batch export (#56776)

Tomás Farías Santana207d2fb4f7c8
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 78042b3ba0c4..5170645392eb 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -63,6 +63,7 @@ rules:
|ApprovalPolicy
|BatchExport
|BatchExportBackfill
+ |BatchExportFileDownload
|BatchImport
|ButtonTile
|ChangeRequest
@@ -269,6 +270,7 @@ rules:
|ApprovalPolicy
|BatchExport
|BatchExportBackfill
+ |BatchExportFileDownload
|BatchImport
|ButtonTile
|ChangeRequest
diff --git a/posthog/batch_exports/models.py b/posthog/batch_exports/models.py
index 50c6d341725b..0e15118ad6ae 100644
--- a/posthog/batch_exports/models.py
+++ b/posthog/batch_exports/models.py
@@ -66,6 +66,7 @@ class BatchExportDestination(UUIDTModel):
WORKFLOWS = "Workflows"
HTTP = "HTTP"
NOOP = "NoOp"
+ FILE_DOWNLOAD = "FileDownload"
secret_fields = {
"S3": {"aws_access_key_id", "aws_secret_access_key"},
@@ -78,6 +79,7 @@ class BatchExportDestination(UUIDTModel):
"HTTP": {"token"},
"NoOp": set(),
"Workflows": set(),
+ "FileDownload": set(),
}
type = models.CharField(
@@ -469,3 +471,58 @@ class BatchExportBackfill(UUIDTModel):
BatchExportRun.Status.FAILED,
],
).count()
+
+
+class BatchExportFileDownload(ModelActivityMixin, UUIDTModel):
+ """Represents a file made available to download by a batch export.
+
+ When creating a "file-download" batch export, the output is a row in this table
+ containing pre-signed URLs to access the data exported.
+ """
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["team", "key"], name="team_key_idx"),
+ ]
+
+ team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")
+ batch_export_run = models.ForeignKey(
+ "BatchExportRun",
+ on_delete=models.CASCADE,
+ help_text="The batch export run that generated this file downloads.",
+ )
+ key = models.TextField(help_text="The S3 key containing the file to download.")
+ expires_at = models.DateTimeField(null=True, help_text="When will this key expire, if available.")
+
+ created_at = models.DateTimeField(
+ auto_now_add=True,
+ help_text="The timestamp at which this was created.",
+ )
+ last_updated_at = models.DateTimeField(
+ auto_now=True,
+ help_text="The timestamp at which this was last updated.",
+ )
+
+ def is_expired(self) -> bool:
+ """Return whether this file download is expired.
+
+ If expired, then the file download should not be used to generate download URLs anymore.
+ """
+ if self.expires_at is None:
+ raise ValueError("Cannot determine if object is expired: `expires_at` missing.")
+
+ return dt.datetime.now(dt.UTC) > self.expires_at
+
+ def is_expired_or_close(self, threshold: dt.timedelta | int = dt.timedelta(hours=1)) -> bool:
+ """Return whether this file download is expired, or close to expiring."""
+ if self.is_expired():
+ return True
+
+ delta = self.expires_at - dt.datetime.now(dt.UTC) # type: ignore
+
+ if isinstance(threshold, int):
+ threshold_delta = dt.timedelta(seconds=threshold)
+ else:
+ threshold_delta = threshold
+
+ return threshold_delta > delta
diff --git a/posthog/migrations/1142_alter_batchexportdestination_type_and_more.py b/posthog/migrations/1142_alter_batchexportdestination_type_and_more.py
new file mode 100644
index 000000000000..3eb8807abc8f
--- /dev/null
+++ b/posthog/migrations/1142_alter_batchexportdestination_type_and_more.py
@@ -0,0 +1,91 @@
+# Generated by Django 5.2.13 on 2026-05-04 13:01
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1141_datadeletionrequest_attempt_count_and_more"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="batchexportdestination",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("S3", "S3"),
+ ("Snowflake", "Snowflake"),
+ ("Postgres", "Postgres"),
+ ("Redshift", "Redshift"),
+ ("BigQuery", "Bigquery"),
+ ("Databricks", "Databricks"),
+ ("AzureBlob", "Azure Blob"),
+ ("Workflows", "Workflows"),
+ ("HTTP", "Http"),
+ ("NoOp", "Noop"),
+ ("FileDownload", "File Download"),
+ ],
+ help_text="A choice of supported BatchExportDestination types.",
+ max_length=64,
+ ),
+ ),
+ migrations.CreateModel(
+ name="BatchExportFileDownload",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "key",
+ models.TextField(help_text="The S3 key containing the file to download."),
+ ),
+ (
+ "expires_at",
+ models.DateTimeField(help_text="When will this key expire, if available.", null=True),
+ ),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ help_text="The timestamp at which this was created.",
+ ),
+ ),
+ (
+ "last_updated_at",
+ models.DateTimeField(
+ auto_now=True,
+ help_text="The timestamp at which this was last updated.",
+ ),
+ ),
+ (
+ "batch_export_run",
+ models.ForeignKey(
+ help_text="The batch export run that generated this file downloads.",
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.batchexportrun",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ help_text="The team this belongs to.",
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [models.Index(fields=["team", "key"], name="team_key_idx")],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 0cbfea0bd66c..39701f8a8036 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1141_datadeletionrequest_attempt_count_and_more
+1142_alter_batchexportdestination_type_and_more
diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.py
index 4904592e5a99..b8398a9437a5 100644
--- a/posthog/settings/batch_exports.py
+++ b/posthog/settings/batch_exports.py
@@ -98,3 +98,6 @@ BATCH_EXPORTS_PERSONS_LIMITED_EXPORT_TEAM_IDS: list[str] = get_list(
BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM: int = get_from_env(
"BATCH_EXPORT_MAX_CONCURRENT_BACKFILLS_PER_TEAM", 100, type_cast=int
)
+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")
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index ba3a50580876..c81d41812db8 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -264,6 +264,28 @@ class S3BatchExportInputs(BaseBatchExportInputs):
use_virtual_style_addressing: bool = False
+@dataclass(kw_only=True)
+class FileDownloadBatchExportInputs(BaseBatchExportInputs):
+ """Inputs for a file download batch export workflow.
+
+ Attributes:
+ data_interval_start: Lower bound for the batch export.
+ data_interval_end: Upper bound for the batch export.
+ file_format: File format to use when exporting files. Same as S3.
+ max_file_size_mb: The maximum file size in MB for each file to be uploaded. Same
+ as S3.
+ compression: Compression algorithm, if any. Same as S3.
+ expires_in: Number of seconds to expire the download URLs.
+ """
+
+ data_interval_start: str | None = None
+ batch_export_run_id: UUID | None = None
+ file_format: str = "Parquet"
+ max_file_size_mb: int | None = None
+ compression: str | None = None
+ expires_in_seconds: int = 3600
+
+
@dataclass(kw_only=True)
class SnowflakeBatchExportInputs(BaseBatchExportInputs):
"""Inputs for Snowflake export workflow."""
@@ -441,15 +463,16 @@ class NoOpInputs(BaseBatchExportInputs):
DESTINATION_WORKFLOWS = {
- "S3": ("s3-export", S3BatchExportInputs),
- "Snowflake": ("snowflake-export", SnowflakeBatchExportInputs),
- "Postgres": ("postgres-export", PostgresBatchExportInputs),
- "Redshift": ("redshift-export", RedshiftBatchExportInputs),
+ "AzureBlob": ("azure-blob-export", AzureBlobBatchExportInputs),
"BigQuery": ("bigquery-export", BigQueryBatchExportInputs),
"Databricks": ("databricks-export", DatabricksBatchExportInputs),
- "AzureBlob": ("azure-blob-export", AzureBlobBatchExportInputs),
+ "FileDownload": ("file-download-export", FileDownloadBatchExportInputs),
"HTTP": ("http-export", HttpBatchExportInputs),
"NoOp": ("no-op", NoOpInputs),
+ "Postgres": ("postgres-export", PostgresBatchExportInputs),
+ "Redshift": ("redshift-export", RedshiftBatchExportInputs),
+ "S3": ("s3-export", S3BatchExportInputs),
+ "Snowflake": ("snowflake-export", SnowflakeBatchExportInputs),
"Workflows": ("workflows-export", WorkflowsBatchExportInputs),
}
diff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
new file mode 100644
index 000000000000..1bc9e05fab2c
--- /dev/null
+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
@@ -0,0 +1,408 @@
+import re
+import json
+import uuid
+import typing
+import asyncio
+import datetime as dt
+import dataclasses
+
+from django.conf import settings
+
+import aioboto3
+from botocore.exceptions import ClientError
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.batch_exports.models import BatchExportFileDownload
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.common.logger import get_logger, get_write_only_logger
+
+from products.batch_exports.backend.service import BatchExportInsertInputs, FileDownloadBatchExportInputs
+from products.batch_exports.backend.temporal.batch_exports import (
+ OverBillingLimitError,
+ StartBatchExportRunInputs,
+ get_data_interval,
+ start_batch_export_run,
+)
+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
+ S3BatchExportResult,
+ S3InsertInputs,
+ insert_into_s3_activity_from_stage,
+ s3_default_fields,
+)
+from products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stage
+from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
+from products.batch_exports.backend.temporal.utils import handle_non_retryable_errors
+
+LOGGER = get_write_only_logger(__name__)
+EXTERNAL_LOGGER = get_logger()
+FILE_DOWNLOAD_PREFIX = (
+ "batch-exports/{batch_export_id}/{batch_export_run_id}/{{data_interval_start}}-{{data_interval_end}}"
+)
+
+NON_RETRYABLE_ERROR_TYPES = ()
+
+
+class Credentials(typing.NamedTuple):
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_session_token: str
+
+
+async def _get_temporary_credentials_for_multipart_upload(
+ bucket: str, prefix: str, /, role_arn: str, duration: int = 3600
+) -> Credentials:
+ """Get temporary AWS credentials for a multipart upload to keys under prefix."""
+ creds = await _get_temporary_credentials_for_bucket_prefix(
+ bucket,
+ prefix,
+ role_arn=role_arn,
+ session_name="batch-exports-file-download-multipart-upload",
+ actions=["s3:PutObject", "s3:AbortMultipartUpload"],
+ duration=duration,
+ )
+ return creds
+
+
+async def _get_temporary_credentials_to_head_object(
+ bucket: str, prefix: str, /, role_arn: str, duration: int = 900
+) -> Credentials:
+ """Get temporary AWS credentials for HEAD object requests for keys under prefix."""
+ creds = await _get_temporary_credentials_for_bucket_prefix(
+ bucket,
+ prefix,
+ role_arn=role_arn,
+ session_name="batch-exports-file-download-head-object",
+ actions=["s3:GetObject"],
+ duration=duration,
+ )
+ return creds
+
+
+async def _get_temporary_credentials_for_bucket_prefix(
+ bucket: str,
+ prefix: str,
+ /,
+ role_arn: str,
+ session_name: str,
+ actions: list[str],
+ duration: int = 3600,
+ max_attempts: int = 5,
+ delay: int | float = 1.0,
+) -> Credentials:
+ """Get temporary credentials scoped to operate only on the bucket's prefix.
+
+ The credentials should be limited to a set of actions using the `actions` argument.
+ Thus, this should not be called directly, rather call
+ `_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:
+ for attempt in range(1, max_attempts + 1):
+ try:
+ response = await sts.assume_role(
+ RoleArn=role_arn,
+ RoleSessionName=session_name,
+ DurationSeconds=duration,
+ Policy=json.dumps(
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": actions,
+ "Resource": f"arn:aws:s3:::{bucket}/{prefix}/*",
+ },
+ ],
+ }
+ ),
+ )
+ except ClientError as e:
+ code = e.response["Error"]["Code"]
+ if code != "AccessDenied" or attempt == max_attempts:
+ raise
+
+ await asyncio.sleep(delay * (2**attempt))
+
+ return Credentials(
+ response["Credentials"]["AccessKeyId"],
+ response["Credentials"]["SecretAccessKey"],
+ response["Credentials"]["SessionToken"],
+ )
+
+
+def parse_expiration(expiration: str | dt.datetime | None) -> dt.datetime | None:
+ """Parse an expiration string returned by AWS to extract the expiry-date."""
+ if expiration is None:
+ return None
+
+ if isinstance(expiration, dt.datetime):
+ return expiration
+
+ match = re.search(r'expiry-date="([^"]+)"', expiration)
+
+ if match is None:
+ return None
+
+ date_str = match.group(1)
+ expiry_date = dt.datetime.strptime(date_str, "%a, %d %b %Y %H:%M:%S %Z").replace(tzinfo=dt.UTC)
+
+ return expiry_date
+
+
+class S3Bucket:
+ name: str
+ region: str
+
+
+class GenerateFileDownloadsInputs:
+ team_id: int
+ batch_export_id: str
+ batch_export_run_id: str
+ s3_bucket: S3Bucket
+ aws_role_arn: str
+ keys: tuple[str, ...]
+
+
+FileDownloadIds = list[uuid.UUID]
+
+
+@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)
+async def generate_file_downloads(inputs: GenerateFileDownloadsInputs) -> FileDownloadIds:
+ """Generate file downloads for given keys."""
+ existing = [
+ file_download
+ async for file_download in BatchExportFileDownload.objects.filter(
+ team_id=inputs.team_id, key__in=inputs.keys
+ ).all()
+ ]
+ file_downloads = [file_download.id for file_download in existing]
+ keys = set(inputs.keys) - {file_download.key for file_download in existing}
+
+ if not keys:
+ # There is nothing to do, maybe we completed everything in a previous attempt.
+ return file_downloads
+
+ async with Heartbeater():
+ credentials = await _get_temporary_credentials_to_head_object(
+ inputs.s3_bucket.name,
+ f"batch-exports/{inputs.batch_export_id}/{inputs.batch_export_run_id}",
+ role_arn=inputs.aws_role_arn,
+ )
+ session = aioboto3.Session(
+ aws_access_key_id=credentials.aws_access_key_id,
+ aws_secret_access_key=credentials.aws_secret_access_key,
+ aws_session_token=credentials.aws_session_token,
+ )
+
+ async with session.client("s3") as s3:
+
+ async def create_file_download(key: str):
+ object = await s3.head_object(Bucket=inputs.s3_bucket.name, Key=key)
+
+ expires_at = parse_expiration(object.get("Expiration"))
+ file_download = await BatchExportFileDownload.objects.acreate(
+ team_id=inputs.team_id,
+ key=key,
+ expires_at=expires_at,
+ batch_export_run_id=inputs.batch_export_run_id,
+ )
+ file_downloads.append(file_download.id)
+
+ async with asyncio.TaskGroup() as tg:
+ for key in keys:
+ tg.create_task(create_file_download(key))
+
+ return file_downloads
+
+
+class ExportInputs:
+ batch_export: BatchExportInsertInputs
+ s3_bucket: S3Bucket
+ aws_role_arn: str
+ compression: str | None = None
+ file_format: str = "JSONLines"
+ max_file_size_mb: int | None = None
+
+
+@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)
+async def export_to_file_download_bucket_with_temporary_credentials(inputs: ExportInputs) -> S3BatchExportResult:
+ """Export to S3 file download bucket using temporary AWS credentials.
+
+ After obtaining the credentials, we simply run the same function as an S3 batch
+ export targeting our own file download bucket.
+ """
+ prefix = FILE_DOWNLOAD_PREFIX.format(
+ batch_export_id=inputs.batch_export.batch_export_id, batch_export_run_id=inputs.batch_export.run_id
+ )
+
+ credentials = await _get_temporary_credentials_for_multipart_upload(
+ inputs.s3_bucket.name,
+ f"batch-exports/{inputs.batch_export.batch_export_id}/{inputs.batch_export.run_id}",
+ role_arn=inputs.aws_role_arn,
+ )
+
+ s3_insert_inputs = S3InsertInputs(
+ bucket_name=inputs.s3_bucket.name,
+ region=inputs.s3_bucket.region,
+ prefix=prefix,
+ compression=inputs.compression,
+ file_format=inputs.file_format,
+ max_file_size_mb=inputs.max_file_size_mb,
+ aws_access_key_id=credentials.aws_access_key_id,
+ aws_secret_access_key=credentials.aws_secret_access_key,
+ aws_session_token=credentials.aws_session_token,
+ data_interval_start=inputs.batch_export.data_interval_start,
+ data_interval_end=inputs.batch_export.data_interval_end,
+ exclude_events=inputs.batch_export.exclude_events,
+ include_events=inputs.batch_export.include_events,
+ team_id=inputs.batch_export.team_id,
+ run_id=inputs.batch_export.run_id,
+ stage_folder=inputs.batch_export.stage_folder,
+ batch_export_model=inputs.batch_export.batch_export_model,
+ batch_export_id=inputs.batch_export.batch_export_id,
+ destination_default_fields=inputs.batch_export.destination_default_fields,
+ )
+ result = await insert_into_s3_activity_from_stage(s3_insert_inputs)
+
+ return result
+
+
+class FileDownloadBatchExportResult(BatchExportResult):
+ file_downloads: FileDownloadIds = dataclasses.field(default_factory=list)
+
+
[email protected](name="file-download-export", failure_exception_types=[workflow.NondeterminismError])
+class FileDownloadBatchExportWorkflow(PostHogWorkflow):
+ """Workflow to generate files for download from an S3 bucket.
+
+ The workflow works by executing what is essentially an S3 batch export, but
+ targeting one of our own buckets. Afterwards, the workflow generates file-download
+ models so that the files in our own bucket can be downloaded after generating a
+ pre-signed URL.
+ """
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> FileDownloadBatchExportInputs:
+ """Parse inputs from the management command CLI."""
+ loaded = json.loads(inputs[0])
+ return FileDownloadBatchExportInputs(**loaded)
+
+ @workflow.run
+ async def run(self, inputs: FileDownloadBatchExportInputs) -> FileDownloadBatchExportResult:
+ """Run the workflow.
+
+ Starts off with the same activities as an S3 batch export, but with some changes
+ to utilize our own buckets and credentials.
+
+ Ends with generating the necessary objects for later generating pre-signed URLs.
+
+ Notably, this workflow can be scheduled and ran outside of a schedule. So we
+ use the data bounds when they are set.
+ """
+ if inputs.data_interval_start and inputs.data_interval_end:
+ # Allow this workflow to be ran outside of a schedule
+ data_interval_end_dt = dt.datetime.fromisoformat(inputs.data_interval_end)
+ data_interval_start_dt = dt.datetime.fromisoformat(inputs.data_interval_start)
+ should_backfill_from_beginning = False
+ else:
+ is_backfill = inputs.get_is_backfill()
+ is_earliest_backfill = inputs.get_is_earliest_backfill()
+ data_interval_start_dt, data_interval_end_dt = get_data_interval(
+ inputs.interval, inputs.data_interval_end, inputs.timezone
+ )
+
+ should_backfill_from_beginning = is_backfill and is_earliest_backfill
+
+ interval_delta = data_interval_end_dt - data_interval_start_dt
+
+ if inputs.batch_export_run_id is not None:
+ run_id = str(inputs.batch_export_run_id)
+ else:
+ start_batch_export_run_inputs = StartBatchExportRunInputs(
+ team_id=inputs.team_id,
+ batch_export_id=inputs.batch_export_id,
+ data_interval_start=data_interval_start_dt.isoformat(),
+ data_interval_end=data_interval_end_dt.isoformat(),
+ exclude_events=inputs.exclude_events,
+ include_events=inputs.include_events,
+ backfill_id=inputs.backfill_details.backfill_id if inputs.backfill_details else None,
+ )
+ try:
+ run_id = await workflow.execute_activity(
+ start_batch_export_run,
+ start_batch_export_run_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=0,
+ non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
+ ),
+ )
+ except OverBillingLimitError:
+ return FileDownloadBatchExportResult(records_completed=0, bytes_exported=0)
+
+ export_inputs = ExportInputs(
+ batch_export=BatchExportInsertInputs(
+ team_id=inputs.team_id,
+ run_id=run_id,
+ batch_export_model=inputs.batch_export_model,
+ batch_export_id=inputs.batch_export_id,
+ exclude_events=inputs.exclude_events,
+ include_events=inputs.include_events,
+ 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(),
+ ),
+ s3_bucket=S3Bucket(
+ name=settings.BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET,
+ region=settings.BATCH_EXPORTS_FILE_DOWNLOAD_REGION,
+ ),
+ aws_role_arn=settings.BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN,
+ compression=inputs.compression,
+ file_format=inputs.file_format,
+ max_file_size_mb=inputs.max_file_size_mb,
+ )
+ result: S3BatchExportResult = await execute_batch_export_using_internal_stage(
+ export_to_file_download_bucket_with_temporary_credentials,
+ export_inputs, # type: ignore
+ interval=f"every {int(interval_delta.total_seconds())} seconds",
+ )
+
+ file_downloads = await workflow.execute_activity(
+ generate_file_downloads,
+ GenerateFileDownloadsInputs(
+ team_id=inputs.team_id,
+ batch_export_id=inputs.batch_export_id,
+ batch_export_run_id=run_id,
+ s3_bucket=S3Bucket(
+ name=settings.BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET,
+ region=settings.BATCH_EXPORTS_FILE_DOWNLOAD_REGION,
+ ),
+ keys=tuple(result.files_uploaded),
+ aws_role_arn=settings.BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ heartbeat_timeout=dt.timedelta(seconds=10),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=1),
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=0,
+ ),
+ )
+
+ return FileDownloadBatchExportResult(
+ records_completed=result.records_completed,
+ bytes_exported=result.bytes_exported,
+ file_downloads=file_downloads,
+ )
diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
index a0d04a9a4229..aab03b72e6db 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -120,6 +120,7 @@ class S3InsertInputs(BatchExportInsertInputs):
prefix: str
aws_access_key_id: str | None = None
aws_secret_access_key: str | None = None
+ aws_session_token: str | None = None
compression: str | None = None
encryption: str | None = None
kms_key_id: str | None = None
@@ -292,9 +293,14 @@ class S3BatchExportWorkflow(PostHogWorkflow):
return
+class S3BatchExportResult(BatchExportResult):
+ files_uploaded: list[str] = dataclasses.field(default_factory=list)
+
+
@activity.defn
@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)
-async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> BatchExportResult:
+async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchExportResult:
"""Activity to batch export data to a customer's S3.
This is a new version of the `insert_into_s3_activity` activity that reads data from our internal S3 stage
@@ -354,7 +360,7 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> BatchExp
inputs.data_interval_end or "END",
)
- return BatchExportResult(records_completed=0, bytes_exported=0)
+ return S3BatchExportResult(records_completed=0, bytes_exported=0)
record_batch_schema = pa.schema(
# NOTE: For some reason, some batches set non-nullable fields as non-nullable, whereas other
@@ -385,13 +391,20 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> BatchExp
max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,
)
- return await run_consumer_from_stage(
+ result = await run_consumer_from_stage(
queue=queue,
consumer=consumer,
producer_task=producer_task,
transformer=transformer,
json_columns=json_columns,
)
+ return S3BatchExportResult(
+ bytes_exported=result.bytes_exported,
+ records_completed=result.records_completed,
+ records_failed=result.records_failed,
+ error=result.error,
+ files_uploaded=consumer.files_uploaded,
+ )
class ConcurrentS3Consumer(Consumer):
@@ -417,6 +430,7 @@ class ConcurrentS3Consumer(Consumer):
file_format: str,
aws_access_key_id: str,
aws_secret_access_key: str,
+ aws_session_token: str | None = None,
kms_key_id: str | None = None,
max_file_size_mb: int | None = None,
compression: str | None = None,
@@ -451,6 +465,7 @@ class ConcurrentS3Consumer(Consumer):
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
+ self.aws_session_token = aws_session_token
self.kms_key_id = kms_key_id
self.endpoint_url = endpoint_url
self.use_virtual_style_addressing = use_virtual_style_addressing
@@ -499,6 +514,7 @@ class ConcurrentS3Consumer(Consumer):
max_file_size_mb=s3_inputs.max_file_size_mb,
aws_access_key_id=s3_inputs.aws_access_key_id,
aws_secret_access_key=s3_inputs.aws_secret_access_key,
+ aws_session_token=s3_inputs.aws_session_token,
kms_key_id=s3_inputs.kms_key_id,
endpoint_url=s3_inputs.endpoint_url,
use_virtual_style_addressing=s3_inputs.use_virtual_style_addressing,
@@ -530,6 +546,7 @@ class ConcurrentS3Consumer(Consumer):
region_name=self.region_name,
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
+ aws_session_token=self.aws_session_token,
endpoint_url=self.endpoint_url,
config=boto_config,
)
diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
index 21aaa70d68a5..c801227d4f4c 100644
--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py
+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
@@ -51,8 +51,9 @@ class _ComposedBatchExportInputsProtocol(typing.Protocol):
InputsType = typing.TypeVar("InputsType", bound=_BatchExportInputsProtocol)
ComposedInputsType = typing.TypeVar("ComposedInputsType", bound=_ComposedBatchExportInputsProtocol)
+BatchExportResultType = typing.TypeVar("BatchExportResultType", bound=BatchExportResult)
BatchExportInsertActivity = collections.abc.Callable[
- [InputsType | ComposedInputsType], collections.abc.Awaitable[BatchExportResult]
+ [InputsType | ComposedInputsType], collections.abc.Awaitable[BatchExportResultType]
]
INITIAL_RETRY_INTERVAL_SECONDS = 1
@@ -72,7 +73,7 @@ async def execute_batch_export_using_internal_stage(
override_start_to_close_timeout_seconds: int | None = None,
num_partitions: int | None = None,
is_workflows: bool = False,
-) -> None:
+) -> BatchExportResultType:
"""
This is the entrypoint for a new version of the batch export insert activity.
@@ -222,3 +223,5 @@ async def execute_batch_export_using_internal_stage(
non_retryable_error_types=["NotNullViolation", "IntegrityError"],
),
)
+
+ return result
diff --git a/products/batch_exports/backend/tests/temporal/README.md b/products/batch_exports/backend/tests/temporal/README.md
index 2a2e752e18ba..c12cd206466b 100644
--- a/products/batch_exports/backend/tests/temporal/README.md
+++ b/products/batch_exports/backend/tests/temporal/README.md
@@ -193,3 +193,34 @@ DEBUG=1 AZURE_STORAGE_CONNECTION_STRING='DefaultEndpointsProtocol=https;AccountN
AZURE_TEST_CONTAINER='<CONTAINER_NAME>' \
pytest products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_with_azure_account.py -v
```
+
+## Testing File Download batch exports
+
+File download batch exports are tested against a real AWS account. A real account is required as the batch export is essentially a wrapper around an S3 batch export, and we already have tests for S3 batch exports to ensure they work with and without an AWS account. The only parts that are left outside of the S3 batch export interact with AWS directly: Generating temporary credentials and checking S3 bucket status.
+
+PostHog has AWS playground accounts that we can leverage for our tests:
+
+1. Obtain an AWS playground account by following [this runbook](https://runbooks.posthog.com/aws/aws-playground)
+2. Configure your environment with the AWS playground's admin credentials. I recommend setting up SSO in your `~/.aws/config` so that credentials are automatically refreshed, logging in with SSO using `aws sso login --profile {profile_name}`, and then setting `AWS_PROFILE={profile_name}` in your environment before running the tests. Here is an example on how to configure this using `playground` as the `{profile_name}`), replace the variables with the details in the playground login page:
+
+ ```ini
+ [sso-session sso-playground]
+ sso_start_url = {SSO URL from playground account}
+ sso_region = {SSO region from playground account}
+ sso_registration_scopes = sso:account:access
+
+ [profile playground]
+ sso_session = sso-playground
+ sso_account_id = {Playground account ID}
+ sso_role_name = {PostHog Admin role}
+ region = us-east-1
+ ```
+
+3. Verify you did everything correctly by calling `aws sts get-caller-identity --profile {profile_name}`
+4. Run the tests:
+
+ ```bash
+ AWS_PROFILE={profile_name} DEBUG=1 pytest products/batch_exports/backend/tests/temporal/destinations/file_download/ -v
+ ```
+
+The tests fixtures will setup the necessary role and bucket for the tests to run, and also clean it up after the test is done.
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.py
new file mode 100644
index 000000000000..6fa27473a2c7
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/conftest.py
@@ -0,0 +1,150 @@
+import os
+import json
+import secrets
+
+import pytest
+
+import aioboto3
+import structlog
+import pytest_asyncio
+import botocore.exceptions
+
+from products.batch_exports.backend.tests.temporal.utils.s3 import delete_all_from_s3
+
+LOGGER = structlog.get_logger()
+TOKEN = secrets.token_hex(6)
+TEST_BUCKET_NAME = os.getenv("FILE_DOWNLOAD_TEST_BUCKET", f"test-file-downloads-{TOKEN}")
+TEST_ROLE = os.getenv("FILE_DOWNLOAD_TEST_ROLE", f"test-file-downloads-role-{TOKEN}")
+TEST_REGION = os.getenv("FILE_DOWNLOAD_TEST_BUCKET_REGION", "us-east-1")
+
+
[email protected](scope="module")
+def region() -> str:
+ return TEST_REGION
+
+
[email protected](scope="module")
+def bucket_name() -> str:
+ return TEST_BUCKET_NAME
+
+
[email protected](scope="module")
+def role_name() -> str:
+ return TEST_ROLE
+
+
+def compression(request) -> str | None:
+ try:
+ return request.param
+ except AttributeError:
+ return None
+
+
+def file_format(request) -> str:
+ try:
+ return request.param
+ except AttributeError:
+ return "Parquet"
+
+
+@pytest_asyncio.fixture(scope="module")
+async def session():
+ session = aioboto3.Session()
+ return session
+
+
+@pytest_asyncio.fixture(scope="module")
+async def s3_client(session):
+ """Manage an S3 client to interact with an S3 bucket.
+
+ Yields the client after assuming the test bucket exists. Upon resuming, we delete
+ the contents of the bucket under the key prefix we are testing.
+ """
+ async with session.client("s3") as s3_client:
+ yield s3_client
+
+
+@pytest_asyncio.fixture(scope="module")
+async def s3_bucket(bucket_name, s3_client, region):
+ try:
+ resp = await s3_client.create_bucket(
+ Bucket=bucket_name,
+ ACL="private",
+ )
+ except botocore.exceptions.ClientError:
+ raise pytest.skip("Could not setup S3 bucket")
+
+ yield bucket_name
+
+ try:
+ await delete_all_from_s3(s3_client, bucket_name, key_prefix="batch-exports")
+ await s3_client.delete_bucket(Bucket=bucket_name)
+ except Exception:
+ LOGGER.warning("Bucket clean-up failed", name=bucket_name, arn=resp["BucketArn"], exc_info=True)
+
+
+@pytest_asyncio.fixture(scope="module")
+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",
+ )
+
+ s3_policy = {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "BucketAccess",
+ "Effect": "Allow",
+ "Action": ["s3:ListBucket", "s3:GetBucketLocation"],
+ "Resource": f"arn:aws:s3:::{bucket_name}",
+ },
+ {
+ "Sid": "ObjectAccess",
+ "Effect": "Allow",
+ "Action": [
+ "s3:PutObject",
+ "s3:GetObject",
+ "s3:DeleteObject",
+ ],
+ "Resource": f"arn:aws:s3:::{bucket_name}/*",
+ },
+ ],
+ }
+ await iam.put_role_policy(
+ RoleName=role_name,
+ PolicyName="batch-export-s3-access",
+ PolicyDocument=json.dumps(s3_policy),
+ )
+
+ yield resp["Role"]["Arn"]
+
+ try:
+ resp = await iam.list_role_policies(RoleName=role_name)
+ for policy_name in resp.get("PolicyNames", []):
+ await iam.delete_role_policy(RoleName=role_name, PolicyName=policy_name)
+ await iam.delete_role(RoleName=role_name)
+
+ except Exception:
+ LOGGER.warning("Test role clean-up failed", name=TEST_ROLE, arn=resp["Role"]["Arn"], exc_info=True)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py
new file mode 100644
index 000000000000..7a8cf07fd19a
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py
@@ -0,0 +1,262 @@
+import uuid
+
+import pytest
+
+from django.test import override_settings
+
+from temporalio.testing._activity import ActivityEnvironment
+
+from posthog.batch_exports.models import BatchExportFileDownload, BatchExportRun
+from posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export
+
+from products.batch_exports.backend.service import BatchExportInsertInputs, BatchExportModel, BatchExportSchema
+from products.batch_exports.backend.temporal.destinations.file_download_batch_export import (
+ ExportInputs,
+ GenerateFileDownloadsInputs,
+ S3Bucket,
+ export_to_file_download_bucket_with_temporary_credentials,
+ generate_file_downloads,
+)
+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
+ COMPRESSION_EXTENSIONS,
+ FILE_FORMAT_EXTENSIONS,
+ SUPPORTED_COMPRESSIONS,
+ s3_default_fields,
+)
+from products.batch_exports.backend.temporal.pipeline.internal_stage import (
+ BatchExportInsertIntoInternalStageInputs,
+ insert_into_internal_stage_activity,
+)
+from products.batch_exports.backend.tests.temporal.destinations.s3.utils import (
+ TEST_S3_MODELS,
+ assert_clickhouse_records_in_s3,
+ has_valid_credentials,
+)
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.django_db,
+ pytest.mark.skipif(
+ not has_valid_credentials(),
+ reason="AWS credentials not set in environment",
+ ),
+]
+
+
[email protected]("compression", COMPRESSION_EXTENSIONS.keys(), indirect=True)
[email protected]("model", TEST_S3_MODELS)
[email protected]("file_format", FILE_FORMAT_EXTENSIONS.keys())
+async def test_export_to_file_download_bucket_puts_data_into_s3(
+ clickhouse_client,
+ activity_environment: ActivityEnvironment,
+ compression,
+ exclude_events,
+ file_format,
+ data_interval_start,
+ data_interval_end,
+ model: BatchExportModel | BatchExportSchema | None,
+ generate_test_data,
+ ateam,
+ s3_client,
+ s3_bucket,
+ aws_role_arn,
+ region,
+):
+ """Test that export_to_file_download_bucket_with_temporary_credentials exports data to S3.
+
+ The activity obtains temporary credentials via STS role assumption, constructs
+ S3InsertInputs, and delegates to insert_into_s3_activity_from_stage. We verify
+ the data ends up in the expected S3 location and matches what ClickHouse produces.
+ """
+ if compression and compression not in SUPPORTED_COMPRESSIONS[file_format]:
+ pytest.skip(f"Compression {compression} is not supported for file format {file_format}")
+
+ batch_export_schema: BatchExportSchema | None = None
+ batch_export_model: BatchExportModel | None = None
+ if isinstance(model, BatchExportModel):
+ batch_export_model = model
+ elif model is not None:
+ batch_export_schema = model
+
+ batch_export_id = str(uuid.uuid4())
+ run_id = str(uuid.uuid4())
+ prefix = (
+ f"batch-exports/{batch_export_id}/{run_id}/{data_interval_start.isoformat()}-{data_interval_end.isoformat()}"
+ )
+
+ stage_folder = await activity_environment.run(
+ insert_into_internal_stage_activity,
+ BatchExportInsertIntoInternalStageInputs(
+ team_id=ateam.pk,
+ batch_export_id=batch_export_id,
+ data_interval_start=data_interval_start.isoformat(),
+ data_interval_end=data_interval_end.isoformat(),
+ exclude_events=exclude_events,
+ include_events=None,
+ run_id=run_id,
+ backfill_details=None,
+ batch_export_model=batch_export_model,
+ batch_export_schema=batch_export_schema,
+ destination_default_fields=s3_default_fields(),
+ ),
+ )
+
+ export_inputs = ExportInputs(
+ batch_export=BatchExportInsertInputs(
+ team_id=ateam.pk,
+ run_id=run_id,
+ stage_folder=stage_folder,
+ batch_export_model=batch_export_model,
+ batch_export_schema=batch_export_schema,
+ batch_export_id=batch_export_id,
+ exclude_events=exclude_events,
+ include_events=None,
+ data_interval_start=data_interval_start.isoformat(),
+ data_interval_end=data_interval_end.isoformat(),
+ destination_default_fields=s3_default_fields(),
+ ),
+ s3_bucket=S3Bucket(
+ name=s3_bucket,
+ region=region,
+ ),
+ aws_role_arn=aws_role_arn,
+ compression=compression,
+ file_format=file_format,
+ )
+
+ with override_settings(BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES=5 * 1024**2):
+ result = await activity_environment.run(
+ export_to_file_download_bucket_with_temporary_credentials,
+ export_inputs,
+ )
+
+ assert result.error is None
+ assert result.records_completed is not None
+ assert result.records_completed > 0
+ assert result.bytes_exported is not None
+ assert result.bytes_exported > 0
+
+ events_to_export_created, persons_to_export_created = generate_test_data
+ assert (
+ result.records_completed == len(events_to_export_created)
+ or result.records_completed == len(persons_to_export_created)
+ or result.records_completed
+ == len([event for event in events_to_export_created if event["properties"] is not None])
+ or (isinstance(model, BatchExportModel) and model.name == "sessions" and 1 <= result.records_completed <= 2)
+ )
+
+ sort_key = "uuid"
+ if isinstance(model, BatchExportModel) and model.name == "persons":
+ sort_key = "person_id"
+ elif isinstance(model, BatchExportModel) and model.name == "sessions":
+ sort_key = "session_id"
+
+ await assert_clickhouse_records_in_s3(
+ s3_compatible_client=s3_client,
+ clickhouse_client=clickhouse_client,
+ bucket_name=s3_bucket,
+ key_prefix=prefix,
+ team_id=ateam.pk,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ batch_export_model=model,
+ exclude_events=exclude_events,
+ include_events=None,
+ compression=compression,
+ file_format=file_format,
+ backfill_details=None,
+ sort_key=sort_key,
+ )
+
+
+async def test_generate_file_downloads_creates_file_download_records(
+ activity_environment: ActivityEnvironment,
+ ateam,
+ s3_client,
+ s3_bucket,
+ temporal_client,
+ aws_role_arn,
+ region,
+):
+ """Test that generate_file_downloads creates BatchExportFileDownload records for exported S3 keys.
+
+ We first upload test files directly to S3, then run the generate_file_downloads
+ activity which should call HeadObject on each key and create corresponding
+ BatchExportFileDownload records in the database.
+ """
+ batch_export_id = str(uuid.uuid4())
+
+ # Create a batch export in the DB since BatchExportFileDownload has a FK to it.
+ batch_export = await acreate_batch_export(
+ team_id=ateam.pk,
+ name="test-file-download-export",
+ destination_data={
+ # TODO: Make this a file-download batch export
+ "type": "FileDownload",
+ "config": {
+ "file_format": "Parquet",
+ },
+ },
+ interval="hour",
+ )
+ run = await BatchExportRun.objects.acreate(
+ batch_export=batch_export,
+ status="Completed",
+ data_interval_start="2024-01-01T00:00:00",
+ data_interval_end="2024-01-01T01:00:00",
+ )
+
+ prefix = f"batch-exports/{batch_export_id}/{run.id}"
+ test_keys = [
+ f"{prefix}/2024-01-01T00:00:00-2024-01-01T01:00:00-0.parquet",
+ f"{prefix}/2024-01-01T00:00:00-2024-01-01T01:00:00-1.parquet",
+ ]
+ for key in test_keys:
+ await s3_client.put_object(Bucket=s3_bucket, Key=key, Body=b"test-data")
+
+ try:
+ inputs = GenerateFileDownloadsInputs(
+ team_id=ateam.pk,
+ batch_export_id=batch_export_id,
+ batch_export_run_id=str(run.id),
+ s3_bucket=S3Bucket(name=s3_bucket, region=region),
+ aws_role_arn=aws_role_arn,
+ keys=tuple(test_keys),
+ )
+
+ file_download_ids = await activity_environment.run(
+ generate_file_downloads,
+ inputs,
+ )
+
+ assert len(file_download_ids) == len(test_keys)
+
+ file_downloads = [
+ file_download
+ async for file_download in BatchExportFileDownload.objects.filter(
+ team_id=ateam.pk, batch_export_run_id=run.id
+ )
+ ]
+ assert len(file_downloads) == len(test_keys)
+
+ created_keys = {fd.key for fd in file_downloads}
+ assert created_keys == set(test_keys)
+
+ for fd in file_downloads:
+ assert fd.team_id == ateam.pk
+ assert fd.batch_export_run_id == run.id
+ assert fd.id in file_download_ids
+
+ # Running again with the same keys should be idempotent (returns existing IDs).
+ file_download_ids_again = await activity_environment.run(
+ generate_file_downloads,
+ inputs,
+ )
+
+ assert set(file_download_ids_again) == set(file_download_ids)
+
+ count = await BatchExportFileDownload.objects.filter(team_id=ateam.pk, batch_export_run_id=run.id).acount()
+ assert count == len(test_keys)
+
+ finally:
+ await adelete_batch_export(batch_export, temporal_client)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py
new file mode 100644
index 000000000000..05e693e15ca9
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py
@@ -0,0 +1,196 @@
+import uuid
+import datetime as dt
+
+import pytest
+
+from django.conf import settings
+from django.test import override_settings
+
+import pytest_asyncio
+from temporalio.common import RetryPolicy
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.batch_exports.models import BatchExportFileDownload
+from posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export, afetch_batch_export_runs
+
+from products.batch_exports.backend.service import BatchExportModel, FileDownloadBatchExportInputs
+from products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_run
+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.pipeline.internal_stage import insert_into_internal_stage_activity
+from products.batch_exports.backend.tests.temporal.destinations.s3.utils import (
+ assert_clickhouse_records_in_s3,
+ has_valid_credentials,
+)
+from products.batch_exports.backend.tests.temporal.utils.workflow import fail_on_application_error
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.django_db,
+ pytest.mark.skipif(
+ not has_valid_credentials(),
+ reason="AWS credentials not set in environment",
+ ),
+]
+
+
+@pytest_asyncio.fixture
+async def file_download_batch_export(
+ ateam,
+ interval,
+ exclude_events,
+ temporal_client,
+ compression,
+ file_format,
+):
+ destination_data = {
+ "type": "FileDownload",
+ "config": {
+ "file_format": file_format,
+ "compression": compression,
+ },
+ }
+
+ batch_export_data = {
+ "name": "my-file-download-destination",
+ "destination": destination_data,
+ "interval": interval,
+ }
+
+ batch_export = await acreate_batch_export(
+ team_id=ateam.pk,
+ name=batch_export_data["name"],
+ destination_data=batch_export_data["destination"],
+ interval=batch_export_data["interval"],
+ )
+
+ yield batch_export
+
+ await adelete_batch_export(batch_export, temporal_client)
+
+
[email protected]("interval", ["hour"], indirect=True)
[email protected]("model", [BatchExportModel(name="events", schema=None)])
[email protected]("exclude_events", [None], indirect=True)
+async def test_file_download_workflow_exports_data(
+ clickhouse_client,
+ s3_client,
+ ateam,
+ file_download_batch_export,
+ s3_bucket,
+ interval,
+ compression,
+ exclude_events,
+ file_format,
+ data_interval_start,
+ data_interval_end,
+ model: BatchExportModel,
+ generate_test_data,
+ aws_role_arn,
+ region,
+):
+ """Test FileDownloadBatchExportWorkflow end-to-end.
+
+ The workflow should:
+ 1. Start a batch export run.
+ 2. Insert data into the internal stage.
+ 3. Export data from the internal stage to the file download S3 bucket using temporary credentials.
+ 4. Generate file download records for the exported files.
+ 5. Complete with the correct records_completed count.
+ """
+ batch_export_id = str(file_download_batch_export.id)
+
+ workflow_id = str(uuid.uuid4())
+ inputs = FileDownloadBatchExportInputs(
+ team_id=ateam.pk,
+ batch_export_id=batch_export_id,
+ data_interval_end=data_interval_end.isoformat(),
+ data_interval_start=data_interval_start.isoformat(),
+ interval=interval,
+ batch_export_model=model,
+ file_format=file_format,
+ compression=compression,
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
+ async with Worker(
+ activity_environment.client,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ workflows=[FileDownloadBatchExportWorkflow],
+ activities=[
+ start_batch_export_run,
+ finish_batch_export_run,
+ insert_into_internal_stage_activity,
+ export_to_file_download_bucket_with_temporary_credentials,
+ generate_file_downloads,
+ ],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ with (
+ fail_on_application_error(),
+ override_settings(
+ BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET=s3_bucket,
+ BATCH_EXPORTS_FILE_DOWNLOAD_ROLE_ARN=aws_role_arn,
+ BATCH_EXPORTS_FILE_DOWNLOAD_REGION=region,
+ ),
+ ):
+ await activity_environment.client.execute_workflow(
+ FileDownloadBatchExportWorkflow.run,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ execution_timeout=dt.timedelta(seconds=30),
+ )
+
+ runs = await afetch_batch_export_runs(batch_export_id=batch_export_id)
+ assert len(runs) == 1
+
+ run = runs[0]
+ assert run.status == "Completed"
+ assert run.records_completed is not None
+ assert run.records_completed > 0
+
+ events_to_export_created, _ = generate_test_data
+ assert run.records_completed == len(events_to_export_created)
+
+ prefix = (
+ f"batch-exports/{batch_export_id}/{run.id}/{data_interval_start.isoformat()}-{data_interval_end.isoformat()}"
+ )
+ await assert_clickhouse_records_in_s3(
+ s3_compatible_client=s3_client,
+ clickhouse_client=clickhouse_client,
+ bucket_name=s3_bucket,
+ key_prefix=prefix,
+ team_id=ateam.pk,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ batch_export_model=model,
+ exclude_events=exclude_events,
+ compression=compression,
+ file_format=file_format,
+ sort_key="uuid",
+ )
+
+ # Verify BatchExportFileDownload records were created by the workflow.
+ file_downloads = [
+ file_download
+ async for file_download in BatchExportFileDownload.objects.filter(team_id=ateam.pk, batch_export_run_id=run.id)
+ ]
+ assert len(file_downloads) > 0
+
+ # Each file download should reference a valid S3 key under the expected prefix.
+ for fd in file_downloads:
+ assert fd.team_id == ateam.pk
+ assert fd.batch_export_run_id == run.id
+ assert fd.key.startswith(f"batch-exports/{batch_export_id}/")
+ assert fd.created_at is not None
+
+ # The S3 keys referenced by file downloads should correspond to actual objects in the bucket.
+ for fd in file_downloads:
+ response = await s3_client.head_object(Bucket=s3_bucket, Key=fd.key)
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
diff --git a/products/batch_exports/backend/tests/temporal/utils/s3.py b/products/batch_exports/backend/tests/temporal/utils/s3.py
index f71d0e0b4d50..d6b44e2a6079 100644
--- a/products/batch_exports/backend/tests/temporal/utils/s3.py
+++ b/products/batch_exports/backend/tests/temporal/utils/s3.py
@@ -28,10 +28,10 @@ async def read_parquet_from_s3(
) -> list:
credentials = s3_client._request_signer._credentials # type: ignore
endpoint_url = s3_client.meta.endpoint_url
-
s3 = fs.S3FileSystem(
access_key=credentials.access_key,
secret_key=credentials.secret_key,
+ session_token=credentials.token,
endpoint_override=endpoint_url,
)
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index 333c14b2156d..c10d0eae18d0 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -41,6 +41,7 @@ export const NullEnumApi = {} as const
* `Workflows` - Workflows
* `HTTP` - Http
* `NoOp` - Noop
+ * `FileDownload` - File Download
*/
export type BatchExportDestinationTypeEnumApi =
(typeof BatchExportDestinationTypeEnumApi)[keyof typeof BatchExportDestinationTypeEnumApi]
@@ -56,6 +57,7 @@ export const BatchExportDestinationTypeEnumApi = {
Workflows: 'Workflows',
Http: 'HTTP',
NoOp: 'NoOp',
+ FileDownload: 'FileDownload',
} as const
/**
@@ -73,7 +75,8 @@ export interface BatchExportDestinationApi {
* `AzureBlob` - Azure Blob
* `Workflows` - Workflows
* `HTTP` - Http
-* `NoOp` - Noop */
+* `NoOp` - Noop
+* `FileDownload` - File Download */
type: BatchExportDestinationTypeEnumApi
/** A JSON field to store all configuration parameters required to access a BatchExportDestination. */
config?: unknown
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index 9d8956e2893b..3a07f2ccac1c 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -44,12 +44,13 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -372,12 +373,13 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -455,12 +457,13 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -543,12 +546,13 @@ export const BatchExportsPauseCreateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -626,12 +630,13 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -712,12 +717,13 @@ export const BatchExportsUnpauseCreateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
@@ -795,12 +801,13 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod
'Workflows',
'HTTP',
'NoOp',
+ 'FileDownload',
])
.describe(
- '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ '* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
)
.describe(
- 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop'
+ 'A choice of supported BatchExportDestination types.\n\n* `S3` - S3\n* `Snowflake` - Snowflake\n* `Postgres` - Postgres\n* `Redshift` - Redshift\n* `BigQuery` - Bigquery\n* `Databricks` - Databricks\n* `AzureBlob` - Azure Blob\n* `Workflows` - Workflows\n* `HTTP` - Http\n* `NoOp` - Noop\n* `FileDownload` - File Download'
),
config: zod
.unknown()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d6b7e0ea3f01..8b4343185348 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -6574,6 +6574,7 @@ export namespace Schemas {
* `Workflows` - Workflows
* `HTTP` - Http
* `NoOp` - Noop
+ * `FileDownload` - File Download
*/
export type BatchExportDestinationTypeEnum = typeof BatchExportDestinationTypeEnum[keyof typeof BatchExportDestinationTypeEnum];
@@ -6589,6 +6590,7 @@ export namespace Schemas {
Workflows: 'Workflows',
Http: 'HTTP',
NoOp: 'NoOp',
+ FileDownload: 'FileDownload',
} as const;
/**
@@ -6606,7 +6608,8 @@ export namespace Schemas {
* `AzureBlob` - Azure Blob
* `Workflows` - Workflows
* `HTTP` - Http
- * `NoOp` - Noop */
+ * `NoOp` - Noop
+ * `FileDownload` - File Download */
type: BatchExportDestinationTypeEnum;
/** A JSON field to store all configuration parameters required to access a BatchExportDestination. */
config?: unknown;