: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(batch-exports): handle expected staging failures (#95312)
Rossb39cea433188
diff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.pyindex 04c590629e83..53a704811afc 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@@ -386,12 +386,18 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):file_format=inputs.file_format,max_file_size_mb=inputs.max_file_size_mb,)- result: S3BatchExportResult = await execute_batch_export_using_internal_stage(+ result = await execute_batch_export_using_internal_stage(export_to_file_download_bucket_with_temporary_credentials,export_inputs, # type: ignoreinterval=f"every {int(interval_delta.total_seconds())} seconds",)+ # A failed run gets no download links, even where some files did reach the bucket. The+ # `isinstance` arm is unreachable in practice, since every failure comes back as a plain+ # `BatchExportResult`; it's needed to narrow the type for `files_uploaded` below.+ if result.error is not None or not isinstance(result, S3BatchExportResult):+ return FileDownloadBatchExportResult(records_completed=0, bytes_exported=0, error=result.error)+file_downloads = await workflow.execute_activity(generate_file_downloads,GenerateFileDownloadsInputs(diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex c876d7c07f3e..79e39c82b366 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -21,6 +21,7 @@ from products.batch_exports.backend.service import (from products.batch_exports.backend.temporal.batch_exports import FinishBatchExportRunInputs, finish_batch_export_runfrom products.batch_exports.backend.temporal.metrics import get_export_finished_metric, get_export_started_metricfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (+ NON_RETRYABLE_ERRORS,BatchExportInsertIntoInternalStageInputs,InternalStageResult,insert_into_internal_stage_activity,@@ -70,11 +71,10 @@ INITIAL_RETRY_INTERVAL_SECONDS = 1DEFAULT_MAX_RETRY_INTERVAL_SECONDS = 3600DEFAULT_MAX_STAGE_RETRY_INTERVAL_SECONDS = 600-STAGE_NON_RETRYABLE_ERROR_TYPES = (- "InvalidFilterError",- "DataIntervalEndInFutureError",- "HogQLQueryResourceLimitExceededError",-)+# The staging activity returns these as an `InternalStageResult.error` rather than raising, so+# Temporal normally never sees them. They stay listed here to stop an endless retry loop if one is+# ever raised from a path the activity's own handling does not cover.+STAGE_NON_RETRYABLE_ERROR_TYPES = tuple(error.__name__ for error in NON_RETRYABLE_ERRORS)@frozen@@ -147,14 +147,16 @@ def _get_status_for_activity_error(error: exceptions.ActivityError) -> BatchExpoif isinstance(error.cause, exceptions.CancelledError):return BatchExportRun.Status.CANCELLED+ # Both activities report their non-retryable errors through their result rather than by raising,+ # so this covers only one escaping from a path that handling does not reach.if isinstance(error.cause, exceptions.ApplicationError) and error.cause.type in STAGE_NON_RETRYABLE_ERROR_TYPES:return BatchExportRun.Status.FAILED# Reaching this outside tests means one of two assumptions broke, so `finish_batch_export_run`# logs it. Callers pass `maximum_attempts=0` with no schedule-to-close or run timeout, so a# retryable error (or activity timeout) retries forever and never surfaces here; and a terminal- # error from the destination activity comes back as a `BatchExportResult` with `error_repr`- # rather than raising. That leaves `TEST`, which forces `maximum_attempts=1`.+ # error from either activity comes back as a result with an error rather than raising. That+ # leaves `TEST`, which forces `maximum_attempts=1`.return BatchExportRun.Status.FAILED_RETRYABLE@@ -235,7 +237,7 @@ async def execute_batch_export_using_internal_stage(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,-) -> BatchExportResultType:+) -> BatchExportResult:"""Run one batch export: stage its data, write it to the destination, record how it went.All batch exports boil down to inserting some data somewhere, and they all follow the same error@@ -263,7 +265,8 @@ async def execute_batch_export_using_internal_stage(query.Returns:- The destination activity's result.+ The destination activity's result, or a plain `BatchExportResult` carrying the staging+ error when staging failed for a reason the user has to resolve."""if hasattr(inputs, "batch_export"):batch_export_inputs: _BatchExportInputsProtocol = inputs.batch_export # ty: ignore[invalid-assignment]@@ -321,6 +324,11 @@ async def execute_batch_export_using_internal_stage(),)+ if stage_result.error is not None:+ finish_inputs.status = BatchExportRun.Status.FAILED+ finish_inputs.latest_error = stage_result.error.message+ return BatchExportResult(error=stage_result.error)+batch_export_inputs.stage_folder = stage_result.stage_folderbatch_export_inputs.records_total = stage_result.records_totalif stage_result.records_total is not None:diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 745c4b6448c1..9a0731d12b9b 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -19,6 +19,7 @@ from temporalio import activityfrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.query_tagging import Productfrom posthog.credentials import AWSKeyPair+from posthog.dataclasses import frozenfrom products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff@@ -52,13 +53,14 @@ 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.filters import compose_filters_clause+from 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 (is_5_min_batch_export,use_distributed_events_recent_table,wait_for_delta_past_data_interval_end,)+from products.batch_exports.backend.temporal.pipeline.types import BatchExportErrorfrom products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_modelfrom products.batch_exports.backend.temporal.sql.common import get_s3_function_callfrom products.batch_exports.backend.temporal.sql.events import (@@ -89,14 +91,25 @@ class DataIntervalEndInFutureError(Exception):class HogQLQueryResourceLimitExceededError(Exception):"""A user's HogQL batch export query exceeded a per-query ClickHouse resource limit.- Raised in place of the ClickHouse error so the workflow treats it as non-retryable (see the- stage activity's `non_retryable_error_types`): re-running the query unchanged would fail again.+ Raised in place of the ClickHouse error so the staging activity treats it as non-retryable+ (see `NON_RETRYABLE_ERRORS`): re-running the query unchanged would fail again.Only raised for the `hogql` model. The fixed models keep their ClickHouse errors and stayretryable, since their queries are ours and any failures are our responsibility to address."""+# Staging failures the user has to resolve; retrying them ourselves would achieve nothing.+# The activity returns these as an `InternalStageResult.error` instead of raising, which fails the+# 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,+ HogQLQueryResourceLimitExceededError,+ InvalidFilterError,+)++def _raise_on_hogql_resource_limit_error(exc: ClickHouseError, model_name: str) -> None:"""Re-raise a per-query resource limit breach as an error the workflow will not retry.@@ -250,13 +263,15 @@ class S3StagingFolder:url: str-@dataclass+@frozenclass InternalStageResult:"""Result of staging a batch export run's data in the internal S3 area."""stage_folder: str# Total rows written to the stage (from ClickHouse's query summary), or None if unknown.records_total: int | None = None+ # Set when staging failed with one of `NON_RETRYABLE_ERRORS`, in which case nothing was staged.+ error: BatchExportError | None = None@dataclass@@ -299,11 +314,7 @@ class BatchExportInsertIntoInternalStageInputs:async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInternalStageInputs,) -> InternalStageResult:- """Write record batches to our own internal S3 staging area.-- Returns:- The S3 staging folder where the data was written to, and the total number of rows staged.- """+ """Write record batches to our own internal S3 staging area."""bind_contextvars(team_id=inputs.team_id,batch_export_id=inputs.batch_export_id,@@ -346,49 +357,85 @@ async def insert_into_internal_stage_activity()logger.info("Computed staging partitions", num_partitions=num_partitions)- if record_batch_model is not None:- query_or_model = record_batch_model- query_parameters = {}- else:- query, query_parameters = await _get_query(+ try:+ records_total = await _stage_query_results(+ inputs,+ record_batch_model=record_batch_model,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,- data_interval_start=inputs.data_interval_start,- data_interval_end=inputs.data_interval_end,fields=fields,filters=filters,- destination_default_fields=inputs.destination_default_fields,- exclude_events=inputs.exclude_events,- include_events=inputs.include_events,extra_query_parameters=extra_query_parameters,- num_partitions=num_partitions,- is_workflows=inputs.is_workflows,- )- query_or_model = query-- try:- records_total = await _write_batch_export_record_batches_to_internal_stage(- query_or_model=query_or_model,full_range=full_range,- query_parameters=query_parameters,- team_id=inputs.team_id,- batch_export_id=inputs.batch_export_id,- data_interval_start=inputs.data_interval_start,- data_interval_end=inputs.data_interval_end,- s3_staging_folder_url=s3_staging_folder.url,+ s3_staging_folder=s3_staging_folder,num_partitions=num_partitions,)- except ClickHouseError as e:- _raise_on_hogql_resource_limit_error(e, model_name)- raise+ except NON_RETRYABLE_ERRORS as e:+ logger.warning("Staging data failed with a non-retryable error", error=str(e))+ return InternalStageResult(+ stage_folder=s3_staging_folder.folder,+ error=BatchExportError(type=type(e).__name__, message=str(e)),+ )+logger.info("Staging data completed successfully", records_total=records_total)return InternalStageResult(stage_folder=s3_staging_folder.folder, records_total=records_total)+async def _stage_query_results(+ inputs: BatchExportInsertIntoInternalStageInputs,+ *,+ record_batch_model: RecordBatchModel | None,+ model_name: str,+ 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],+ s3_staging_folder: S3StagingFolder,+ num_partitions: int,+) -> int | None:+ """Build this run's query and write its results into the internal S3 staging area.++ Returns the number of rows staged, or None if the count couldn't be determined.+ """+ if record_batch_model is not None:+ query_or_model: str | RecordBatchModel = record_batch_model+ query_parameters: dict[str, typing.Any] = {}+ else:+ 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,+ data_interval_start=inputs.data_interval_start,+ data_interval_end=inputs.data_interval_end,+ fields=fields,+ filters=filters,+ destination_default_fields=inputs.destination_default_fields,+ exclude_events=inputs.exclude_events,+ include_events=inputs.include_events,+ extra_query_parameters=extra_query_parameters,+ num_partitions=num_partitions,+ is_workflows=inputs.is_workflows,+ )++ try:+ return await _write_batch_export_record_batches_to_internal_stage(+ query_or_model=query_or_model,+ full_range=full_range,+ query_parameters=query_parameters,+ team_id=inputs.team_id,+ batch_export_id=inputs.batch_export_id,+ data_interval_start=inputs.data_interval_start,+ data_interval_end=inputs.data_interval_end,+ s3_staging_folder_url=s3_staging_folder.url,+ num_partitions=num_partitions,+ )+ except ClickHouseError as e:+ _raise_on_hogql_resource_limit_error(e, model_name)+ raise++async def compute_num_partitions(batch_export_id: str, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime) -> int:diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.pyindex c66b11efb156..53da5fddda5f 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py@@ -28,14 +28,12 @@ from products.batch_exports.backend.tests.temporal.destinations.s3.utils import)from products.batch_exports.backend.tests.temporal.utils.workflow import fail_on_application_error-pytestmark = [- pytest.mark.asyncio,- pytest.mark.django_db,- pytest.mark.skipif(- not has_valid_credentials(),- reason="AWS credentials not set in environment",- ),-]+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]++requires_aws_credentials = pytest.mark.skipif(+ not has_valid_credentials(),+ reason="AWS credentials not set in environment",+)@pytest_asyncio.fixture@@ -73,6 +71,7 @@ async def file_download_batch_export(await adelete_batch_export(batch_export, temporal_client)+@requires_aws_credentials@pytest.mark.parametrize("interval", ["hour"], indirect=True)@pytest.mark.parametrize("model", [BatchExportModel(name="events", schema=None)])@pytest.mark.parametrize("exclude_events", [None], indirect=True)@@ -194,3 +193,71 @@ async def test_file_download_workflow_exports_data(for fd in file_downloads:response = await s3_client.head_object(Bucket=s3_bucket, Key=fd.key)assert response["ResponseMetadata"]["HTTPStatusCode"] == 200++[email protected]("interval", ["hour"], indirect=True)[email protected]("exclude_events", [None], indirect=True)+async def test_file_download_workflow_generates_no_downloads_for_a_failed_run(+ ateam,+ file_download_batch_export,+ interval,+ compression,+ exclude_events,+ file_format,+ data_interval_start,+ data_interval_end,+):+ """A run that fails while staging must not leave download records behind.++ An invalid filter fails the staging activity before it reaches S3, so this needs no AWS+ credentials. The workflow should complete successfully, because this is user error, not our+ fault.+ """+ batch_export_id = str(file_download_batch_export.id)++ inputs = FileDownloadBatchExportInputs(+ team_id=ateam.pk,+ batch_export_id=batch_export_id,+ data_interval_end=data_interval_end.isoformat(),+ data_interval_start=data_interval_start.isoformat(),+ interval=interval,+ batch_export_model=BatchExportModel(+ name="events",+ schema=None,+ filters=[{"key": "event =", "type": "hogql", "value": None}],+ ),+ file_format=file_format,+ compression=compression,+ )++ async with await WorkflowEnvironment.start_time_skipping() as activity_environment:+ async with Worker(+ activity_environment.client,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ workflows=[FileDownloadBatchExportWorkflow],+ activities=[+ start_batch_export_run,+ finish_batch_export_run,+ insert_into_internal_stage_activity,+ export_to_file_download_bucket_with_temporary_credentials,+ generate_file_downloads,+ ],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ with fail_on_application_error():+ await activity_environment.client.execute_workflow(+ FileDownloadBatchExportWorkflow.run,+ inputs,+ id=str(uuid.uuid4()),+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ execution_timeout=dt.timedelta(seconds=30),+ )++ runs = await afetch_batch_export_runs(batch_export_id=batch_export_id)+ assert len(runs) == 1+ assert runs[0].status == "Failed"+ assert runs[0].latest_error is not None+ assert runs[0].latest_error.startswith("One or more provided filters are invalid")++ assert not await BatchExportFileDownload.objects.filter(team_id=ateam.pk, batch_export_run_id=runs[0].id).aexists()diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.pyindex 514aaae80950..b2080b17847c 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py@@ -274,8 +274,8 @@ class TestErrorHandling:)async def test_hogql_queries_fail_terminally_if_per_query_resource_limit_reached(self, batch_export):- """A user-supplied HogQL query that hits a per-query ClickHouse resource limit should be- fail as a non-retryable error (re-running it would not produce a different result).+ """A user-supplied HogQL query that hits a per-query ClickHouse resource limit is a user+ error, so it should fail the run but not the Temporal activity or the workflow."""inputs = DummyExportInputs(team_id=batch_export.team_id,@@ -290,7 +290,7 @@ class TestErrorHandling:"products.batch_exports.backend.temporal.pipeline.internal_stage._write_batch_export_record_batches_to_internal_stage",new=AsyncMock(side_effect=self._QUERY_MEMORY_ERROR),):- run = await self._run_workflow(inputs, expect_workflow_failure=True)+ run = await self._run_workflow(inputs, expect_workflow_failure=False)assert run.status == "Failed"assert run.latest_error is not None