: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
fix: Raise if data_interval_end is in the future (#60836)
Tomás Farías Santana1b706e214f0a
diff --git a/posthog/batch_exports/api/file_download.py b/posthog/batch_exports/api/file_download.pyindex 82c813fca056..78ecc3af7197 100644--- a/posthog/batch_exports/api/file_download.py+++ b/posthog/batch_exports/api/file_download.py@@ -105,6 +105,11 @@ class FileDownloadBatchExportOnDemandSerializer(serializers.Serializer):if data["data_interval_end"] - data["data_interval_start"] > FILE_DOWNLOAD_MAX_RANGE:raise ValidationError("data interval range too big")+ if data["data_interval_end"] > dt.datetime.now(dt.UTC):+ raise ValidationError(+ f"The provided 'data_interval_end' ({data['data_interval_end'].isoformat()}) is in the future"+ )+return datadef create(self, validated_data: dict) -> BatchExportRun:diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex 0f76eedbf49d..b5136a9e65bf 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -175,7 +175,7 @@ async def execute_batch_export_using_internal_stage(initial_interval=dt.timedelta(seconds=initial_retry_interval_seconds),maximum_interval=dt.timedelta(seconds=maximum_stage_retry_interval_seconds),maximum_attempts=maximum_attempts,- non_retryable_error_types=["InvalidFilterError"],+ non_retryable_error_types=["InvalidFilterError", "DataIntervalEndInFutureError"],),)batch_export_inputs.stage_folder = stage_folderdiff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex b8b67eba39e6..ecea886ffc0d 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -70,6 +70,13 @@ from products.batch_exports.backend.temporal.utils import set_status_to_running_LOGGER = get_write_only_logger()+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")++def _is_local_dev_or_test() -> bool:return settings.DEBUG or settings.TEST@@ -492,6 +499,11 @@ async def _write_batch_export_record_batches_to_internal_stage(else:delta = dt.timedelta(minutes=1)end_at = full_range[1]++ if _is_local_dev_or_test() is False and end_at > dt.datetime.now(dt.UTC):+ # Some tests create data in the future, so we do not check this.+ raise DataIntervalEndInFutureError(end_at)+await wait_for_delta_past_data_interval_end(end_at, delta)done_ranges: list[tuple[dt.datetime, dt.datetime]] = []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 6afb753f8552..0ea2011eb70d 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@@ -359,6 +359,45 @@ async def test_file_download_create_rejects_when_concurrency_limit_reached(mock_start.assert_not_called()[email protected]_db(transaction=True)+async def test_file_download_create_rejects_future_data_interval_end(+ async_client: AsyncClient,+ team,+ user,+):+ now = dt.datetime.now(dt.UTC)++ await async_client.aforce_login(user)++ with unittest.mock.patch("posthog.batch_exports.api.file_download.start_file_download_batch_export") as mock_start:+ data_interval_end_iso = (now + dt.timedelta(hours=1)).isoformat()+ response = await async_client.post(+ f"/api/projects/{team.pk}/file_download_batch_exports",+ {+ "file": {+ "format": "Parquet",+ "compression": "zstd",+ },+ "model": "events",+ "data_interval_start": (now - dt.timedelta(hours=1)).isoformat(),+ "data_interval_end": data_interval_end_iso,+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["detail"] == f"The provided 'data_interval_end' ({data_interval_end_iso}) is in the future"++ mock_start.assert_not_called()+ assert (+ await BatchExportRun.objects.filter(+ batch_export_on_demand__team_id=team.pk,+ batch_export_on_demand__destination__type=BatchExportDestination.Destination.FILE_DOWNLOAD,+ ).acount()+ == 0+ )++@pytest.mark.django_db(transaction=True)async def test_file_download_list_returns_run_ids_and_statuses(async_client: AsyncClient,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 5fea19ee3e4b..04fe41c81ada 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@@ -20,6 +20,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModelfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (BatchExportInsertIntoInternalStageInputs,+ DataIntervalEndInFutureError,+ _write_batch_export_record_batches_to_internal_stage,insert_into_internal_stage_activity,)from products.batch_exports.backend.temporal.pipeline.producer import Producer@@ -175,6 +177,33 @@ async def test_insert_into_stage_activity_executes_the_expected_query_for_sessio)+async def test_write_batch_export_record_batches_to_internal_stage_rejects_future_data_interval_end():+ data_interval_start = dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)+ data_interval_end = dt.datetime.now(dt.UTC) + dt.timedelta(hours=1)++ with (+ patch(+ "products.batch_exports.backend.temporal.pipeline.internal_stage.wait_for_delta_past_data_interval_end"+ ) as mock_wait,+ patch("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"):+ await _write_batch_export_record_batches_to_internal_stage(+ query_or_model="SELECT 1",+ full_range=(data_interval_start, data_interval_end),+ query_parameters={},+ team_id=1,+ batch_export_id=str(uuid.uuid4()),+ data_interval_start=data_interval_start.isoformat(),+ data_interval_end=data_interval_end.isoformat(),+ s3_staging_folder_url="s3://bucket/folder",+ )++ mock_wait.assert_not_called()+ mock_get_client.assert_not_called()++@pytest_asyncio.fixtureasync def minio_client():"""Manage an S3 client to interact with a MinIO bucket."""