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.

chore(batch-exports): skip calculating staging partitions for on-demand exports (#100243)

Ross923dff01b61b
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 1743603a78bf..d4bfd9a00e48 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -6,7 +6,6 @@ from dataclasses import Field, asdict, dataclass, field, fields
from uuid import UUID
from django.conf import settings
-from django.db.models import Q
import structlog
import temporalio
@@ -1359,7 +1358,7 @@ async def aupdate_records_total_count(
async def afetch_last_run_records_completed(
- parent_id: UUID,
+ batch_export_id: UUID,
*,
matching_interval_duration: dt.timedelta | None,
before_or_at_interval_end: dt.datetime | None = None,
@@ -1367,9 +1366,9 @@ async def afetch_last_run_records_completed(
) -> int | None:
"""Async fetch the `records_completed` of the most recent completed run for a batch export.
- Used as a rough estimate to pick how many staging files to write. A run belongs to exactly one of
- a `BatchExport` (scheduled) or a `BatchExportOnDemand`, and their ids are globally unique UUIDs, so
- we match `parent_id` against either parent.
+ Used as a rough estimate to pick how many staging files to write. Only scheduled `BatchExport`
+ runs are matched. A `BatchExportOnDemand` is created for each request and runs once, so it has no
+ earlier run to estimate from, and `compute_num_partitions` does not call this for one.
The `before_or_at_interval_end` and `not_older_than` filters are relative to the interval being
processed (which improves accuracy for backfills):
@@ -1385,7 +1384,7 @@ async def afetch_last_run_records_completed(
Returns None when no usable run exists (e.g. the first ever run, or a frequency change).
"""
queryset = BatchExportRun.objects.filter(
- Q(batch_export_id=parent_id) | Q(batch_export_on_demand_id=parent_id),
+ batch_export_id=batch_export_id,
status=BatchExportRun.Status.COMPLETED,
records_completed__isnull=False,
)
diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
index 79e39c82b366..fb4493a8706f 100644
--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py
+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
@@ -185,6 +185,7 @@ async def _stage_batch_export_data(
backfill_details=batch_export_inputs.backfill_details,
batch_export_model=batch_export_inputs.batch_export_model,
is_workflows=is_workflows,
+ on_demand=batch_export_inputs.on_demand,
batch_export_schema=batch_export_inputs.batch_export_schema,
destination_default_fields=batch_export_inputs.destination_default_fields,
)
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 9a0731d12b9b..1138d19e0489 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -274,7 +274,7 @@ class InternalStageResult:
error: BatchExportError | None = None
-@dataclass
+@frozen
class BatchExportInsertIntoInternalStageInputs:
"""Base dataclass for batch export insert inputs containing common fields."""
@@ -288,6 +288,7 @@ class BatchExportInsertIntoInternalStageInputs:
backfill_details: BackfillDetails | None = None
batch_export_model: BatchExportModel | None = None
is_workflows: bool = False
+ on_demand: bool = False
# TODO: Remove after updating existing batch exports
batch_export_schema: BatchExportSchema | None = None
destination_default_fields: list[BatchExportField] | None = None
@@ -354,6 +355,7 @@ async def insert_into_internal_stage_activity(
batch_export_id=inputs.batch_export_id,
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
+ on_demand=inputs.on_demand,
)
logger.info("Computed staging partitions", num_partitions=num_partitions)
@@ -437,7 +439,10 @@ 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
+ batch_export_id: str,
+ data_interval_start: dt.datetime | None,
+ data_interval_end: dt.datetime,
+ on_demand: bool = False,
) -> int:
"""Choose how many staging files (partitions) to write for this run.
@@ -453,11 +458,14 @@ async def compute_num_partitions(
We fall back to the static default when there is no usable estimate (first run, frequency
change, or a run with no recorded count), if the fetch fails, or if dynamic partitioning is
disabled entirely via BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED.
+
+ An on-demand export skips the estimate without querying. Each request creates its own
+ `BatchExportOnDemand` and runs once, so there is never an earlier run to size from.
"""
logger = LOGGER.bind()
static_default = settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS
- if not settings.BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED:
+ if not settings.BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED or on_demand:
return static_default
# Without the current interval's bounds we can't match the previous run's frequency, so don't risk
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.py
index cc588d41641d..f5368123264f 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
@@ -18,7 +18,6 @@ import pytest_asyncio
from structlog.testing import capture_logs
from temporalio.testing import ActivityEnvironment
-from posthog.models.scoping import team_scope
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import (
@@ -34,12 +33,7 @@ from posthog.temporal.tests.utils.events import (
insert_sessions_in_clickhouse,
)
-from products.batch_exports.backend.models.batch_export import (
- BatchExport,
- BatchExportDestination,
- BatchExportOnDemand,
- BatchExportRun,
-)
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
from products.batch_exports.backend.service import BackfillDetails, BatchExportModel, afetch_last_run_records_completed
from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
@@ -869,29 +863,27 @@ async def test_compute_num_partitions_db_error_falls_back_to_static_default():
assert result == 10
-async def test_compute_num_partitions_disabled_uses_static_default():
- with (
- override_settings(
- BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED=False,
- BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=10,
- ),
- patch(_FETCHER_PATH, new=AsyncMock(return_value=5_000_000)) as mock_fetch,
- ):
- result = await compute_num_partitions(
- batch_export_id=str(uuid.uuid4()), data_interval_start=_INTERVAL_START, data_interval_end=_INTERVAL_END
- )
- assert result == 10
- mock_fetch.assert_not_called()
-
-
-async def test_compute_num_partitions_without_interval_start_falls_back_to_static_default():
- """An unbounded interval (no start) gives no frequency to match, so we don't risk an estimate."""
+ "settings_overrides, call_overrides",
+ [
+ ({"BATCH_EXPORT_DYNAMIC_PARTITIONING_ENABLED": False}, {}),
+ ({}, {"data_interval_start": None}),
+ ({}, {"on_demand": True}),
+ ],
+ ids=["dynamic partitioning disabled", "unbounded interval", "on-demand export"],
+)
+async def test_compute_num_partitions_skips_the_estimate(settings_overrides, call_overrides):
with (
- override_settings(BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=10),
+ override_settings(BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=10, **settings_overrides),
patch(_FETCHER_PATH, new=AsyncMock(return_value=5_000_000)) as mock_fetch,
):
result = await compute_num_partitions(
- batch_export_id=str(uuid.uuid4()), data_interval_start=None, data_interval_end=_INTERVAL_END
+ **{
+ "batch_export_id": str(uuid.uuid4()),
+ "data_interval_start": _INTERVAL_START,
+ "data_interval_end": _INTERVAL_END,
+ **call_overrides,
+ }
)
assert result == 10
mock_fetch.assert_not_called()
@@ -988,26 +980,6 @@ async def test_afetch_last_run_records_completed_no_runs(ateam):
)
-async def test_afetch_last_run_records_completed_for_on_demand_export(ateam):
- destination = await BatchExportDestination.objects.acreate(
- type="S3", config={"bucket_name": "test-bucket", "region": "us-east-1", "prefix": "test"}
- )
- with team_scope(team_id=ateam.pk, canonical=True):
- on_demand = await BatchExportOnDemand.objects.acreate(team_id=ateam.pk, destination=destination, model="events")
- base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
- await BatchExportRun.objects.acreate(
- batch_export_on_demand_id=on_demand.id,
- data_interval_start=base,
- data_interval_end=base + dt.timedelta(hours=1),
- status=BatchExportRun.Status.COMPLETED,
- records_completed=321,
- )
-
- assert (
- await afetch_last_run_records_completed(on_demand.id, matching_interval_duration=dt.timedelta(hours=1)) == 321
- )
-
-
async def test_afetch_last_run_records_completed_none_duration_skips_frequency_check(ateam):
"""Passing None opts out of the frequency check: the latest run is returned whatever its interval."""
batch_export = await _acreate_batch_export_for_test(ateam.pk)