: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(batch-exports): Support nullable on-demand run bounds (#101764)
Tomás Farías Santana57947c153cba
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 9ff3bc6a4c4a..3af26240f4c6 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -254,7 +254,7 @@ batch_export_runs: _BatchExportRunsTable = _BatchExportRunsTable(),"data_interval_end": DateTimeDatabaseField(name="data_interval_end",- nullable=False,+ nullable=True,description="End of the time range covered by the run",),"status": StringDatabaseField(diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.pyindex 71a25d910c31..5a48cf329107 100644--- a/posthog/settings/batch_exports.py+++ b/posthog/settings/batch_exports.py@@ -177,6 +177,9 @@ BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS: int = get_from_env(BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME: int = get_from_env("BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME", 900, type_cast=int) # 15 minutes (deliberately under the file-download stage timeout of 20 minutes)+BATCH_EXPORT_HOGQL_ON_DEMAND_MAIN_TIMEOUT_SECONDS: int = get_from_env(+ "BATCH_EXPORT_HOGQL_ON_DEMAND_MAIN_TIMEOUT_SECONDS", 6 * 60 * 60, type_cast=int+)BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE: int = get_from_env("BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE", 50 * 1024**3, type_cast=int) # 50GiB (rather arbitrary for now, can always increase later)diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex d6ab3671bbd3..91a88b9461a8 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -162,6 +162,15 @@ def validate_date_input(date_input: Any, batch_export: BatchExport) -> dt.dateticlass BatchExportRunSerializer(serializers.ModelSerializer):"""Serializer for a BatchExportRun model."""+ # Underlying model can be null for on demand batch exports. But scheduled+ # batch exports always have a data_interval_end given by the schedule+ # itself (even if that isn't used by the underlying HogQL query). This+ # narrows the API contract so any consumers don't have to deal with+ # nullable data_interval_end.+ data_interval_end = serializers.DateTimeField(+ required=True, allow_null=False, help_text="The end of the data interval."+ )+class Meta:model = BatchExportRunfields = "__all__"diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.pyindex 2f2dfeba23fd..c394d3d63ded 100644--- a/products/batch_exports/backend/debug/debugger.py+++ b/products/batch_exports/backend/debug/debugger.py@@ -344,7 +344,13 @@ class BatchExportsDebugger:folder = get_base_s3_staging_folder(batch_export_run.parent.id,batch_export_run.data_interval_start.isoformat() if batch_export_run.data_interval_start else None,- batch_export_run.data_interval_end.isoformat(),+ batch_export_run.data_interval_end.isoformat() if batch_export_run.data_interval_end is not None else None,+ run_id=(+ str(batch_export_run.id)+ if batch_export_run.batch_export_on_demand_id is not None+ and (batch_export_run.data_interval_start is None or batch_export_run.data_interval_end is None)+ else None+ ),)file_selector = fs.FileSelector(base_dir=f"{settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET}/{folder}", recursive=True@@ -389,6 +395,10 @@ class BatchExportsDebugger:self,batch_export_run: BatchExportRun,) -> collections.abc.Generator[pa.RecordBatch]:+ if batch_export_run.data_interval_end is None or (+ batch_export_run.batch_export_on_demand_id is not None and batch_export_run.data_interval_start is None+ ):+ raise ValueError("Query debugging requires explicit interval bounds; inspect the run's S3 data instead")team_id = batch_export_run.parent.team.idfull_range = (batch_export_run.data_interval_start, batch_export_run.data_interval_end)parameters: dict[str, typing.Any] = {diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.pyindex 1a52754afb69..1e52d7ab69df 100644--- a/products/batch_exports/backend/facade/contracts.py+++ b/products/batch_exports/backend/facade/contracts.py@@ -77,7 +77,7 @@ class BatchExportRunSummary:status: strlatest_error: str | Nonedata_interval_start: dt.datetime | None- data_interval_end: dt.datetime+ data_interval_end: dt.datetime | Nonefinished_at: dt.datetime | Nonecreated_at: dt.datetimelast_updated_at: dt.datetimediff --git a/products/batch_exports/backend/migrations/0007_alter_batchexportrun_data_interval_end.py b/products/batch_exports/backend/migrations/0007_alter_batchexportrun_data_interval_end.pynew file mode 100644index 000000000000..52b2d2fa3406--- /dev/null+++ b/products/batch_exports/backend/migrations/0007_alter_batchexportrun_data_interval_end.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0006_alter_batchexport_team_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="batchexportrun",+ name="data_interval_end",+ field=models.DateTimeField(help_text="The end of the data interval.", null=True),+ ),+ ]diff --git a/products/batch_exports/backend/migrations/max_migration.txt b/products/batch_exports/backend/migrations/max_migration.txtindex 0843f31317d3..48ad53c773c9 100644--- a/products/batch_exports/backend/migrations/max_migration.txt+++ b/products/batch_exports/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_alter_batchexport_team_and_more+0007_alter_batchexportrun_data_interval_enddiff --git a/products/batch_exports/backend/models/batch_export.py b/products/batch_exports/backend/models/batch_export.pyindex 896029c077dd..f5d682b668aa 100644--- a/products/batch_exports/backend/models/batch_export.py+++ b/products/batch_exports/backend/models/batch_export.py@@ -228,7 +228,7 @@ class BatchExportRun(UUIDTModel):)latest_error = models.TextField(null=True, help_text="The latest error that occurred during this run.")data_interval_start = models.DateTimeField(help_text="The start of the data interval.", null=True)- data_interval_end = models.DateTimeField(help_text="The end of the data interval.")+ data_interval_end = models.DateTimeField(help_text="The end of the data interval.", null=True)cursor = models.TextField(null=True, help_text="An opaque cursor that may be used to resume.")created_at = models.DateTimeField(auto_now_add=True,@@ -264,9 +264,13 @@ class BatchExportRun(UUIDTModel):parent = self.parentif isinstance(parent, BatchExport):+ if self.data_interval_end is None:+ raise ValueError("Scheduled batch export runs require data_interval_end to compute a workflow ID")return f"{parent.id}-{self.data_interval_end:%Y-%m-%dT%H:%M:%S}Z"if isinstance(parent, BatchExportOnDemand):+ if self.data_interval_start is None or self.data_interval_end is None:+ return f"{parent.id}-{self.id}"return (f"{parent.id}-{self.data_interval_start:%Y-%m-%dT%H:%M:%S}Z-{self.data_interval_end:%Y-%m-%dT%H:%M:%S}Z")diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 67d339948373..4f4fe26fd8b7 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -187,7 +187,7 @@ def _field_is_type(f: Field, target: type) -> bool:return False-@dataclass(kw_only=True)+@dataclass(frozen=False, kw_only=True)class BaseBatchExportInputs:"""Base class for all batch export inputs containing common fields.@@ -340,7 +340,7 @@ class S3CompatibleBatchExportInputs(S3FamilyBaseInputs):use_virtual_style_addressing: bool = False-@dataclass(kw_only=True)+@dataclass(frozen=False, kw_only=True)class FileDownloadBatchExportInputs(BaseBatchExportInputs):"""Inputs for a file download batch export workflow.@@ -360,6 +360,8 @@ class FileDownloadBatchExportInputs(BaseBatchExportInputs):max_file_size_mb: int | None = Nonecompression: str | None = Noneexpires_in_seconds: int = 3600+ main_activity_timeout_seconds: int | None = None+ stage_activity_timeout_seconds: int | None = None@dataclass(frozen=False, kw_only=True)@@ -975,8 +977,8 @@ async def start_batch_export_workflow(def start_file_download_batch_export(batch_export: BatchExportOnDemand,workflow_id: str,- data_interval_start: dt.datetime,- data_interval_end: dt.datetime,+ data_interval_start: dt.datetime | None,+ data_interval_end: dt.datetime | None,batch_export_model: BatchExportModel,batch_export_run_id: UUID | None = None,compression: str | None = None,@@ -985,18 +987,28 @@ def start_file_download_batch_export(include_events: list[str] | None = None,exclude_events: list[str] | None = None,) -> None:+ incomplete_interval = data_interval_start is None or data_interval_end is None+ if incomplete_interval and (batch_export_model.name != "hogql" or batch_export_run_id is None):+ raise ValueError("Only on-demand HogQL exports can omit interval bounds")inputs = FileDownloadBatchExportInputs(batch_export_id=batch_export.id,batch_export_model=batch_export_model,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(),+ data_interval_start=data_interval_start.isoformat() if data_interval_start is not None else None,+ data_interval_end=data_interval_end.isoformat() if data_interval_end is not None else None,compression=compression,file_format=format,max_file_size_mb=max_size_mb,include_events=include_events,exclude_events=exclude_events,+ # Persist timeout choices in the workflow input so configuration changes do not affect replay.+ main_activity_timeout_seconds=settings.BATCH_EXPORT_HOGQL_ON_DEMAND_MAIN_TIMEOUT_SECONDS+ if incomplete_interval+ else None,+ stage_activity_timeout_seconds=settings.BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME + 300+ if incomplete_interval+ else None,)temporal = sync_connect()@@ -1389,7 +1401,8 @@ async def afetch_last_run_records_completed(return Noneif matching_interval_duration is not None:start = run["data_interval_start"]- last_interval_duration = run["data_interval_end"] - start if start is not None else None+ end = run["data_interval_end"]+ last_interval_duration = end - start if start is not None and end is not None else Noneif last_interval_duration != matching_interval_duration:return Nonereturn run["records_completed"]@@ -1419,13 +1432,13 @@ async def afetch_batch_export_runs_in_range(return [run async for run in queryset]-@dataclass(kw_only=True)+@dataclass(frozen=False, kw_only=True)class BatchExportInsertInputs:"""Base dataclass for batch export insert inputs containing common fields."""team_id: intdata_interval_start: str | None- data_interval_end: str+ data_interval_end: str | Noneexclude_events: list[str] | None = Noneinclude_events: list[str] | None = Nonerun_id: str | None = Nonediff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex cb53f092044a..e35e68dc164a 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -813,7 +813,7 @@ def make_internal_events_payload(batch_export_run_id: str,batch_export_name: str,data_interval_start: dt.datetime | None,- data_interval_end: dt.datetime,+ data_interval_end: dt.datetime | None,destination_type: str,rows_exported: int,error: str | None,@@ -830,7 +830,7 @@ def make_internal_events_payload("batch_export_run_id": batch_export_run_id,"batch_export_name": batch_export_name,"data_interval_start": data_interval_start.isoformat() if data_interval_start is not None else None,- "data_interval_end": data_interval_end.isoformat(),+ "data_interval_end": data_interval_end.isoformat() if data_interval_end is not None else None,"destination_type": destination_type,}diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.pyindex 255d56f61e45..37ae7f90390d 100644--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py@@ -105,6 +105,7 @@ def _is_authorization_failure_response_error(err: HttpResponseError) -> bool:@dataclasses.dataclass(frozen=False, kw_only=True)class AzureBlobInsertInputs(BatchExportInsertInputs):+ data_interval_end: strcontainer_name: strintegration_id: intprefix: str = ""diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex 639f09b9da03..3f00c6eb3b7f 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -1387,6 +1387,7 @@ def _get_merge_settings(class BigQueryInsertInputs(BatchExportInsertInputs):"""Inputs for BigQuery."""+ data_interval_end: strdataset_id: strtable_id: strproject_id: str | None = Nonediff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex aab73795a19c..0a2e2669d1b2 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -193,7 +193,7 @@ class DatabricksIncompatibleSchemaError(DatabricksOperationError):)[email protected](kw_only=True)[email protected](frozen=False, kw_only=True)class DatabricksInsertInputs(BatchExportInsertInputs):"""Inputs for Databricks.@@ -214,6 +214,7 @@ class DatabricksInsertInputs(BatchExportInsertInputs):NOTE: currently we don't expose this in the frontend as we're assuming all users would want to use this."""+ data_interval_end: strintegration_id: inthttp_path: strcatalog: strdiff --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 2606eda80ad3..2743ce9ca1e7 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@@ -17,7 +17,7 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger, get_write_only_logger-from products.batch_exports.backend.models.batch_export import BatchExportFileDownload+from products.batch_exports.backend.models.batch_export import BatchExportFileDownload, BatchExportRunfrom products.batch_exports.backend.service import (AWSCredentials,BatchExportInsertInputs,@@ -38,6 +38,7 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export importinsert_into_s3_from_stage,s3_default_fields,)+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stagefrom products.batch_exports.backend.temporal.pipeline.types import BatchExportResultfrom products.batch_exports.backend.temporal.utils import handle_non_retryable_errors@@ -47,6 +48,7 @@ EXTERNAL_LOGGER = get_logger()FILE_DOWNLOAD_PREFIX = ("batch-exports/{batch_export_id}/{batch_export_run_id}/{{data_interval_start}}-{{data_interval_end}}")+FILE_DOWNLOAD_UNBOUNDED_PREFIX = "batch-exports/{batch_export_id}/{batch_export_run_id}"# This export runs the same S3 write as a batch export, so it fails the same way. It has no# Integration, so the integration errors an S3 batch export can raise are not reachable here.@@ -181,20 +183,20 @@ FileDownloadIds = list[uuid.UUID]@activity.defnasync 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():+ 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+credentials = await _get_temporary_credentials_to_head_object(inputs.s3_bucket.name,f"batch-exports/{inputs.batch_export_id}/{inputs.batch_export_run_id}",@@ -245,47 +247,64 @@ async def export_to_file_download_bucket_with_temporary_credentials(inputs: ExpoAfter obtaining the credentials, we simply run the same function as an S3 batchexport 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- )+ async with Heartbeater():+ prefix = FILE_DOWNLOAD_PREFIX.format(+ batch_export_id=inputs.batch_export.batch_export_id, batch_export_run_id=inputs.batch_export.run_id+ )+ file_name_prefix = None+ if inputs.batch_export.on_demand and (+ inputs.batch_export.data_interval_start is None or inputs.batch_export.data_interval_end is None+ ):+ run_id = inputs.batch_export.run_id+ if run_id is None:+ raise MissingRequiredInputsError("An on-demand file download requires a run_id")+ prefix = FILE_DOWNLOAD_UNBOUNDED_PREFIX.format(+ batch_export_id=inputs.batch_export.batch_export_id, batch_export_run_id=run_id+ )+ run = await BatchExportRun.objects.aget(+ id=run_id, batch_export_on_demand__team_id=inputs.batch_export.team_id+ )+ file_name_prefix = f"export-{run.created_at.astimezone(dt.UTC):%Y-%m-%dT%H-%M-%SZ}"- refresh_credentials = functools.partial(- _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,- )+ refresh_credentials = functools.partial(+ _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,- 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,- # These files live in a PostHog bucket, expire on a lifecycle rule, and are reached through- # a key stored on `BatchExportFileDownload`. No customer pipeline matches on their names, so- # there is nothing to grandfather and they always use the standard extension.- legacy_parquet_extension=False,- )- # Minting the first credentials calls AWS STS, and this activity heartbeats every 10 seconds,- # so the call runs under the heartbeater rather than ahead of it.- async with Heartbeater():+ 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,+ 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,+ # These files live in a PostHog bucket, expire on a lifecycle rule, and are reached through+ # a key stored on `BatchExportFileDownload`. No customer pipeline matches on their names, so+ # there is nothing to grandfather and they always use the standard extension.+ legacy_parquet_extension=False,+ on_demand=inputs.batch_export.on_demand,+ )+ # Minting the first credentials calls AWS STS, and this activity heartbeats every 10 seconds,+ # so the call runs under the heartbeater rather than ahead of it.resolved_credentials = ResolvedS3Credentials(credentials=await refresh_credentials(),refresh_using=refresh_credentials,)- return await insert_into_s3_from_stage(s3_insert_inputs, resolved_credentials)+ return await insert_into_s3_from_stage(+ s3_insert_inputs, resolved_credentials, file_name_prefix=file_name_prefix+ )@dataclasses.dataclass@@ -321,27 +340,40 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):Notably, this workflow can be scheduled and ran outside of a schedule. So weuse the data bounds when they are set."""- if inputs.data_interval_start and inputs.data_interval_end:+ on_demand = inputs.batch_export_run_id is not None+ incomplete_interval = inputs.data_interval_start is None or inputs.data_interval_end is None+ data_interval: DataInterval | None = None+ if on_demand and incomplete_interval:+ assert inputs.batch_export_model is not None and inputs.batch_export_model.name == "hogql", (+ "Only on-demand HogQL exports can omit interval bounds"+ )+ interval = None+ data_interval_start = inputs.data_interval_start+ data_interval_end = inputs.data_interval_end+ elif inputs.data_interval_start and inputs.data_interval_end:# Allow this workflow to be ran outside of a scheduledata_interval = DataInterval(start=dt.datetime.fromisoformat(inputs.data_interval_start),end=dt.datetime.fromisoformat(inputs.data_interval_end),)should_backfill_from_beginning = False+ interval = f"every {int((data_interval.end - data_interval.start).total_seconds())} seconds"+ data_interval_start = data_interval.start.isoformat()+ data_interval_end = data_interval.end.isoformat()else:is_backfill = inputs.get_is_backfill()is_earliest_backfill = inputs.get_is_earliest_backfill()data_interval = get_data_interval(inputs.interval, inputs.data_interval_end, inputs.timezone)should_backfill_from_beginning = is_backfill and is_earliest_backfill+ interval = f"every {int((data_interval.end - data_interval.start).total_seconds())} seconds"+ data_interval_start = data_interval.start.isoformat() if not should_backfill_from_beginning else None+ data_interval_end = data_interval.end.isoformat()- interval_delta = data_interval.end - data_interval.start-- on_demand = Falseif inputs.batch_export_run_id is not None:run_id = str(inputs.batch_export_run_id)- on_demand = Trueelse:+ assert data_interval is not Nonestart_batch_export_run_inputs = StartBatchExportRunInputs(team_id=inputs.team_id,batch_export_id=inputs.batch_export_id,@@ -376,8 +408,8 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):batch_export_id=inputs.batch_export_id,exclude_events=inputs.exclude_events,include_events=inputs.include_events,- data_interval_start=data_interval.start.isoformat() if not should_backfill_from_beginning else None,- data_interval_end=data_interval.end.isoformat(),+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,destination_default_fields=s3_default_fields(),on_demand=on_demand,),@@ -393,7 +425,9 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):result = 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",+ interval=interval,+ main_activity_timeout_seconds=inputs.main_activity_timeout_seconds,+ stage_activity_timeout_seconds=inputs.stage_activity_timeout_seconds,)# A failed run gets no download links, even where some files did reach the bucket. Thediff --git a/products/batch_exports/backend/temporal/destinations/http_batch_export.py b/products/batch_exports/backend/temporal/destinations/http_batch_export.pyindex 44150c7cdc04..d831a40cca49 100644--- a/products/batch_exports/backend/temporal/destinations/http_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/http_batch_export.py@@ -116,10 +116,11 @@ class HeartbeatDetails:return HeartbeatDetails(last_uploaded_timestamp)[email protected](kw_only=True)[email protected](frozen=False, kw_only=True)class HttpInsertInputs(BatchExportInsertInputs):"""Inputs for HTTP insert activity."""+ data_interval_end: strurl: strtoken: strdiff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.pyindex f2deb0b9203c..34107bfb2597 100644--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py@@ -183,6 +183,7 @@ class _PostgreSQLClientInputsProtocol(typing.Protocol):class PostgresInsertInputs(BatchExportInsertInputs):"""Inputs for Postgres."""+ data_interval_end: strdatabase: strtable_name: strschema: str = "public"diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.pyindex 6295392ba343..571915bb161e 100644--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py@@ -69,6 +69,7 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export imports3_client,)from products.batch_exports.backend.temporal.destinations.utils import get_absolute_key_prefix+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stagefrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stagefrom products.batch_exports.backend.temporal.pipeline.producer import Producer@@ -1271,6 +1272,9 @@ async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs)the Redshift-specific properties_data_type to indicate the type of JSON-likefields."""+ if inputs.batch_export.data_interval_end is None:+ raise MissingRequiredInputsError("Scheduled Redshift exports require a data_interval_end")+bind_contextvars(team_id=inputs.batch_export.team_id,destination="Redshift",@@ -1673,6 +1677,9 @@ async def _get_s3_bucket_aws_credentials(Otherwise, credentials are long lived and the second returned parameter isNone."""+ if inputs.batch_export.data_interval_end is None:+ raise MissingRequiredInputsError("Scheduled Redshift exports require a data_interval_end")+credentials = inputs.copy.s3_bucket.credentialsif isinstance(credentials, IntegrationID):credentials = await _resolve_aws_s3_integration(credentials, inputs.batch_export.team_id)@@ -1713,6 +1720,9 @@ async def _resolve_copy_authorization(staged files: a customer role ARN from an integration cannot be passed as`IAM_ROLE` in the COPY statement, since it is not attached to the cluster."""+ if inputs.batch_export.data_interval_end is None:+ raise MissingRequiredInputsError("Scheduled Redshift exports require a data_interval_end")+authorization = inputs.copy.authorizationif not isinstance(authorization, IntegrationID):return authorization, None@@ -1782,6 +1792,9 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInpthe Redshift-specific properties_data_type to indicate the type of JSON-likefields."""+ if inputs.batch_export.data_interval_end is None:+ raise MissingRequiredInputsError("Scheduled Redshift exports require a data_interval_end")+bind_contextvars(team_id=inputs.batch_export.team_id,destination="Redshift",diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.pyindex d12e7fd9cb9b..0432bcc5f791 100644--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py@@ -62,6 +62,7 @@ from products.batch_exports.backend.temporal.destinations.utils import (get_manifest_key,get_object_key,)+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.metrics import Attributes, CumulativeTimer, ExecutionTimeRecorderfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stagefrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stage@@ -219,7 +220,7 @@ class S3InsertInputs(BatchExportInsertInputs):legacy_parquet_extension: bool = True-def get_s3_key_from_inputs(inputs: S3InsertInputs, file_number: int = 0) -> str:+def get_s3_key_from_inputs(inputs: S3InsertInputs, file_number: int = 0, file_name_prefix: str | None = None) -> str:return get_object_key(prefix=inputs.prefix,data_interval_start=inputs.data_interval_start,@@ -230,6 +231,7 @@ def get_s3_key_from_inputs(inputs: S3InsertInputs, file_number: int = 0) -> str:legacy_parquet_extension=inputs.legacy_parquet_extension,file_number=file_number,include_file_number=bool(inputs.max_file_size_mb),+ file_name_prefix=file_name_prefix,)@@ -600,6 +602,8 @@ async def s3_client(async def _resolve_credentials_from_integration(inputs: S3InsertInputs) -> ResolvedS3Credentials:"""Resolve an export's S3 credentials from the Integration it links to."""+ if inputs.data_interval_end is None:+ raise MissingRequiredInputsError("Scheduled S3 exports require a data_interval_end")if inputs.integration_id is None:raise MissingIntegrationError(inputs.batch_export_id)@@ -702,7 +706,7 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEasync def insert_into_s3_from_stage(- inputs: S3InsertInputs, resolved_credentials: ResolvedS3Credentials+ inputs: S3InsertInputs, resolved_credentials: ResolvedS3Credentials, file_name_prefix: str | None = None) -> S3BatchExportResult:"""Write data staged in our internal S3 stage to a target S3 bucket.@@ -731,7 +735,7 @@ async def insert_into_s3_from_stage("Batch exporting range %s - %s to S3: %s",inputs.data_interval_start or "START",inputs.data_interval_end or "END",- get_s3_key_from_inputs(inputs),+ get_s3_key_from_inputs(inputs, file_name_prefix=file_name_prefix),)queue = RecordBatchQueue(max_size_bytes=settings.BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES)@@ -792,6 +796,7 @@ async def insert_into_s3_from_stage(part_size=settings.BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES,max_concurrent_uploads=settings.BATCH_EXPORT_S3_MAX_CONCURRENT_UPLOADS,checksum_algorithm="CRC64NVME" if endpoint_url is None else None,+ file_name_prefix=file_name_prefix,)result = await run_consumer_from_stage(@@ -831,7 +836,7 @@ class ConcurrentS3Consumer(Consumer):region_name: str,prefix: str,data_interval_start: str | None,- data_interval_end: str,+ data_interval_end: str | None,batch_export_model: BatchExportModel | None,file_format: str,checksum_algorithm: str | None = None,@@ -843,6 +848,7 @@ class ConcurrentS3Consumer(Consumer):legacy_parquet_extension: bool = True,part_size: int = 50 * 1024 * 1024, # 50MB partsmax_concurrent_uploads: int = 5,+ file_name_prefix: str | None = None,):super().__init__(model=batch_export_model.name if batch_export_model else "events")@@ -852,6 +858,7 @@ class ConcurrentS3Consumer(Consumer):self.data_interval_start = data_interval_startself.data_interval_end = data_interval_end+ self.file_name_prefix = file_name_prefixself.batch_export_model = batch_export_modelself.checksum_algorithm = checksum_algorithm@@ -898,6 +905,7 @@ class ConcurrentS3Consumer(Consumer):part_size: int = 50 * 1024 * 1024,max_concurrent_uploads: int = 5,checksum_algorithm: str | None = None,+ file_name_prefix: str | None = None,):return cls(s3_client=s3_client,@@ -917,6 +925,7 @@ class ConcurrentS3Consumer(Consumer):legacy_parquet_extension=s3_inputs.legacy_parquet_extension,part_size=part_size,max_concurrent_uploads=max_concurrent_uploads,+ file_name_prefix=file_name_prefix,)async def finalize_file(self):@@ -1122,6 +1131,7 @@ class ConcurrentS3Consumer(Consumer):legacy_parquet_extension=self.legacy_parquet_extension,file_number=self.current_file_index,include_file_number=bool(self.max_file_size_mb),+ file_name_prefix=self.file_name_prefix,)async def _start_new_file(self):@@ -1233,7 +1243,11 @@ class ConcurrentS3Consumer(Consumer):# containing the list of files. This is used to check if the export is complete.if self.max_file_size_mb:manifest_key = get_manifest_key(- self.prefix, self.data_interval_start, self.data_interval_end, self.batch_export_model+ self.prefix,+ self.data_interval_start,+ self.data_interval_end,+ self.batch_export_model,+ file_name_prefix=self.file_name_prefix,)self.external_logger.info("Uploading manifest file '%s'", manifest_key)await self.upload_manifest_file(diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.pyindex b6c02caa3103..6a8b733248f1 100644--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py@@ -489,6 +489,8 @@ class SnowflakeInsertInputs(BatchExportInsertInputs):Temporal payload."""+ data_interval_end: str+database: strwarehouse: strschema: strdiff --git a/products/batch_exports/backend/temporal/destinations/utils.py b/products/batch_exports/backend/temporal/destinations/utils.pyindex a2044bce5c1b..ad231ccce4d9 100644--- a/products/batch_exports/backend/temporal/destinations/utils.py+++ b/products/batch_exports/backend/temporal/destinations/utils.py@@ -8,6 +8,7 @@ from products.batch_exports.backend.temporal.destinations.constants import (COMPRESSION_EXTENSIONS,FILE_FORMAT_EXTENSIONS,)+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorEXTERNAL_LOGGER = get_logger("EXTERNAL")@@ -62,9 +63,17 @@ def get_absolute_key_prefix(def get_manifest_key(- prefix: str, data_interval_start: str | None, data_interval_end: str, batch_export_model: BatchExportModel | None+ prefix: str,+ data_interval_start: str | None,+ data_interval_end: str | None,+ batch_export_model: BatchExportModel | None,+ file_name_prefix: str | None = None,) -> str:"""Generate manifest file key."""+ if file_name_prefix is not None and (data_interval_start is None or data_interval_end is None):+ return posixpath.join(prefix, f"{file_name_prefix}_manifest.json")+ if data_interval_end is None:+ raise MissingRequiredInputsError("Provide a filename prefix for an export without an end bound.")key_prefix = get_key_prefix(prefix, data_interval_start, data_interval_end, batch_export_model)return posixpath.join(key_prefix, f"{data_interval_start}-{data_interval_end}_manifest.json")@@ -89,18 +98,25 @@ def _get_compression_extension(file_format: str, compression: str | None, legacydef get_object_key(prefix: str,data_interval_start: str | None,- data_interval_end: str,+ data_interval_end: str | None,batch_export_model: BatchExportModel | None,file_format: str,compression: str | None = None,legacy_parquet_extension: bool = False,file_number: int = 0,include_file_number: bool = False,+ file_name_prefix: str | None = None,) -> str:"""Generate object storage key for batch export files."""- key_prefix = get_key_prefix(prefix, data_interval_start, data_interval_end, batch_export_model)-- base_file_name = f"{data_interval_start}-{data_interval_end}"+ if file_name_prefix is not None and (data_interval_start is None or data_interval_end is None):+ key_prefix = prefix+ base_file_name = file_name_prefix+ include_file_number = True+ else:+ if data_interval_end is None:+ raise MissingRequiredInputsError("Provide a filename prefix for an export without an end bound.")+ key_prefix = get_key_prefix(prefix, data_interval_start, data_interval_end, batch_export_model)+ base_file_name = f"{data_interval_start}-{data_interval_end}"if include_file_number:base_file_name = f"{base_file_name}-{file_number}"diff --git a/products/batch_exports/backend/temporal/errors.py b/products/batch_exports/backend/temporal/errors.pynew file mode 100644index 000000000000..f37d0901dd35--- /dev/null+++ b/products/batch_exports/backend/temporal/errors.py@@ -0,0 +1,9 @@+class MissingRequiredInputsError(RuntimeError):+ """We are unable to recover due to some input being missing.++ This exists to signal an impossible runtime state. At the time of writing,+ it should not be possible to get into this state, but if we ever see this,+ it's likely a signal of a bug.+ """++ passdiff --git a/products/batch_exports/backend/temporal/metrics.py b/products/batch_exports/backend/temporal/metrics.pyindex 2eefe63c3fe1..49edab1d36e7 100644--- a/products/batch_exports/backend/temporal/metrics.py+++ b/products/batch_exports/backend/temporal/metrics.py@@ -177,12 +177,18 @@ class _BatchExportsMetricsActivityInboundInterceptor(ActivityInboundInterceptor)try:data_interval_start = input.args[0].data_interval_startdata_interval_end = input.args[0].data_interval_end- interval = get_interval_from_bounds(data_interval_start, data_interval_end)+ interval = get_interval_from_bounds(+ data_interval_start, data_interval_end, on_demand=getattr(input.args[0], "on_demand", False)+ )except AttributeError:try:data_interval_start = input.args[0].batch_export.data_interval_startdata_interval_end = input.args[0].batch_export.data_interval_end- interval = get_interval_from_bounds(data_interval_start, data_interval_end)+ interval = get_interval_from_bounds(+ data_interval_start,+ data_interval_end,+ on_demand=getattr(input.args[0].batch_export, "on_demand", False),+ )except Exception:data_interval_start = Nonedata_interval_end = None@@ -452,9 +458,17 @@ def log_query_duration(def get_interval_from_bounds(- data_interval_start: dt.datetime | None | str, data_interval_end: dt.datetime | str+ data_interval_start: dt.datetime | None | str,+ data_interval_end: dt.datetime | str | None,+ *,+ on_demand: bool = False,) -> str | None:"""Calculate the interval for a batch export based on its bounds."""+ if on_demand:+ return "on_demand"+ if data_interval_end is None:+ return None+if isinstance(data_interval_start, str):try:data_interval_start = dt.datetime.fromisoformat(data_interval_start)diff --git a/products/batch_exports/backend/temporal/monitoring.py b/products/batch_exports/backend/temporal/monitoring.pyindex 741e5b27c44a..9f1eb0da77b9 100644--- a/products/batch_exports/backend/temporal/monitoring.py+++ b/products/batch_exports/backend/temporal/monitoring.py@@ -212,6 +212,7 @@ async def fetch_exported_event_counts(inputs: FetchExportedEventCountsInputs) ->count=run.records_completed or 0,)for run in runs+ if run.data_interval_end is not None]diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex fb4493a8706f..40e9dab078e1 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -40,7 +40,10 @@ LOGGER = get_write_only_logger(__name__)class _BatchExportInputsProtocol(typing.Protocol):team_id: intdata_interval_start: str | None- data_interval_end: str++ @property+ def data_interval_end(self) -> str | None: ...+exclude_events: list[str] | None = Noneinclude_events: list[str] | None = Nonerun_id: str | None = None@@ -87,12 +90,31 @@ class IntervalConfig:failure_check_window: int-def _get_config_for_interval(interval: str, override_start_to_close: dt.timedelta) -> IntervalConfig:+def _get_config_for_interval(+ interval: str | None,+ override_start_to_close: dt.timedelta,+ *,+ main_activity_timeout_seconds: int | None = None,+ stage_activity_timeout_seconds: int | None = None,+) -> IntervalConfig:"""Derive a run's activity timeouts and failure-check window from its interval.Raises:ValueError: If the interval is not one this function knows how to configure."""+ if interval is None:+ assert (+ main_activity_timeout_seconds is not None+ and main_activity_timeout_seconds > 0+ and stage_activity_timeout_seconds is not None+ and stage_activity_timeout_seconds > 0+ ), "Exports without an interval require positive activity timeouts"+ return IntervalConfig(+ main_start_to_close=max(dt.timedelta(seconds=main_activity_timeout_seconds), override_start_to_close),+ stage_start_to_close=dt.timedelta(seconds=stage_activity_timeout_seconds),+ failure_check_window=50,+ )+if interval == "hour":# TODO - we should reduce this to 1 hour once we are more confident about hitting 1 hour SLAs.# TODO: Review timeouts for internal stage activity.@@ -231,13 +253,15 @@ async def _finish_run(finish_inputs: FinishBatchExportRunInputs, details: Workflasync def execute_batch_export_using_internal_stage(activity: BatchExportInsertActivity[BatchExportResultType],inputs: BatchExportInputs,- interval: str,+ interval: str | None,maximum_attempts: int = 0,initial_retry_interval_seconds: int = INITIAL_RETRY_INTERVAL_SECONDS,maximum_retry_interval_seconds: int = DEFAULT_MAX_RETRY_INTERVAL_SECONDS,maximum_stage_retry_interval_seconds: int = DEFAULT_MAX_STAGE_RETRY_INTERVAL_SECONDS,override_start_to_close_timeout_seconds: int | None = None,is_workflows: bool = False,+ main_activity_timeout_seconds: int | None = None,+ stage_activity_timeout_seconds: int | None = None,) -> BatchExportResult:"""Run one batch export: stage its data, write it to the destination, record how it went.@@ -297,8 +321,15 @@ async def execute_batch_export_using_internal_stage(heartbeat_timeout_seconds = settings.BATCH_EXPORT_HEARTBEAT_TIMEOUT_SECONDSheartbeat_timeout = dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None+ if interval is None:+ assert model_name == "hogql" and batch_export_inputs.on_demand, (+ "Only on-demand HogQL exports can omit the interval"+ )interval_config = _get_config_for_interval(- interval, dt.timedelta(seconds=override_start_to_close_timeout_seconds or 0)+ interval,+ dt.timedelta(seconds=override_start_to_close_timeout_seconds or 0),+ main_activity_timeout_seconds=main_activity_timeout_seconds,+ stage_activity_timeout_seconds=stage_activity_timeout_seconds,)finish_inputs = FinishBatchExportRunInputs(diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 94c044f28ae5..6c36219c002c 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -45,6 +45,7 @@ from posthog.temporal.common.clickhouse import (from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryErrorfrom products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.service import (BackfillDetails,@@ -54,6 +55,7 @@ from products.batch_exports.backend.service import (afetch_last_run_records_completed,)from products.batch_exports.backend.temporal.batch_exports import default_fields+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.filters import InvalidFilterError, compose_filters_clausefrom products.batch_exports.backend.temporal.metrics import log_query_durationfrom products.batch_exports.backend.temporal.pipeline.query_ranges import (@@ -62,7 +64,11 @@ from products.batch_exports.backend.temporal.pipeline.query_ranges import (wait_for_delta_past_data_interval_end,)from products.batch_exports.backend.temporal.pipeline.types import BatchExportError-from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_model+from products.batch_exports.backend.temporal.record_batch_model import (+ HogQLQueryRecordBatchModel,+ RecordBatchModel,+ resolve_batch_exports_model,+)from products.batch_exports.backend.temporal.sql.common import get_s3_function_callfrom products.batch_exports.backend.temporal.sql.events import (EXPORT_TO_S3_FROM_DISTRIBUTED_EVENTS_RECENT,@@ -83,11 +89,9 @@ LOGGER = get_write_only_logger()TRACER = trace.get_tracer(__name__)-class DataIntervalEndInFutureError(Exception):- """Raised when a batch export's 'data_interval_end' is after now."""-- def __init__(self, data_interval_end: dt.datetime) -> None:- super().__init__(f"The provided 'data_interval_end' ({data_interval_end.isoformat()}) is in the future")+class DataIntervalInFutureError(Exception):+ def __init__(self, bound: typing.Literal["data_interval_start", "data_interval_end"], value: dt.datetime) -> None:+ super().__init__(f"The provided '{bound}' ({value.isoformat()}) is in the future. Choose a date in the past.")class HogQLQueryResourceLimitExceededError(Exception):@@ -106,9 +110,10 @@ class HogQLQueryResourceLimitExceededError(Exception):# run without failing the activity. This mirrors how the destination activities treat their own# non-retryable errors (see `handle_non_retryable_errors`), and prevents us being alerted on user errors.NON_RETRYABLE_ERRORS: tuple[type[Exception], ...] = (- DataIntervalEndInFutureError,+ DataIntervalInFutureError,HogQLQueryResourceLimitExceededError,InvalidFilterError,+ UnsupportedHogQLQueryError,)@@ -283,7 +288,7 @@ class BatchExportInsertIntoInternalStageInputs:team_id: intbatch_export_id: strdata_interval_start: str | None- data_interval_end: str+ data_interval_end: str | Noneexclude_events: list[str] | None = Noneinclude_events: list[str] | None = Nonerun_id: str | None = None@@ -332,27 +337,30 @@ async def insert_into_internal_stage_activity(Heartbeater(),set_status_to_running_task(run_id=inputs.run_id),):- _, record_batch_model, model_name, fields, filters, extra_query_parameters = await database_sync_to_async(- resolve_batch_exports_model- )(- inputs.team_id,- inputs.batch_export_model,- inputs.batch_export_schema,- inputs.batch_export_id,- is_backfill=inputs.backfill_details is not None,- )data_interval_start = (- dt.datetime.fromisoformat(inputs.data_interval_start) if inputs.data_interval_start else None+ dt.datetime.fromisoformat(inputs.data_interval_start) if inputs.data_interval_start is not None else None+ )+ data_interval_end = (+ dt.datetime.fromisoformat(inputs.data_interval_end) if inputs.data_interval_end is not None else None)- data_interval_end = dt.datetime.fromisoformat(inputs.data_interval_end)full_range = (data_interval_start, data_interval_end)+ if data_interval_end is None and not inputs.on_demand:+ raise MissingRequiredInputsError("Scheduled batch exports require data_interval_end")++ staging_run_id = None+ if inputs.on_demand and (data_interval_start is None or data_interval_end is None):+ if inputs.run_id is None:+ raise MissingRequiredInputsError("On-demand batch exports with missing interval bounds require run_id")+ staging_run_id = inputs.run_id+attempt_number = activity.info().attempts3_staging_folder = get_s3_staging_folder(batch_export_id=inputs.batch_export_id,data_interval_start=inputs.data_interval_start,data_interval_end=inputs.data_interval_end,attempt_number=attempt_number,+ run_id=staging_run_id,)num_partitions = await compute_num_partitions(@@ -364,6 +372,20 @@ async def insert_into_internal_stage_activity(logger.info("Computed staging partitions", num_partitions=num_partitions)try:+ (+ _,+ record_batch_model,+ model_name,+ fields,+ filters,+ extra_query_parameters,+ ) = await database_sync_to_async(resolve_batch_exports_model)(+ inputs.team_id,+ inputs.batch_export_model,+ inputs.batch_export_schema,+ inputs.batch_export_id,+ is_backfill=inputs.backfill_details is not None,+ )records_total = await _stage_query_results(inputs,record_batch_model=record_batch_model,@@ -374,6 +396,7 @@ async def insert_into_internal_stage_activity(full_range=full_range,s3_staging_folder=s3_staging_folder,num_partitions=num_partitions,+ run_id=staging_run_id,)except NON_RETRYABLE_ERRORS as e:logger.warning("Staging data failed with a non-retryable error", error=str(e))@@ -394,9 +417,10 @@ async def _stage_query_results(fields: list[BatchExportField] | None,filters: list[dict[str, str | list[str] | None]] | None,extra_query_parameters: dict[str, typing.Any] | None,- full_range: tuple[dt.datetime | None, dt.datetime],+ full_range: tuple[dt.datetime | None, dt.datetime | None],s3_staging_folder: S3StagingFolder,num_partitions: int,+ run_id: str | None = None,) -> int | None:"""Build this run's query and write its results into the internal S3 staging area.@@ -406,13 +430,15 @@ async def _stage_query_results(query_or_model: str | RecordBatchModel = record_batch_modelquery_parameters: dict[str, typing.Any] = {}else:+ if full_range[1] is None or inputs.data_interval_end is None:+ raise MissingRequiredInputsError("Fixed batch export models require data_interval_end")query_or_model, query_parameters = await _get_query(model_name=model_name,backfill_details=inputs.backfill_details,team_id=inputs.team_id,batch_export_id=inputs.batch_export_id,s3_staging_folder_url=s3_staging_folder.url,- full_range=full_range,+ full_range=(full_range[0], full_range[1]),data_interval_start=inputs.data_interval_start,data_interval_end=inputs.data_interval_end,fields=fields,@@ -436,6 +462,7 @@ async def _stage_query_results(data_interval_end=inputs.data_interval_end,s3_staging_folder_url=s3_staging_folder.url,num_partitions=num_partitions,+ run_id=run_id,)except ClickHouseError as e:_raise_on_hogql_resource_limit_error(e, model_name)@@ -445,7 +472,7 @@ async def _stage_query_results(async def compute_num_partitions(batch_export_id: str,data_interval_start: dt.datetime | None,- data_interval_end: dt.datetime,+ data_interval_end: dt.datetime | None,on_demand: bool = False,) -> int:"""Choose how many staging files (partitions) to write for this run.@@ -474,7 +501,7 @@ async def compute_num_partitions(# Without the current interval's bounds we can't match the previous run's frequency, so don't risk# sizing off a differently-sized interval (e.g. an unbounded backfill) -> fall back to the default.- if data_interval_start is None:+ if data_interval_start is None or data_interval_end is None:return static_defaultinterval_duration = data_interval_end - data_interval_start@@ -642,17 +669,32 @@ async def _get_query(return query, parameters-def get_base_s3_staging_folder(batch_export_id: str, data_interval_start: str | None, data_interval_end: str) -> str:+def get_base_s3_staging_folder(+ batch_export_id: str,+ data_interval_start: str | None,+ data_interval_end: str | None,+ run_id: str | None = None,+) -> str:"""Get the base S3 staging folder for a given batch export."""subfolder = "batch-exports"+ if run_id is not None:+ return f"{subfolder}/{batch_export_id}/runs/{run_id}"+ if data_interval_end is None:+ raise MissingRequiredInputsError("A staging folder requires data_interval_end or run_id")return f"{subfolder}/{batch_export_id}/{data_interval_start}-{data_interval_end}"def get_s3_staging_folder(- batch_export_id: str, data_interval_start: str | None, data_interval_end: str, attempt_number: int+ batch_export_id: str,+ data_interval_start: str | None,+ data_interval_end: str | None,+ attempt_number: int,+ run_id: str | None = None,) -> S3StagingFolder:"""Get the S3 staging folder for a given batch export and attempt number."""- base_s3_staging_folder = get_base_s3_staging_folder(batch_export_id, data_interval_start, data_interval_end)+ base_s3_staging_folder = get_base_s3_staging_folder(+ batch_export_id, data_interval_start, data_interval_end, run_id=run_id+ )folder = f"{base_s3_staging_folder}/attempt_{attempt_number}"url = _get_clickhouse_s3_staging_folder_url(folder)return S3StagingFolder(folder=folder, url=url)@@ -678,14 +720,15 @@ def _get_clickhouse_s3_staging_folder_url(folder: str) -> str:async def _write_batch_export_record_batches_to_internal_stage(query_or_model: str | RecordBatchModel,- full_range: tuple[dt.datetime | None, dt.datetime],+ full_range: tuple[dt.datetime | None, dt.datetime | None],query_parameters: dict[str, typing.Any],team_id: int,batch_export_id: str,data_interval_start: str | None,- data_interval_end: str,+ data_interval_end: str | None,s3_staging_folder_url: str,num_partitions: int | None = None,+ run_id: str | None = None,) -> int | None:"""Write record batches to our own internal S3 staging area.@@ -708,11 +751,20 @@ async def _write_batch_export_record_batches_to_internal_stage(delta = dt.timedelta(minutes=1)interval_start, interval_end = full_range- if _is_local_dev_or_test() is False and interval_end > dt.datetime.now(dt.UTC):+ if _is_local_dev_or_test() is False:# Some tests create data in the future, so we do not check this.- raise DataIntervalEndInFutureError(interval_end)+ now = dt.datetime.now(dt.UTC)+ if interval_start is not None and interval_start > now:+ raise DataIntervalInFutureError("data_interval_start", interval_start)+ if interval_end is not None and interval_end > now:+ raise DataIntervalInFutureError("data_interval_end", interval_end)- if not isinstance(query_or_model, RecordBatchModel) or query_or_model.wait_for_data_interval_end:+ if interval_end is None and not isinstance(query_or_model, HogQLQueryRecordBatchModel):+ raise MissingRequiredInputsError("Fixed batch export models and raw SQL queries require data_interval_end")++ if interval_end is not None and (+ not isinstance(query_or_model, RecordBatchModel) or query_or_model.wait_for_data_interval_end+ ):with TRACER.start_as_current_span("batch_export.stage.wait_for_delta"):await wait_for_delta_past_data_interval_end(interval_end, delta)@@ -738,7 +790,8 @@ async def _write_batch_export_record_batches_to_internal_stage(query_parameters["interval_start"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")else:query_parameters["interval_start"] = None- query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")+ if interval_end is not None:+ query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")if isinstance(query_or_model, RecordBatchModel):query, query_parameters = await query_or_model.as_insert_into_s3_query_with_parameters(@@ -757,6 +810,7 @@ async def _write_batch_export_record_batches_to_internal_stage(batch_export_id=batch_export_id,data_interval_start=data_interval_start,data_interval_end=data_interval_end,+ run_id=run_id,)# First delete any existing files in the staging folder.# We technically don't need to do this, since the Temporal activity attempt number is used in the S3 key,diff --git a/products/batch_exports/backend/temporal/pipeline/producer.py b/products/batch_exports/backend/temporal/pipeline/producer.pyindex 3b5d08c452ea..093a931027cf 100644--- a/products/batch_exports/backend/temporal/pipeline/producer.py+++ b/products/batch_exports/backend/temporal/pipeline/producer.py@@ -12,6 +12,7 @@ from opentelemetry import traceimport posthog.temporal.common.asyncpa as asyncpafrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.metrics import CumulativeTimerfrom products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder, get_s3_clientfrom products.batch_exports.backend.temporal.queue import RecordBatchQueue@@ -76,7 +77,7 @@ class Producer:queue: RecordBatchQueue,batch_export_id: str,data_interval_start: str | None,- data_interval_end,+ data_interval_end: str | None,max_record_batch_size_bytes: int = 0,min_records_per_batch: int = 100,# TODO: after deployment, make this required@@ -101,13 +102,15 @@ class Producer:queue: RecordBatchQueue,batch_export_id: str,data_interval_start: str | None,- data_interval_end: str,+ data_interval_end: str | None,max_record_batch_size_bytes: int = 0,min_records_per_batch: int = 100,stage_folder: str | None = None,):# TODO: after deployment, remove the fallback behaviour.if stage_folder is None:+ if data_interval_end is None:+ raise MissingRequiredInputsError("An explicit stage_folder is required without a data_interval_end")stage_folder = get_base_s3_staging_folder(batch_export_id=batch_export_id,data_interval_start=data_interval_start,diff --git a/products/batch_exports/backend/temporal/pipeline/query_ranges.py b/products/batch_exports/backend/temporal/pipeline/query_ranges.pyindex 775ad551e068..202071ce0a29 100644--- a/products/batch_exports/backend/temporal/pipeline/query_ranges.py+++ b/products/batch_exports/backend/temporal/pipeline/query_ranges.py@@ -6,9 +6,9 @@ from django.conf import settingsfrom products.batch_exports.backend.service import BackfillDetails-def is_5_min_batch_export(full_range: tuple[dt.datetime | None, dt.datetime]) -> bool:+def is_5_min_batch_export(full_range: tuple[dt.datetime | None, dt.datetime | None]) -> bool:start_at, end_at = full_range- if start_at:+ if start_at is not None and end_at is not None:return (end_at - start_at) == dt.timedelta(seconds=300)return Falsediff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex ae8ec488fa36..998d713fcb69 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -28,6 +28,7 @@ from products.batch_exports.backend.hogql_source import (serialize_batch_export_query,)from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.metrics import log_query_durationfrom products.batch_exports.backend.temporal.sql.common import (BatchExportQuerySettings,@@ -40,7 +41,7 @@ LOGGER = get_write_only_logger()Query = strQueryParameters = dict[str, typing.Any]-BatchExportDateRange = tuple[dt.datetime | None, dt.datetime]+BatchExportDateRange = tuple[dt.datetime | None, dt.datetime | None]def _as_clickhouse_request_settings(query_settings: HogQLQuerySettings) -> dict[str, str]:@@ -98,7 +99,7 @@ class RecordBatchModel(abc.ABC):@abc.abstractmethoddef get_hogql_query(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> ast.SelectQuery | ast.SelectSetQuery:"""Return the HogQL query to export, scoped to the given data interval."""raise NotImplementedError@@ -113,7 +114,7 @@ class RecordBatchModel(abc.ABC):return {}async def _print_query(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime, output_format: str | None+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None, output_format: str | None) -> tuple[str, QueryParameters]:"""Transpile the model's HogQL query to ClickHouse SQL, returning it with its parameters."""hogql_query = self.get_hogql_query(data_interval_start, data_interval_end)@@ -133,7 +134,7 @@ class RecordBatchModel(abc.ABC):return printed, context.valuesasync def as_query_with_parameters(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> tuple[Query, QueryParameters]:"""Produce a printed query and any necessary ClickHouse query parameters."""return await self._print_query(data_interval_start, data_interval_end, output_format="ArrowStream")@@ -141,7 +142,7 @@ class RecordBatchModel(abc.ABC):async def as_insert_into_s3_query_with_parameters(self,data_interval_start: dt.datetime | None,- data_interval_end: dt.datetime,+ data_interval_end: dt.datetime | None,s3_folder: str,credentials: AWSKeyPair | None,num_partitions: int,@@ -171,9 +172,11 @@ class SessionsRecordBatchModel(RecordBatchModel):self.is_backfill = is_backfilldef get_hogql_query(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> ast.SelectQuery:"""Return the HogQLQuery used for the sessions model."""+ if data_interval_end is None:+ raise MissingRequiredInputsError("The sessions model requires data_interval_end")hogql_query = clone_expr(SELECT_FROM_SESSIONS_HOGQL)team_id_filter = ast.CompareOperation(@@ -371,7 +374,7 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):self.hogql_query = hogql_querydef get_hogql_query(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> ast.SelectQuery | ast.SelectSetQuery:"""Return the parsed HogQL query used for this model.@@ -381,7 +384,7 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):return parse_hogql_select_for_batch_export(self.hogql_query)def get_count_hogql_query(- self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime+ self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime | None) -> ast.SelectQuery:"""Return a HogQL query counting the rows this model would export."""return ast.SelectQuery(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.pyindex be6701cd151b..c17962fa2b88 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py@@ -806,6 +806,7 @@ class TestFileDownloadHogQL:).aget(id=response.json()["id"])assert run.data_interval_start == run.data_interval_end+ assert run.data_interval_end is not Noneassert before <= run.data_interval_end <= afteron_demand = run.batch_export_on_demandassert on_demand is not None@@ -874,6 +875,13 @@ class TestFileDownloadHogQL:await asyncio.sleep(2)assert files is not None and len(files) == 1+ run = await BatchExportRun.objects.aget(id=run_id, batch_export_on_demand__team_id=team.pk)+ if run.data_interval_start is None or run.data_interval_end is None:+ file_download = await BatchExportFileDownload.objects.aget(id=files[0], team_id=team.pk)+ assert file_download.key == (+ f"batch-exports/{run.batch_export_on_demand_id}/{run.id}/"+ f"export-{run.created_at.astimezone(dt.UTC):%Y-%m-%dT%H-%M-%SZ}-0.parquet"+ )response = await async_client.get(f"/api/projects/{team.pk}/file_download_batch_exports/{run_id}/download/{files[0]}",)diff --git a/products/batch_exports/backend/tests/temporal/destinations/test_utils.py b/products/batch_exports/backend/tests/temporal/destinations/test_utils.pyindex c50aa050f891..6cae2e9968ed 100644--- a/products/batch_exports/backend/tests/temporal/destinations/test_utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/test_utils.py@@ -2,8 +2,12 @@ import datetime as dtimport pytest-from products.batch_exports.backend.temporal.destinations.s3_batch_export import S3InsertInputs-from products.batch_exports.backend.temporal.destinations.utils import get_object_key, get_query_timeout+from products.batch_exports.backend.temporal.destinations.s3_batch_export import S3InsertInputs, get_s3_key_from_inputs+from products.batch_exports.backend.temporal.destinations.utils import (+ get_manifest_key,+ get_object_key,+ get_query_timeout,+)@pytest.mark.parametrize(@@ -248,3 +252,40 @@ def test_get_object_key(inputs, expected):include_file_number=inputs.max_file_size_mb is not None,)assert result == expected+++ "data_interval_start,data_interval_end,expected_name",+ [+ (None, None, "export-2023-01-01T00-00-00Z"),+ ("2023-01-01T00:00:00+00:00", None, "export-2023-01-01T00-00-00Z"),+ (None, "2023-01-01T01:00:00+00:00", "export-2023-01-01T00-00-00Z"),+ (+ "2023-01-01T00:00:00+00:00",+ "2023-01-01T01:00:00+00:00",+ "2023-01-01T00:00:00+00:00-2023-01-01T01:00:00+00:00",+ ),+ ],+)+def test_run_scoped_keys(data_interval_start: str | None, data_interval_end: str | None, expected_name: str) -> None:+ inputs = S3InsertInputs(+ bucket_name="test",+ region="test",+ team_id=1,+ prefix="batch-exports/export-123/run-123",+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ file_format="Parquet",+ compression="gzip",+ max_file_size_mb=1,+ )+ file_name_prefix = "export-2023-01-01T00-00-00Z"+ assert get_s3_key_from_inputs(inputs, file_number=0, file_name_prefix=file_name_prefix) == (+ f"{inputs.prefix}/{expected_name}-0.parquet.gz"+ )+ assert get_s3_key_from_inputs(inputs, file_number=1, file_name_prefix=file_name_prefix) == (+ f"{inputs.prefix}/{expected_name}-1.parquet.gz"+ )+ assert get_manifest_key(+ inputs.prefix, data_interval_start, data_interval_end, None, file_name_prefix=file_name_prefix+ ) == (f"{inputs.prefix}/{expected_name}_manifest.json")diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.pyindex eb6d7061c0a7..19666e8dc05d 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py@@ -37,7 +37,7 @@ from products.batch_exports.backend.models.batch_export import BatchExport, Batcfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModel, afetch_last_run_records_completedfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (BatchExportInsertIntoInternalStageInputs,- DataIntervalEndInFutureError,+ DataIntervalInFutureError,HogQLQueryResourceLimitExceededError,_execute_query,_raise_on_hogql_resource_limit_error,@@ -209,7 +209,7 @@ async def test_write_batch_export_record_batches_to_internal_stage_rejects_futurpatch("products.batch_exports.backend.temporal.pipeline.internal_stage.get_client") as mock_get_client,override_settings(DEBUG=False, TEST=False),):- with pytest.raises(DataIntervalEndInFutureError, match="The provided 'data_interval_end'.*is in the future"):+ with pytest.raises(DataIntervalInFutureError, match="The provided 'data_interval_end'.*is in the future"):await _write_batch_export_record_batches_to_internal_stage(query_or_model="SELECT 1",full_range=(data_interval_start, data_interval_end),diff --git a/products/batch_exports/backend/tests/temporal/test_metrics.py b/products/batch_exports/backend/tests/temporal/test_metrics.pyindex 6320f1d7d7c8..aa854699b14c 100644--- a/products/batch_exports/backend/tests/temporal/test_metrics.py+++ b/products/batch_exports/backend/tests/temporal/test_metrics.py@@ -5,11 +5,27 @@ import pytestfrom structlog.testing import capture_logs-from products.batch_exports.backend.temporal.metrics import SLAWaiter+from products.batch_exports.backend.temporal.metrics import SLAWaiter, get_interval_from_boundspytestmark = [pytest.mark.asyncio]+ "data_interval_start,data_interval_end,on_demand,expected",+ [+ (None, None, True, "on_demand"),+ ("2023-01-01T00:00:00+00:00", None, True, "on_demand"),+ (None, "2023-01-01T01:00:00+00:00", True, "on_demand"),+ (None, "2023-01-01T01:00:00+00:00", False, "beginning_of_time"),+ ("2023-01-01T00:00:00+00:00", None, False, None),+ ],+)+async def test_interval_from_optional_bounds(+ data_interval_start: str | None, data_interval_end: str | None, on_demand: bool, expected: str | None+) -> None:+ assert get_interval_from_bounds(data_interval_start, data_interval_end, on_demand=on_demand) == expected++async def test_sla_waiter():with capture_logs() as cap_logs:async with SLAWaiter(batch_export_id="test", sla=dt.timedelta(seconds=0.25)) as detector:diff --git a/products/batch_exports/backend/tests/temporal/test_monitoring.py b/products/batch_exports/backend/tests/temporal/test_monitoring.pyindex 52f78d29eab1..b901b70f976e 100644--- a/products/batch_exports/backend/tests/temporal/test_monitoring.py+++ b/products/batch_exports/backend/tests/temporal/test_monitoring.py@@ -256,6 +256,7 @@ async def test_monitoring_workflow_when_missing_batch_export_runs(assert len(runs) == 1for run in runs:assert run.data_interval_start is not None+ assert run.data_interval_end is not Noneexpected_missing_runs.append((run.data_interval_start, run.data_interval_end))await run.adelete()@@ -315,6 +316,7 @@ async def test_monitoring_workflow_when_missing_events(for run in runs:if run.records_completed and run.records_completed > 1:assert run.data_interval_start is not None+ assert run.data_interval_end is not Nonemissing_events = run.records_completed // 2expected_missing_events.append(EventCount(diff --git a/products/batch_exports/backend/tests/test_batch_export_run_workflow_id.py b/products/batch_exports/backend/tests/test_batch_export_run_workflow_id.pynew file mode 100644index 000000000000..f0012d6ce0ee--- /dev/null+++ b/products/batch_exports/backend/tests/test_batch_export_run_workflow_id.py@@ -0,0 +1,51 @@+import datetime as dt+from uuid import UUID++from django.test import SimpleTestCase++from parameterized import parameterized++from products.batch_exports.backend.models import BatchExport, BatchExportOnDemand, BatchExportRun+++class TestBatchExportRunWorkflowId(SimpleTestCase):+ @parameterized.expand(+ [+ ("bounded", True, True, "2026-01-01T00:00:00Z-2026-01-02T00:00:00Z"),+ ("start_only", True, False, "00000000-0000-0000-0000-000000000002"),+ ("end_only", False, True, "00000000-0000-0000-0000-000000000002"),+ ("unbounded", False, False, "00000000-0000-0000-0000-000000000002"),+ ]+ )+ def test_on_demand_workflow_id(self, _name: str, has_start: bool, has_end: bool, expected_suffix: str) -> None:+ parent = BatchExportOnDemand(id=UUID(int=1))+ run = BatchExportRun(+ id=UUID(int=2),+ batch_export_on_demand=parent,+ data_interval_start=dt.datetime(2026, 1, 1, tzinfo=dt.UTC) if has_start else None,+ data_interval_end=dt.datetime(2026, 1, 2, tzinfo=dt.UTC) if has_end else None,+ )++ assert run.workflow_id == f"{parent.id}-{expected_suffix}"++ @parameterized.expand(+ [+ ("bounded", True, True),+ ("start_only", True, False),+ ("end_only", False, True),+ ("unbounded", False, False),+ ]+ )+ def test_scheduled_workflow_id(self, _name: str, has_start: bool, has_end: bool) -> None:+ parent = BatchExport(id=UUID(int=1))+ run = BatchExportRun(+ batch_export=parent,+ data_interval_start=dt.datetime(2026, 1, 1, tzinfo=dt.UTC) if has_start else None,+ data_interval_end=dt.datetime(2026, 1, 2, tzinfo=dt.UTC) if has_end else None,+ )++ if has_end:+ assert run.workflow_id == f"{parent.id}-2026-01-02T00:00:00Z"+ else:+ with self.assertRaisesRegex(ValueError, "Scheduled batch export runs require data_interval_end"):+ _ = run.workflow_iddiff --git a/products/batch_exports/backend/tests/test_file_download_timeouts.py b/products/batch_exports/backend/tests/test_file_download_timeouts.pynew file mode 100644index 000000000000..b002ee4544b1--- /dev/null+++ b/products/batch_exports/backend/tests/test_file_download_timeouts.py@@ -0,0 +1,204 @@+import datetime as dt+from uuid import UUID++from unittest.mock import AsyncMock, Mock, patch++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized+from temporalio import workflow+from temporalio.client import Client+from temporalio.common import MetricMeter++from products.batch_exports.backend import service+from products.batch_exports.backend.models.batch_export import BatchExportOnDemand+from products.batch_exports.backend.service import BatchExportModel, FileDownloadBatchExportInputs+from products.batch_exports.backend.temporal.destinations.file_download_batch_export import (+ FileDownloadBatchExportWorkflow,+ export_to_file_download_bucket_with_temporary_credentials,+)+from products.batch_exports.backend.temporal.destinations.s3_batch_export import S3BatchExportResult+from products.batch_exports.backend.temporal.pipeline.entrypoint import _get_config_for_interval+from products.batch_exports.backend.temporal.pipeline.internal_stage import (+ InternalStageResult,+ insert_into_internal_stage_activity,+)++START = dt.datetime(2026, 1, 1, tzinfo=dt.timezone(dt.timedelta(hours=2)))+END = START + dt.timedelta(hours=1)+EXPORT_ID = UUID("00000000-0000-4000-8000-000000000001")+RUN_ID = UUID("00000000-0000-4000-8000-000000000002")+++class TestFileDownloadTimeouts(SimpleTestCase):+ @parameterized.expand(+ [+ ("neither_bound", None, None, 21600, 900),+ ("start_only", START, None, 21600, 900),+ ("end_only", None, END, 21600, 900),+ ("both_bounds", START, END, 28800, 1500),+ ("configured_budgets", None, None, 28800, 1500),+ ]+ )+ def test_service_pins_budgets_only_for_incomplete_intervals(+ self, _name: str, start: dt.datetime | None, end: dt.datetime | None, main_seconds: int, query_seconds: int+ ) -> None:+ batch_export = BatchExportOnDemand(id=EXPORT_ID, team_id=1)+ model = BatchExportModel(name="hogql", schema=None, hogql_query="SELECT 1 AS value")+ client = AsyncMock(spec=Client)++ with (+ override_settings(+ BATCH_EXPORT_HOGQL_ON_DEMAND_MAIN_TIMEOUT_SECONDS=main_seconds,+ BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME=query_seconds,+ ),+ patch.object(service, "sync_connect", return_value=client),+ ):+ service.start_file_download_batch_export(+ batch_export,+ "file-download-test",+ start,+ end,+ model,+ batch_export_run_id=RUN_ID,+ )++ client.start_workflow.assert_awaited_once()+ call = client.start_workflow.await_args+ assert call is not None+ assert call.args[0] == "file-download-export"+ assert call.kwargs["id"] == "file-download-test"+ inputs = call.args[1]+ assert isinstance(inputs, FileDownloadBatchExportInputs)+ assert inputs.data_interval_start == (start.isoformat() if start is not None else None)+ assert inputs.data_interval_end == (end.isoformat() if end is not None else None)+ assert inputs.batch_export_run_id == RUN_ID+ assert inputs.batch_export_model == model+ incomplete = start is None or end is None+ assert inputs.main_activity_timeout_seconds == (main_seconds if incomplete else None)+ assert inputs.stage_activity_timeout_seconds == (query_seconds + 300 if incomplete else None)++ @parameterized.expand(+ [+ ("events", "events", RUN_ID, None, None),+ ("events_start_only", "events", RUN_ID, START, None),+ ("events_end_only", "events", RUN_ID, None, END),+ ("not_on_demand", "hogql", None, None, None),+ ]+ )+ def test_service_rejects_incomplete_intervals_outside_on_demand_hogql(+ self, _name: str, model_name: str, run_id: UUID | None, start: dt.datetime | None, end: dt.datetime | None+ ) -> None:+ with patch.object(service, "sync_connect") as connect:+ with self.assertRaisesRegex(ValueError, "Only on-demand HogQL exports"):+ service.start_file_download_batch_export(+ BatchExportOnDemand(id=EXPORT_ID, team_id=1),+ "file-download-test",+ start,+ end,+ BatchExportModel(name=model_name, schema=None),+ batch_export_run_id=run_id,+ )+ connect.assert_not_called()++ @parameterized.expand(+ [+ ("explicit_budgets", 21600, 1200, 0, 21600),+ ("main_override", 21600, 1200, 28800, 28800),+ ("smaller_override", 21600, 1200, 60, 21600),+ ("independent_stage_budget", 21600, 1800, 0, 21600),+ ]+ )+ def test_interval_free_budgets_are_independent(+ self, _name: str, main_seconds: int, stage_seconds: int, override_seconds: int, expected_main_seconds: int+ ) -> None:+ config = _get_config_for_interval(+ None,+ dt.timedelta(seconds=override_seconds),+ main_activity_timeout_seconds=main_seconds,+ stage_activity_timeout_seconds=stage_seconds,+ )++ assert config.main_start_to_close == dt.timedelta(seconds=expected_main_seconds)+ assert config.stage_start_to_close == dt.timedelta(seconds=stage_seconds)+ assert config.failure_check_window == 50++ @parameterized.expand(+ [+ ("hour", 21600, 3600, 24),+ ("day", 86400, 21600, 7),+ ("week", 259200, 86400, 4),+ ("every 5 minutes", 1200, 1200, 12),+ ("every 3600 seconds", 3600, 3600, 50),+ ]+ )+ def test_existing_intervals_ignore_explicit_budgets(+ self, interval: str, main_seconds: int, stage_seconds: int, failure_check_window: int+ ) -> None:+ config = _get_config_for_interval(+ interval,+ dt.timedelta(0),+ main_activity_timeout_seconds=400000,+ stage_activity_timeout_seconds=300000,+ )++ assert config.main_start_to_close == dt.timedelta(seconds=main_seconds)+ assert config.stage_start_to_close == dt.timedelta(seconds=stage_seconds)+ assert config.failure_check_window == failure_check_window++ @parameterized.expand(+ [+ ("neither_bound", None, None, 28800, 1800),+ ("start_only", START.isoformat(), None, 28800, 1800),+ ("end_only", None, END.isoformat(), 28800, 1800),+ ("both_bounds", START.isoformat(), END.isoformat(), 3600, 3600),+ ]+ )+ async def test_workflow_dispatch_preserves_bounds_and_persisted_budgets(+ self, _name: str, start: str | None, end: str | None, main_seconds: int, stage_seconds: int+ ) -> None:+ inputs = FileDownloadBatchExportInputs(+ batch_export_id=str(EXPORT_ID),+ team_id=1,+ batch_export_run_id=RUN_ID,+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT 1 AS value"),+ data_interval_start=start,+ data_interval_end=end,+ main_activity_timeout_seconds=28800,+ stage_activity_timeout_seconds=1800,+ )+ with (+ override_settings(+ BATCH_EXPORT_HOGQL_ON_DEMAND_MAIN_TIMEOUT_SECONDS=21600,+ BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME=900,+ ),+ patch.object(workflow, "info", return_value=Mock(workflow_id="file-download-test")),+ patch.object(workflow, "metric_meter", return_value=MetricMeter.noop),+ patch.object(workflow, "set_current_details"),+ patch.object(+ workflow,+ "execute_activity",+ new_callable=AsyncMock,+ side_effect=[+ InternalStageResult(stage_folder="test-stage", records_total=1),+ S3BatchExportResult(records_completed=1, bytes_exported=10),+ None,+ [],+ ],+ ) as execute_activity,+ ):+ result = await FileDownloadBatchExportWorkflow().run(inputs)++ activity_calls = {call.args[0]: call for call in execute_activity.await_args_list}+ stage_call = activity_calls[insert_into_internal_stage_activity]+ export_call = activity_calls[export_to_file_download_bucket_with_temporary_credentials]+ for activity_inputs in (stage_call.args[1], export_call.args[1].batch_export):+ assert activity_inputs.data_interval_start == start+ assert activity_inputs.data_interval_end == end+ assert activity_inputs.run_id == str(RUN_ID)+ assert activity_inputs.on_demand is True+ assert stage_call.kwargs["start_to_close_timeout"] == dt.timedelta(seconds=stage_seconds)+ assert export_call.kwargs["start_to_close_timeout"] == dt.timedelta(seconds=main_seconds)+ assert result.records_completed == 1+ assert result.bytes_exported == 10+ assert result.error is Nonediff --git a/products/batch_exports/backend/tests/test_internal_stage_storage_config.py b/products/batch_exports/backend/tests/test_internal_stage_storage_config.pyindex 39b3a59b8286..973776ef240e 100644--- a/products/batch_exports/backend/tests/test_internal_stage_storage_config.py+++ b/products/batch_exports/backend/tests/test_internal_stage_storage_config.py@@ -4,9 +4,11 @@ from django.test.utils import override_settingsfrom posthog.credentials import AWSKeyPair+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsErrorfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (_get_s3_credentials,_get_s3_endpoint_url,+ get_base_s3_staging_folder,get_s3_staging_folder,)@@ -104,3 +106,28 @@ def test_s3_endpoint_url_self_hosted_uses_configured_endpoint_not_localhost() ->BATCH_EXPORT_OBJECT_STORAGE_ENDPOINT=OBJECT_STORAGE_ENDPOINT,):assert _get_s3_endpoint_url() == OBJECT_STORAGE_ENDPOINT+++ "start,end,run_id,expected_base",+ [+ ("2026-01-01", "2026-01-02", None, "batch-exports/export/2026-01-01-2026-01-02"),+ (None, "2026-01-02", None, "batch-exports/export/None-2026-01-02"),+ (None, "2026-01-02", "run-a", "batch-exports/export/runs/run-a"),+ ("2026-01-01", None, "run-a", "batch-exports/export/runs/run-a"),+ (None, None, "run-b", "batch-exports/export/runs/run-b"),+ (None, None, None, None),+ ],+)+def test_staging_folder_namespace(+ start: str | None, end: str | None, run_id: str | None, expected_base: str | None+) -> None:+ if expected_base is None:+ with pytest.raises(MissingRequiredInputsError, match="requires data_interval_end or run_id"):+ get_s3_staging_folder("export", start, end, 1, run_id=run_id)+ return+ assert get_base_s3_staging_folder("export", start, end, run_id) == expected_base+ for attempt in (1, 2):+ assert (+ get_s3_staging_folder("export", start, end, attempt, run_id).folder == f"{expected_base}/attempt_{attempt}"+ )diff --git a/products/batch_exports/backend/tests/test_nullable_staging.py b/products/batch_exports/backend/tests/test_nullable_staging.pynew file mode 100644index 000000000000..0f74440e0211--- /dev/null+++ b/products/batch_exports/backend/tests/test_nullable_staging.py@@ -0,0 +1,227 @@+import datetime as dt+from collections.abc import Iterator++import pytest+import time_machine+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import override_settings++from temporalio.testing import ActivityEnvironment++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database++from posthog.models import Team++from products.batch_exports.backend.service import BatchExportModel+from products.batch_exports.backend.temporal.errors import MissingRequiredInputsError+from products.batch_exports.backend.temporal.pipeline import internal_stage+from products.batch_exports.backend.temporal.pipeline.entrypoint import STAGE_NON_RETRYABLE_ERROR_TYPES+from products.batch_exports.backend.temporal.pipeline.query_ranges import is_5_min_batch_export+from products.batch_exports.backend.temporal.record_batch_model import (+ HogQLQueryRecordBatchModel,+ SessionsRecordBatchModel,+)++START = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+END = START + dt.timedelta(minutes=5)+EXPORT_ID = "00000000-0000-4000-8000-000000000001"+RUN_ID = "00000000-0000-4000-8000-000000000002"+++def staging_clients() -> Iterator[tuple[AsyncMock, AsyncMock]]:+ clickhouse = AsyncMock()+ clickhouse.execute_query_with_summary.return_value = {"written_rows": "1"}+ clickhouse_cm = MagicMock()+ clickhouse_cm.__aenter__.return_value = clickhouse+ s3 = AsyncMock()+ s3.list_objects_v2.return_value = {}+ s3_cm = MagicMock()+ s3_cm.__aenter__.return_value = s3+ with (+ patch.object(internal_stage, "get_client", return_value=clickhouse_cm),+ patch.object(internal_stage, "get_s3_client", return_value=s3_cm),+ patch("products.batch_exports.backend.temporal.utils.aupdate_batch_export_run", new_callable=AsyncMock),+ patch.object(+ HogQLQueryRecordBatchModel,+ "get_hogql_context",+ new_callable=AsyncMock,+ side_effect=lambda: HogQLContext(+ team=Team(id=1),+ database=Database(),+ restricted_properties=set(),+ apply_events_retention_floor=False,+ enable_select_queries=True,+ values={"log_comment": "{}"},+ ),+ ),+ ):+ yield clickhouse, s3++[email protected]("start,end", [(None, None), (START, None), (None, END), (START, END)])+async def test_hogql_staging_preserves_optional_bounds_and_cleanup_namespace(+ staging_clients: tuple[AsyncMock, AsyncMock], start: dt.datetime | None, end: dt.datetime | None+) -> None:+ clickhouse, s3 = staging_clients+ start_str = start.isoformat() if start is not None else None+ end_str = end.isoformat() if end is not None else None+ inputs = internal_stage.BatchExportInsertIntoInternalStageInputs(+ team_id=1,+ batch_export_id=EXPORT_ID,+ run_id=RUN_ID,+ data_interval_start=start_str,+ data_interval_end=end_str,+ on_demand=True,+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT 1 AS value"),+ )++ result = await ActivityEnvironment().run(internal_stage.insert_into_internal_stage_activity, inputs)++ expected_base = (+ f"batch-exports/{EXPORT_ID}/runs/{RUN_ID}"+ if start is None or end is None+ else f"batch-exports/{EXPORT_ID}/{start_str}-{end_str}"+ )+ assert result.error is None+ assert result.records_total == 1+ assert result.stage_folder == f"{expected_base}/attempt_1"+ assert s3.list_objects_v2.call_args.kwargs["Prefix"] == expected_base+ query = clickhouse.execute_query_with_summary.call_args.args[0]+ assert result.stage_folder in query+ assert "SELECT" in query+ query_parameters = clickhouse.execute_query_with_summary.call_args.kwargs["query_parameters"]+ assert "interval_start" not in query_parameters+ assert "interval_end" not in query_parameters++[email protected]("hogql_query", [None, "SELECT {data_interval_end} AS value"])+async def test_unsupported_hogql_returns_nonretryable_staging_error(+ staging_clients: tuple[AsyncMock, AsyncMock], hogql_query: str | None+) -> None:+ inputs = internal_stage.BatchExportInsertIntoInternalStageInputs(+ team_id=1,+ batch_export_id=EXPORT_ID,+ run_id=RUN_ID,+ data_interval_start=None,+ data_interval_end=None,+ on_demand=True,+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query=hogql_query),+ )++ result = await ActivityEnvironment().run(internal_stage.insert_into_internal_stage_activity, inputs)++ assert result.error is not None+ assert result.error.type == "UnsupportedHogQLQueryError"+ staging_clients[0].execute_query_with_summary.assert_not_called()+ staging_clients[1].list_objects_v2.assert_not_called()+++ "start,end,bound",+ [+ (END, None, "data_interval_start"),+ (None, END, "data_interval_end"),+ ],+)+async def test_hogql_staging_rejects_each_future_bound_without_waiting(+ staging_clients: tuple[AsyncMock, AsyncMock],+ start: dt.datetime | None,+ end: dt.datetime | None,+ bound: str,+) -> None:+ inputs = internal_stage.BatchExportInsertIntoInternalStageInputs(+ team_id=1,+ batch_export_id=EXPORT_ID,+ run_id=RUN_ID,+ data_interval_start=start.isoformat() if start is not None else None,+ data_interval_end=end.isoformat() if end is not None else None,+ on_demand=True,+ batch_export_model=BatchExportModel(name="hogql", schema=None, hogql_query="SELECT 1 AS value"),+ )+ # Patch the helper rather than override settings.TEST, because DatabaseSyncToAsync calls+ # close_old_connections() whenever settings.TEST is False, and that needs a database.+ with (+ time_machine.travel(START, tick=False),+ patch.object(internal_stage, "_is_local_dev_or_test", return_value=False),+ ):+ result = await ActivityEnvironment().run(internal_stage.insert_into_internal_stage_activity, inputs)++ assert result.error is not None+ assert result.error.type == "DataIntervalInFutureError"+ assert f"'{bound}'" in result.error.message+ assert END.isoformat() in result.error.message+ staging_clients[0].is_alive.assert_not_called()+ staging_clients[1].list_objects_v2.assert_not_called()+++ "on_demand,model_name,run_id",+ [(False, "hogql", RUN_ID), (True, "hogql", None), (True, "events", RUN_ID)],+ ids=["scheduled-missing-end", "on-demand-missing-run-id", "fixed-model-missing-end"],+)+async def test_missing_staging_inputs_raise(+ staging_clients: tuple[AsyncMock, AsyncMock],+ on_demand: bool,+ model_name: str,+ run_id: str | None,+) -> None:+ inputs = internal_stage.BatchExportInsertIntoInternalStageInputs(+ team_id=1,+ batch_export_id=EXPORT_ID,+ run_id=run_id,+ data_interval_start=None,+ data_interval_end=None,+ on_demand=on_demand,+ batch_export_model=BatchExportModel(name=model_name, schema=None, hogql_query="SELECT 1 AS value"),+ )+ with pytest.raises(MissingRequiredInputsError, match="require"):+ await ActivityEnvironment().run(internal_stage.insert_into_internal_stage_activity, inputs)+ assert "MissingRequiredInputsError" not in STAGE_NON_RETRYABLE_ERROR_TYPES+ staging_clients[0].is_alive.assert_not_called()+ staging_clients[1].list_objects_v2.assert_not_called()++[email protected]("is_backfill", [False, True])+def test_sessions_require_an_interval_end(is_backfill: bool) -> None:+ with pytest.raises(MissingRequiredInputsError, match="requires data_interval_end"):+ SessionsRecordBatchModel(team_id=1, is_backfill=is_backfill).get_hogql_query(START, None)+++async def test_raw_sql_staging_requires_an_interval_end() -> None:+ with pytest.raises(MissingRequiredInputsError, match="require data_interval_end"):+ await internal_stage._write_batch_export_record_batches_to_internal_stage(+ query_or_model="SELECT 1",+ full_range=(None, None),+ query_parameters={},+ team_id=1,+ batch_export_id=EXPORT_ID,+ data_interval_start=None,+ data_interval_end=None,+ s3_staging_folder_url="https://example.com/stage",+ run_id=RUN_ID,+ )++[email protected]("start", [None, START])+async def test_partition_count_without_end_uses_static_default(start: dt.datetime | None) -> None:+ with override_settings(BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED=True, BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=7):+ assert await internal_stage.compute_num_partitions(EXPORT_ID, start, None) == 7+++ "start,end,expected",+ [(None, None, False), (START, None, False), (None, END, False), (START, END, True)],+)+def test_five_minute_detection_requires_both_bounds(+ start: dt.datetime | None, end: dt.datetime | None, expected: bool+) -> None:+ assert is_5_min_batch_export((start, end)) is expecteddiff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 743339e1e94a..ed51e6cc526c 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -538,6 +538,8 @@ export const BatchExportRunStatusEnumApi = {*/export interface BatchExportRunApi {readonly id: string+ /** The end of the data interval. */+ data_interval_end: string/** The status of this run.** * `Cancelled` - Cancelled@@ -575,8 +577,6 @@ export interface BatchExportRunApi {* @nullable*/data_interval_start?: string | null- /** The end of the data interval. */- data_interval_end: string/*** An opaque cursor that may be used to resume.* @nullablediff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 95078f5c3d64..451a2dc1c89a 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -591,6 +591,7 @@ export const batchExportsRunsCancelCreateBodyBytesExportedMax = 2147483647export const BatchExportsRunsCancelCreateBody = /* @__PURE__ */ zod.object({+ data_interval_end: zod.iso.datetime({ offset: true }).describe('The end of the data interval.'),status: zod.enum(['Cancelled',@@ -624,7 +625,6 @@ export const BatchExportsRunsCancelCreateBody = /* @__PURE__ */ zod.describe('The number of records that failed downstream processing (e.g. hog function execution errors).'),latest_error: zod.string().nullish().describe('The latest error that occurred during this run.'),data_interval_start: zod.iso.datetime({ offset: true }).nullish().describe('The start of the data interval.'),- data_interval_end: zod.iso.datetime({ offset: true }).describe('The end of the data interval.'),cursor: zod.string().nullish().describe('An opaque cursor that may be used to resume.'),finished_at: zod.iso.datetime({ offset: true })@@ -667,6 +667,7 @@ export const batchExportsRunsRetryCreateBodyBytesExportedMax = 2147483647export const BatchExportsRunsRetryCreateBody = /* @__PURE__ */ zod.object({+ data_interval_end: zod.iso.datetime({ offset: true }).describe('The end of the data interval.'),status: zod.enum(['Cancelled',@@ -700,7 +701,6 @@ export const BatchExportsRunsRetryCreateBody = /* @__PURE__ */ zod.describe('The number of records that failed downstream processing (e.g. hog function execution errors).'),latest_error: zod.string().nullish().describe('The latest error that occurred during this run.'),data_interval_start: zod.iso.datetime({ offset: true }).nullish().describe('The start of the data interval.'),- data_interval_end: zod.iso.datetime({ offset: true }).describe('The end of the data interval.'),cursor: zod.string().nullish().describe('An opaque cursor that may be used to resume.'),finished_at: zod.iso.datetime({ offset: true })diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f9a2b158e507..ba7a60d8763c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13549,6 +13549,8 @@ export namespace Schemas {*/export interface BatchExportRun {readonly id: string;+ /** The end of the data interval. */+ data_interval_end: string;/** The status of this run.** * `Cancelled` - Cancelled@@ -13586,8 +13588,6 @@ export namespace Schemas {* @nullable*/data_interval_start?: string | null;- /** The end of the data interval. */- data_interval_end: string;/*** An opaque cursor that may be used to resume.* @nullable