Skip to content

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

refactor(batch-exports): refactor internal-stage entrypoint (#83257)

Ross26e1776fa5a1
diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
index ab3aebe9168f..fb8efa5e1d09 100644
--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py
+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
@@ -7,6 +7,7 @@ from django.conf import settings
from temporalio import exceptions, workflow
from temporalio.common import RetryPolicy
+from posthog.dataclasses import frozen
from posthog.settings.base_variables import TEST
from posthog.temporal.common.logger import get_write_only_logger
@@ -21,6 +22,7 @@ from products.batch_exports.backend.temporal.batch_exports import FinishBatchExp
from products.batch_exports.backend.temporal.metrics import get_export_finished_metric, get_export_started_metric
from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
+ InternalStageResult,
insert_into_internal_stage_activity,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
@@ -56,24 +58,174 @@ class _ComposedBatchExportInputsProtocol(typing.Protocol):
batch_export: _BatchExportInputsProtocol
-InputsType = typing.TypeVar("InputsType", bound=_BatchExportInputsProtocol)
-ComposedInputsType = typing.TypeVar("ComposedInputsType", bound=_ComposedBatchExportInputsProtocol)
+# Either the batch export inputs themselves, or an object holding them under `batch_export`.
+BatchExportInputs = _BatchExportInputsProtocol | _ComposedBatchExportInputsProtocol
BatchExportResultType = typing.TypeVar("BatchExportResultType", bound=BatchExportResult)
BatchExportInsertActivity = collections.abc.Callable[
- [InputsType | ComposedInputsType], collections.abc.Awaitable[BatchExportResultType]
+ [BatchExportInputs], collections.abc.Awaitable[BatchExportResultType]
]
INITIAL_RETRY_INTERVAL_SECONDS = 1
DEFAULT_MAX_RETRY_INTERVAL_SECONDS = 3600
DEFAULT_MAX_STAGE_RETRY_INTERVAL_SECONDS = 600
+STAGE_NON_RETRYABLE_ERROR_TYPES = (
+ "InvalidFilterError",
+ "DataIntervalEndInFutureError",
+)
+
+
+@frozen
+class IntervalConfig:
+ # Start-to-close timeouts for the run's two activities: staging the data, then exporting it.
+ main_start_to_close: dt.timedelta
+ stage_start_to_close: dt.timedelta
+ # How many recent runs `finish_batch_export_run` considers when deciding to auto-pause a
+ # failing export. A count of runs, not a duration.
+ failure_check_window: int
+
+
+def _get_config_for_interval(interval: str, override_start_to_close: dt.timedelta) -> 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 == "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.
+ return IntervalConfig(
+ main_start_to_close=max(dt.timedelta(hours=6), override_start_to_close),
+ stage_start_to_close=dt.timedelta(hours=1),
+ failure_check_window=24, # A day's worth of runs
+ )
+
+ if interval == "day":
+ return IntervalConfig(
+ main_start_to_close=max(dt.timedelta(days=1), override_start_to_close),
+ stage_start_to_close=dt.timedelta(hours=6),
+ failure_check_window=7, # A week's worth of runs
+ )
+
+ if interval == "week":
+ # TODO - review these once we have more users using weekly batch exports
+ return IntervalConfig(
+ main_start_to_close=max(dt.timedelta(days=3), override_start_to_close),
+ stage_start_to_close=dt.timedelta(days=1),
+ failure_check_window=4, # A (roughly) months' worth of runs
+ )
+
+ if interval.startswith("every"):
+ _, value, unit = interval.split(" ")
+ # TODO: Consider removing this 20 minute minimum once we are more confident about hitting 5 minute or lower SLAs.
+ main_start_to_close = max(dt.timedelta(minutes=20), dt.timedelta(**{unit: int(value)}), override_start_to_close)
+ if unit == "minutes":
+ failure_check_window = 60 // int(value) # Last hour worth of runs
+ else:
+ # Anything other than minutes is not currently supported, but just
+ # setting a default in case we ever add support for, e.g., seconds.
+ failure_check_window = 50
+ return IntervalConfig(
+ # The stage has to fit inside the main activity for sub-hourly intervals: there is no
+ # slack to give it a budget of its own.
+ main_start_to_close=main_start_to_close,
+ stage_start_to_close=main_start_to_close,
+ failure_check_window=failure_check_window,
+ )
+
+ raise ValueError(f"Unsupported interval: '{interval}'")
+
+
+def _get_status_for_activity_error(error: exceptions.ActivityError) -> BatchExportRun.Status:
+ """Decide what a failed run's status should be, given the error raised.
+
+ The error could be raised by either the `insert_into_internal_stage_activity` or the
+ `insert_into_*_activity_from_stage` activities.
+ """
+ if isinstance(error.cause, exceptions.CancelledError):
+ return BatchExportRun.Status.CANCELLED
+
+ return BatchExportRun.Status.FAILED_RETRYABLE
+
+
+async def _stage_batch_export_data(
+ batch_export_inputs: _BatchExportInputsProtocol,
+ *,
+ batch_export_id: str,
+ is_workflows: bool,
+ start_to_close_timeout: dt.timedelta,
+ heartbeat_timeout: dt.timedelta | None,
+ retry_policy: RetryPolicy,
+) -> InternalStageResult:
+ """Copy this run's data out of ClickHouse and into our internal S3 staging area.
+
+ `batch_export_id` is passed separately because the staging activity requires it while the
+ protocol types it as optional; the caller has already narrowed it.
+ """
+ stage_inputs = BatchExportInsertIntoInternalStageInputs(
+ team_id=batch_export_inputs.team_id,
+ batch_export_id=batch_export_id,
+ data_interval_start=batch_export_inputs.data_interval_start,
+ data_interval_end=batch_export_inputs.data_interval_end,
+ exclude_events=batch_export_inputs.exclude_events,
+ include_events=batch_export_inputs.include_events,
+ run_id=batch_export_inputs.run_id,
+ backfill_details=batch_export_inputs.backfill_details,
+ batch_export_model=batch_export_inputs.batch_export_model,
+ is_workflows=is_workflows,
+ batch_export_schema=batch_export_inputs.batch_export_schema,
+ destination_default_fields=batch_export_inputs.destination_default_fields,
+ )
+ # All workers now run the `InternalStageResult` path, so the pre-patch bare-string
+ # branch is gone. `deprecate_patch` keeps the marker compatible for any execution
+ # still in flight that recorded it.
+ # See https://docs.temporal.io/develop/python/workflows/versioning#deprecated-patches
+ # TODO: delete this call once those histories have drained.
+ workflow.deprecate_patch("batch-exports-stage-result")
+ return await workflow.execute_activity(
+ insert_into_internal_stage_activity,
+ stage_inputs,
+ start_to_close_timeout=start_to_close_timeout,
+ heartbeat_timeout=heartbeat_timeout,
+ retry_policy=retry_policy,
+ )
+
+
+async def _finish_run(finish_inputs: FinishBatchExportRunInputs, details: WorkflowDetails, model_name: str) -> None:
+ """Record how the run ended: its metric, its workflow details, and its `BatchExportRun` row.
+
+ Runs from a `finally`, so it must cope with every outcome — success, failure, and cancellation —
+ and `finish_inputs` carries whichever one happened.
+ """
+ get_export_finished_metric(status=finish_inputs.status.lower(), model=model_name).add(1)
+
+ bytes_exported = humanize_bytes(finish_inputs.bytes_exported) if finish_inputs.bytes_exported is not None else None
+ workflow.set_current_details(
+ details.add("Status", finish_inputs.status)
+ .add("Records completed", finish_inputs.records_completed)
+ .add("Bytes exported", bytes_exported)
+ .code_block("Error", finish_inputs.latest_error)
+ .render()
+ )
+
+ await workflow.execute_activity(
+ finish_batch_export_run,
+ finish_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=0,
+ non_retryable_error_types=["NotNullViolation", "IntegrityError"],
+ ),
+ )
+
async def execute_batch_export_using_internal_stage(
- activity: BatchExportInsertActivity,
- inputs: InputsType | ComposedInputsType,
+ activity: BatchExportInsertActivity[BatchExportResultType],
+ inputs: BatchExportInputs,
interval: str,
- heartbeat_timeout_seconds: int | None = 180,
maximum_attempts: int = 0,
initial_retry_interval_seconds: int = INITIAL_RETRY_INTERVAL_SECONDS,
maximum_retry_interval_seconds: int = DEFAULT_MAX_RETRY_INTERVAL_SECONDS,
@@ -81,30 +233,34 @@ async def execute_batch_export_using_internal_stage(
override_start_to_close_timeout_seconds: int | None = None,
is_workflows: bool = False,
) -> BatchExportResultType:
- """
- This is the entrypoint for a new version of the batch export insert activity.
+ """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
handling patterns, logging and updating run status. For this reason, we have this function
to abstract executing the main insert activity of each batch export.
- It works in a similar way to the old version of the batch export insert activity, but instead of
- reading data from ClickHouse and exporting it to the destination in batches, we break this down into 2 steps:
- 1. Exporting the batch export data directly into our own internal S3 staging area using ClickHouse
- 2. Reading the data from the internal S3 staging area and exporting it to the destination using the
- producer/consumer pattern
+ The two steps are:
+ 1. Copy the run's data from ClickHouse straight into our internal S3 staging area.
+ 2. Read it back from staging and write it to the destination (producer/consumer).
Args:
- activity: The 'insert_into_*' activity function to execute.
- inputs: The inputs to the activity.
- interval: The interval of the batch export used to set the start to close timeout.
- maximum_attempts: Maximum number of retries for the 'insert_into_*' activity function.
- Assuming the error that triggered the retry is not in non_retryable_error_types.
- initial_retry_interval_seconds: When retrying, seconds until the first retry.
- maximum_retry_interval_seconds: Maximum interval in seconds between retries.
- override_start_to_close_timeout_seconds: Optionally, override the start-to-close
- timeout of the main activity. If this is lower than the calculated default
- timeout for the main activity, then the default will be preferred.
+ activity: The 'insert_into_*' activity that writes staged data to this destination.
+ inputs: Inputs for that activity — either the batch export inputs themselves, or an object
+ holding them under a `batch_export` attribute.
+ interval: The export's interval, which sets both activity timeouts and the failure-check
+ window. See `_get_config_for_interval`.
+ maximum_attempts: Retry limit for both activities, for errors not in their non-retryable
+ lists. 0 means unlimited; forced to 1 under TEST.
+ initial_retry_interval_seconds: Seconds until the first retry.
+ maximum_retry_interval_seconds: Ceiling on the gap between retries of `activity`.
+ maximum_stage_retry_interval_seconds: The same ceiling for the staging activity.
+ override_start_to_close_timeout_seconds: Raises `activity`'s start-to-close timeout. Only
+ ever grants more time: a value below the interval's own timeout is ignored.
+ is_workflows: Whether this export reads the workflows model, which is staged by a different
+ query.
+
+ Returns:
+ The destination activity's result.
"""
if hasattr(inputs, "batch_export"):
batch_export_inputs: _BatchExportInputsProtocol = inputs.batch_export # ty: ignore[invalid-assignment]
@@ -130,48 +286,13 @@ async def execute_batch_export_using_internal_stage(
if TEST:
maximum_attempts = 1
- if isinstance(settings.BATCH_EXPORT_HEARTBEAT_TIMEOUT_SECONDS, int):
- heartbeat_timeout_seconds = settings.BATCH_EXPORT_HEARTBEAT_TIMEOUT_SECONDS
-
- override_start_to_close_timeout_timedelta = dt.timedelta(seconds=override_start_to_close_timeout_seconds or 0)
- failure_check_window = 50 # Default, overriden based on interval
-
- 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.
- main_activity_start_to_close_timeout = max(dt.timedelta(hours=6), override_start_to_close_timeout_timedelta)
- stage_activity_start_to_close_timeout = dt.timedelta(hours=1)
- failure_check_window = 24 # A day's worth of runs
-
- elif interval == "day":
- main_activity_start_to_close_timeout = max(dt.timedelta(days=1), override_start_to_close_timeout_timedelta)
- stage_activity_start_to_close_timeout = dt.timedelta(hours=6)
- failure_check_window = 7 # A week's worth of runs
-
- elif interval == "week":
- # TODO - review these once we have more users using weekly batch exports
- main_activity_start_to_close_timeout = max(dt.timedelta(days=3), override_start_to_close_timeout_timedelta)
- stage_activity_start_to_close_timeout = dt.timedelta(days=1)
- failure_check_window = 4 # A (roughly) months' worth of runs
-
- elif interval.startswith("every"):
- _, value, unit = interval.split(" ")
- kwargs = {unit: int(value)}
- # TODO: Consider removing this 20 minute minimum once we are more confident about hitting 5 minute or lower SLAs.
- main_activity_start_to_close_timeout = max(
- dt.timedelta(minutes=20), dt.timedelta(**kwargs), override_start_to_close_timeout_timedelta
- )
- stage_activity_start_to_close_timeout = main_activity_start_to_close_timeout
+ # Both activities share one heartbeat timeout. Setting it to 0 disables heartbeat timeouts.
+ heartbeat_timeout_seconds = settings.BATCH_EXPORT_HEARTBEAT_TIMEOUT_SECONDS
+ heartbeat_timeout = dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None
- if unit == "minutes":
- runs_in_an_hour = 60 // int(value)
- failure_check_window = runs_in_an_hour # Last hour worth of runs
- else:
- # Anything other than minutes is not currently supported, but just
- # setting a default in case we ever add support for, e.g., seconds.
- failure_check_window = 50
- else:
- raise ValueError(f"Unsupported interval: '{interval}'")
+ interval_config = _get_config_for_interval(
+ interval, dt.timedelta(seconds=override_start_to_close_timeout_seconds or 0)
+ )
finish_inputs = FinishBatchExportRunInputs(
id=batch_export_inputs.run_id,
@@ -179,52 +300,34 @@ async def execute_batch_export_using_internal_stage(
status=BatchExportRun.Status.COMPLETED,
team_id=batch_export_inputs.team_id,
on_demand=batch_export_inputs.on_demand,
- failure_check_window=failure_check_window,
+ failure_check_window=interval_config.failure_check_window,
)
try:
- stage_inputs = BatchExportInsertIntoInternalStageInputs(
- team_id=batch_export_inputs.team_id,
+ stage_result = await _stage_batch_export_data(
+ batch_export_inputs,
batch_export_id=batch_export_inputs.batch_export_id,
- data_interval_start=batch_export_inputs.data_interval_start,
- data_interval_end=batch_export_inputs.data_interval_end,
- exclude_events=batch_export_inputs.exclude_events,
- include_events=batch_export_inputs.include_events,
- run_id=batch_export_inputs.run_id,
- backfill_details=batch_export_inputs.backfill_details,
- batch_export_model=batch_export_inputs.batch_export_model,
is_workflows=is_workflows,
- batch_export_schema=batch_export_inputs.batch_export_schema,
- destination_default_fields=batch_export_inputs.destination_default_fields,
- )
- stage_activity_kwargs: dict[str, typing.Any] = {
- "start_to_close_timeout": stage_activity_start_to_close_timeout,
- "heartbeat_timeout": dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None,
- "retry_policy": RetryPolicy(
+ start_to_close_timeout=interval_config.stage_start_to_close,
+ heartbeat_timeout=heartbeat_timeout,
+ retry_policy=RetryPolicy(
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", "DataIntervalEndInFutureError"],
+ non_retryable_error_types=list(STAGE_NON_RETRYABLE_ERROR_TYPES),
),
- }
- # All workers now run the `InternalStageResult` path, so the pre-patch bare-string
- # branch is gone. `deprecate_patch` keeps the marker compatible for any execution
- # still in flight that recorded it.
- # See https://docs.temporal.io/develop/python/workflows/versioning#deprecated-patches
- # TODO: delete this call once those histories have drained.
- workflow.deprecate_patch("batch-exports-stage-result")
- stage_result = await workflow.execute_activity(
- insert_into_internal_stage_activity, stage_inputs, **stage_activity_kwargs
)
+
batch_export_inputs.stage_folder = stage_result.stage_folder
batch_export_inputs.records_total = stage_result.records_total
if stage_result.records_total is not None:
workflow.set_current_details(details.add("Staged records", stage_result.records_total).render())
+
result = await workflow.execute_activity(
activity,
inputs,
- start_to_close_timeout=main_activity_start_to_close_timeout,
- heartbeat_timeout=dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None,
+ start_to_close_timeout=interval_config.main_start_to_close,
+ heartbeat_timeout=heartbeat_timeout,
retry_policy=RetryPolicy(
initial_interval=dt.timedelta(seconds=initial_retry_interval_seconds),
maximum_interval=dt.timedelta(seconds=maximum_retry_interval_seconds),
@@ -239,11 +342,7 @@ async def execute_batch_export_using_internal_stage(
finish_inputs.status = BatchExportRun.Status.FAILED
except exceptions.ActivityError as e:
- if isinstance(e.cause, exceptions.CancelledError):
- finish_inputs.status = BatchExportRun.Status.CANCELLED
- else:
- finish_inputs.status = BatchExportRun.Status.FAILED_RETRYABLE
-
+ finish_inputs.status = _get_status_for_activity_error(e)
finish_inputs.latest_error = str(e.cause)
raise
@@ -253,29 +352,6 @@ async def execute_batch_export_using_internal_stage(
raise
finally:
- get_export_finished_metric(status=finish_inputs.status.lower(), model=model_name).add(1)
-
- bytes_exported = (
- humanize_bytes(finish_inputs.bytes_exported) if finish_inputs.bytes_exported is not None else None
- )
- workflow.set_current_details(
- details.add("Status", finish_inputs.status)
- .add("Records completed", finish_inputs.records_completed)
- .add("Bytes exported", bytes_exported)
- .code_block("Error", finish_inputs.latest_error)
- .render()
- )
-
- await workflow.execute_activity(
- finish_batch_export_run,
- finish_inputs,
- start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=RetryPolicy(
- initial_interval=dt.timedelta(seconds=10),
- maximum_interval=dt.timedelta(seconds=60),
- maximum_attempts=0,
- non_retryable_error_types=["NotNullViolation", "IntegrityError"],
- ),
- )
+ await _finish_run(finish_inputs, details, model_name)
return result