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.

feat(batch-exports): size staging partitions dynamically and cap producer reads (#62123)

Ross45f102526a07
diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.py
index ca58062e3b8e..99aff62474aa 100644
--- a/posthog/settings/batch_exports.py
+++ b/posthog/settings/batch_exports.py
@@ -83,8 +83,26 @@ BATCH_EXPORT_OBJECT_STORAGE_ENDPOINT: str = os.getenv(
)
BATCH_EXPORT_OBJECT_STORAGE_REGION: str = os.getenv("BATCH_EXPORT_OBJECT_STORAGE_REGION", "us-east-1")
BATCH_EXPORT_INTERNAL_STAGING_BUCKET: str = os.getenv("BATCH_EXPORT_INTERNAL_STAGING_BUCKET", "posthog")
-# The number of partitions controls how many files ClickHouse writes to concurrently
+# The number of partitions controls how many files ClickHouse writes to concurrently. Used as the fallback
+# when we have no size estimate to drive a dynamic partition count (e.g. the first ever run of an export).
BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS: int = get_from_env("BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS", 10, type_cast=int)
+# When a previous run's row count is known, the staging partition count is chosen to target roughly this many
+# rows per staging Arrow file (file size ≈ rows × per-team row width), clamped to [MIN, MAX]. Set MIN == MAX to
+# pin the partition count back to a fixed value.
+BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION: int = get_from_env(
+ "BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION", 250_000, type_cast=int
+)
+BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS: int = get_from_env(
+ "BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS", 1, type_cast=int
+)
+BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS: int = get_from_env(
+ "BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS", 50, type_cast=int
+)
+# Caps how many staging files the producer streams from S3 concurrently. This decouples read concurrency
+# from the number of files written (which scales with export size)
+BATCH_EXPORT_PRODUCER_MAX_CONCURRENT_FILE_READS: int = get_from_env(
+ "BATCH_EXPORT_PRODUCER_MAX_CONCURRENT_FILE_READS", 5, type_cast=int
+)
BATCH_EXPORT_TRANSFORMER_MAX_WORKERS: int = get_from_env("BATCH_EXPORT_TRANSFORMER_MAX_WORKERS", 2, type_cast=int)
BATCH_EXPORTS_ENABLE_BILLING_CHECK: bool = get_from_env(
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 117e3010b0ad..3333d1d11ede 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -6,6 +6,7 @@ from dataclasses import Field, asdict, dataclass, fields
from uuid import UUID
from django.conf import settings
+from django.db.models import Q
import structlog
import temporalio
@@ -1289,6 +1290,57 @@ async def aupdate_records_total_count(
return rows_updated
+async def afetch_last_run_records_completed(
+ parent_id: UUID,
+ *,
+ matching_interval_duration: dt.timedelta | None,
+ before_or_at_interval_end: dt.datetime | None = None,
+ not_older_than: dt.datetime | None = None,
+) -> 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.
+
+ The `before_or_at_interval_end` and `not_older_than` filters are relative to the interval being
+ processed (which improves accuracy for backfills):
+ - `before_or_at_interval_end`: only runs whose `data_interval_end` is at or before it.
+ - `not_older_than`: only runs whose `data_interval_end` is at or after it, to ignore stale runs from
+ a long-paused export.
+
+ `matching_interval_duration` is the current interval's length. We look only at the single most
+ recent run and return its count only if that run's own interval length matches; if the export's
+ frequency changed, the latest run isn't comparable, so we return None and let the next run (which
+ will have a same-frequency predecessor) re-adjust.
+
+ 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),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed__isnull=False,
+ )
+ if before_or_at_interval_end is not None:
+ queryset = queryset.filter(data_interval_end__lte=before_or_at_interval_end)
+ if not_older_than is not None:
+ queryset = queryset.filter(data_interval_end__gte=not_older_than)
+
+ run = (
+ await queryset.order_by("-data_interval_end")
+ .values("records_completed", "data_interval_start", "data_interval_end")
+ .afirst()
+ )
+ if run is None:
+ return None
+ if 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
+ if last_interval_duration != matching_interval_duration:
+ return None
+ return run["records_completed"]
+
+
async def afetch_batch_export_runs_in_range(
batch_export_id: UUID,
interval_start: dt.datetime,
diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
index 19b58bc64552..bcd055521075 100644
--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py
+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
@@ -72,7 +72,6 @@ async def execute_batch_export_using_internal_stage(
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,
- num_partitions: int | None = None,
is_workflows: bool = False,
) -> BatchExportResultType:
"""
@@ -99,8 +98,6 @@ async def execute_batch_export_using_internal_stage(
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.
- num_partitions: Optionally, set a number of partitions for the internal stage
- activity.
"""
if hasattr(inputs, "batch_export"):
batch_export_inputs: _BatchExportInputsProtocol = inputs.batch_export # ty: ignore[invalid-assignment]
@@ -164,7 +161,6 @@ async def execute_batch_export_using_internal_stage(
run_id=batch_export_inputs.run_id,
backfill_details=batch_export_inputs.backfill_details,
batch_export_model=batch_export_inputs.batch_export_model,
- num_partitions=num_partitions,
is_workflows=is_workflows,
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 ecea886ffc0d..5073f77a0003 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -1,4 +1,5 @@
import sys
+import math
import uuid
import socket
import typing
@@ -42,6 +43,7 @@ from products.batch_exports.backend.service import (
BatchExportField,
BatchExportModel,
BatchExportSchema,
+ afetch_last_run_records_completed,
)
from products.batch_exports.backend.temporal.batch_exports import default_fields
from products.batch_exports.backend.temporal.metrics import log_query_duration
@@ -198,7 +200,6 @@ class BatchExportInsertIntoInternalStageInputs:
run_id: str | None = None
backfill_details: BackfillDetails | None = None
batch_export_model: BatchExportModel | None = None
- num_partitions: int | None = None
is_workflows: bool = False
# TODO: Remove after updating existing batch exports
batch_export_schema: BatchExportSchema | None = None
@@ -215,7 +216,6 @@ class BatchExportInsertIntoInternalStageInputs:
"exclude_events": self.exclude_events,
"include_events": self.include_events,
"run_id": self.run_id,
- "num_partitions": self.num_partitions,
"backfill_details": self.backfill_details,
"batch_export_model": self.batch_export_model,
"batch_export_schema": self.batch_export_schema,
@@ -260,6 +260,13 @@ async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInter
attempt_number=attempt_number,
)
+ num_partitions = await compute_num_partitions(
+ batch_export_id=inputs.batch_export_id,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ )
+ logger.info("Computed staging partitions", num_partitions=num_partitions)
+
if record_batch_model is not None:
query_or_model = record_batch_model
query_parameters = {}
@@ -279,7 +286,7 @@ async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInter
exclude_events=inputs.exclude_events,
include_events=inputs.include_events,
extra_query_parameters=extra_query_parameters,
- num_partitions=inputs.num_partitions,
+ num_partitions=num_partitions,
is_workflows=inputs.is_workflows,
)
query_or_model = query
@@ -293,12 +300,61 @@ async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInter
data_interval_start=inputs.data_interval_start,
data_interval_end=inputs.data_interval_end,
s3_staging_folder_url=s3_staging_folder.url,
- num_partitions=inputs.num_partitions,
+ num_partitions=num_partitions,
)
logger.info("Staging data completed successfully")
return s3_staging_folder.folder
+async def compute_num_partitions(
+ batch_export_id: str, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime
+) -> int:
+ """Choose how many staging files (partitions) to write for this run.
+
+ We estimate the export size from the most recent completed run at or before the interval being
+ processed, then pick a partition count targeting a roughly-constant number of rows per staging
+ Arrow file, clamped to [MIN, MAX].
+
+ Sizing relative to the current interval keeps backfills of old intervals from being sized off
+ today's (potentially much larger) live runs. We size off the most recent run only if its interval
+ length matches this one's, so a change in export frequency doesn't size off a differently-sized
+ interval (we fall back and let the next run, which has a same-frequency predecessor, re-adjust).
+
+ We fall back to the static default when there is no usable estimate (first run, frequency
+ change, or a run with no recorded count) or if the fetch fails.
+ """
+ logger = LOGGER.bind()
+ static_default = settings.BATCH_EXPORT_CLICKHOUSE_S3_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:
+ return static_default
+ interval_duration = data_interval_end - data_interval_start
+
+ estimate_rows: int | None = None
+ try:
+ estimate_rows = await afetch_last_run_records_completed(
+ uuid.UUID(batch_export_id),
+ before_or_at_interval_end=data_interval_end,
+ # ignore stale runs from a long-paused export
+ not_older_than=data_interval_end - dt.timedelta(days=365),
+ matching_interval_duration=interval_duration,
+ )
+ except Exception:
+ logger.warning("Failed to fetch last run records completed; falling back to static default", exc_info=True)
+ if not estimate_rows or estimate_rows <= 0:
+ return static_default
+
+ min_partitions = settings.BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS
+ # guard against misconfiguration where max is set below min
+ max_partitions = max(settings.BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS, min_partitions)
+ # guard against misconfiguration where the target is set to 0
+ target_rows = max(settings.BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION, 1)
+ n = math.ceil(estimate_rows / target_rows)
+ return max(min_partitions, min(n, max_partitions))
+
+
async def _get_query(
model_name: str,
backfill_details: BackfillDetails | None,
diff --git a/products/batch_exports/backend/temporal/pipeline/producer.py b/products/batch_exports/backend/temporal/pipeline/producer.py
index 221a9399fe79..2e065987af93 100644
--- a/products/batch_exports/backend/temporal/pipeline/producer.py
+++ b/products/batch_exports/backend/temporal/pipeline/producer.py
@@ -119,9 +119,19 @@ class Producer:
self.logger.info("Finished stream", key=key)
+ stream_func = make_retryable_with_exponential_backoff(stream_from_s3_file, max_attempts=5, max_retry_delay=1)
+
+ # Bound how many files we read at once (so S3 connections and in-flight memory stay bounded as
+ # the file count grows with export size).
+ semaphore = asyncio.Semaphore(settings.BATCH_EXPORT_PRODUCER_MAX_CONCURRENT_FILE_READS)
+
+ async def stream_with_semaphore(key):
+ try:
+ await stream_func(key)
+ finally:
+ semaphore.release()
+
async with asyncio.TaskGroup() as tg:
- stream_func = make_retryable_with_exponential_backoff(
- stream_from_s3_file, max_attempts=5, max_retry_delay=1
- )
for key in keys:
- tg.create_task(stream_func(key))
+ await semaphore.acquire()
+ tg.create_task(stream_with_semaphore(key))
diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
index ee1192d0e96f..e7e4dc2805a2 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
@@ -73,7 +73,6 @@ async def _run_activity(
include_events=None,
run_id=None,
backfill_details=None,
- num_partitions=1,
is_workflows=True,
batch_export_model=workflows_inputs.batch_export.batch_export_model,
batch_export_schema=workflows_inputs.batch_export.batch_export_schema,
@@ -181,7 +180,6 @@ async def test_insert_into_workflows_activity_from_stage_fails_on_non_retryable_
include_events=None,
run_id=None,
backfill_details=None,
- num_partitions=1,
is_workflows=True,
batch_export_model=workflows_inputs.batch_export.batch_export_model,
batch_export_schema=workflows_inputs.batch_export.batch_export_schema,
@@ -325,7 +323,6 @@ async def test_insert_into_workflows_activity_from_stage_fails_when_hog_function
include_events=None,
run_id=None,
backfill_details=None,
- num_partitions=1,
is_workflows=True,
batch_export_model=workflows_inputs.batch_export.batch_export_model,
batch_export_schema=workflows_inputs.batch_export.batch_export_schema,
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 04fe41c81ada..fb7cd4526791 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
@@ -6,7 +6,7 @@ import datetime as dt
from collections.abc import AsyncGenerator
import pytest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
from django.conf import settings
from django.test.utils import override_settings
@@ -15,13 +15,21 @@ import pyarrow as pa
import pytest_asyncio
from temporalio.testing import ActivityEnvironment
+from posthog.models.scoping import team_scope
from posthog.temporal.common.clickhouse import ClickHouseClient
-from products.batch_exports.backend.service import BackfillDetails, BatchExportModel
+from products.batch_exports.backend.models.batch_export import (
+ BatchExport,
+ BatchExportDestination,
+ BatchExportOnDemand,
+ 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,
DataIntervalEndInFutureError,
_write_batch_export_record_batches_to_internal_stage,
+ compute_num_partitions,
insert_into_internal_stage_activity,
)
from products.batch_exports.backend.temporal.pipeline.producer import Producer
@@ -581,3 +589,401 @@ async def test_insert_into_stage_activity_for_persons_model(
model=model,
)
assert_exported_rows_match_persons_to_export(records_exported, new_persons_to_export)
+
+
+_FETCHER_PATH = "products.batch_exports.backend.temporal.pipeline.internal_stage.afetch_last_run_records_completed"
+_INTERVAL_END = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+_INTERVAL_START = _INTERVAL_END - dt.timedelta(hours=1)
+
+
+ "estimate_rows, target, min_partitions, max_partitions, static_default, expected",
+ [
+ (None, 1_000_000, 1, 50, 10, 10), # no estimate -> static default
+ (0, 1_000_000, 1, 50, 10, 10), # zero -> static default
+ (-5, 1_000_000, 1, 50, 10, 10), # negative -> static default
+ (1, 1_000_000, 1, 50, 10, 1), # tiny -> min
+ (1_000_000, 1_000_000, 1, 50, 10, 1), # exactly target -> 1
+ (1_000_001, 1_000_000, 1, 50, 10, 2), # just over -> ceil to 2
+ (5_000_000, 1_000_000, 1, 50, 10, 5),
+ (10_000_000_000, 1_000_000, 1, 50, 10, 50), # huge -> max
+ (5_000_000, 1_000_000, 10, 50, 10, 10), # ceil(5) below min floor -> min
+ (100, 1_000_000, 5, 3, 10, 5), # max < min misconfig -> guarded, clamps to min
+ (5_000_000, 0, 1, 50, 10, 50), # target of 0 misconfig -> guarded (no ZeroDivisionError), clamps to max
+ ],
+)
+async def test_compute_num_partitions(estimate_rows, target, min_partitions, max_partitions, static_default, expected):
+ with (
+ override_settings(
+ BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=static_default,
+ BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION=target,
+ BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=min_partitions,
+ BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=max_partitions,
+ ),
+ patch(_FETCHER_PATH, new=AsyncMock(return_value=estimate_rows)),
+ ):
+ result = await compute_num_partitions(
+ batch_export_id=str(uuid.uuid4()), data_interval_start=_INTERVAL_START, data_interval_end=_INTERVAL_END
+ )
+ assert result == expected
+
+
+async def test_compute_num_partitions_db_error_falls_back_to_static_default():
+ with (
+ override_settings(BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=10),
+ patch(_FETCHER_PATH, new=AsyncMock(side_effect=Exception("db unavailable"))),
+ ):
+ result = await compute_num_partitions(
+ batch_export_id=str(uuid.uuid4()), data_interval_start=_INTERVAL_START, data_interval_end=_INTERVAL_END
+ )
+ assert result == 10
+
+
+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."""
+ with (
+ override_settings(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=None, data_interval_end=_INTERVAL_END
+ )
+ assert result == 10
+ mock_fetch.assert_not_called()
+
+
+async def test_compute_num_partitions_fetches_estimate_relative_to_interval():
+ with (
+ override_settings(
+ BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION=1_000_000,
+ BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=1,
+ BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=50,
+ ),
+ patch(_FETCHER_PATH, new=AsyncMock(return_value=4_500_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 == 5 # ceil(4_500_000 / 1_000_000)
+ # The estimate is fetched relative to the interval being processed, and only from runs of the same
+ # frequency (interval duration) within the lookback window.
+ kwargs = mock_fetch.call_args.kwargs
+ assert kwargs["before_or_at_interval_end"] == _INTERVAL_END
+ assert kwargs["matching_interval_duration"] == _INTERVAL_END - _INTERVAL_START
+ assert kwargs["not_older_than"] < _INTERVAL_END
+
+
+async def _acreate_batch_export_for_test(team_id: int, interval: str = "hour") -> BatchExport:
+ """Create a minimal BatchExport via the ORM (no Temporal schedule) for FK-backed run rows."""
+ destination = await BatchExportDestination.objects.acreate(
+ type="S3",
+ config={"bucket_name": "test-bucket", "region": "us-east-1", "prefix": "test"},
+ )
+ return await BatchExport.objects.acreate(
+ team_id=team_id,
+ name="test-dynamic-partitions",
+ destination=destination,
+ interval=interval,
+ model="events",
+ )
+
+
+async def test_afetch_last_run_records_completed(ateam):
+ batch_export = await _acreate_batch_export_for_test(ateam.pk)
+ base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+
+ # An older completed run.
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base,
+ data_interval_end=base + dt.timedelta(hours=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=100,
+ )
+ # The most recent completed run with a recorded count -> should win.
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base + dt.timedelta(hours=1),
+ data_interval_end=base + dt.timedelta(hours=2),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=250,
+ )
+ # A newer run, but FAILED -> ignored.
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base + dt.timedelta(hours=2),
+ data_interval_end=base + dt.timedelta(hours=3),
+ status=BatchExportRun.Status.FAILED,
+ records_completed=9999,
+ )
+ # The newest completed run, but with no recorded count -> ignored.
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base + dt.timedelta(hours=3),
+ data_interval_end=base + dt.timedelta(hours=4),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=None,
+ )
+
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id, matching_interval_duration=batch_export.interval_time_delta
+ )
+ == 250
+ )
+
+
+async def test_afetch_last_run_records_completed_no_runs(ateam):
+ batch_export = await _acreate_batch_export_for_test(ateam.pk)
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id, matching_interval_duration=batch_export.interval_time_delta
+ )
+ is None
+ )
+
+
+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)
+ base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base,
+ data_interval_end=base + dt.timedelta(days=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=100,
+ )
+
+ assert await afetch_last_run_records_completed(batch_export.id, matching_interval_duration=None) == 100
+
+
+async def test_afetch_last_run_records_completed_relative_to_interval(ateam):
+ """The estimate is taken from the interval next to the one being processed, not the globally latest run."""
+ batch_export = await _acreate_batch_export_for_test(ateam.pk, interval="day")
+ base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+
+ # A small historical interval (e.g. an old backfill day).
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base,
+ data_interval_end=base + dt.timedelta(days=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=100,
+ )
+ # A much larger interval far in the future (e.g. today's live run).
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base + dt.timedelta(days=400),
+ data_interval_end=base + dt.timedelta(days=401),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=10_000_000,
+ )
+
+ # Processing an interval just after the historical one -> sized off the small neighbour, not today's run.
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id,
+ matching_interval_duration=batch_export.interval_time_delta,
+ before_or_at_interval_end=base + dt.timedelta(days=2),
+ )
+ == 100
+ )
+ # Without the bound we'd pick the globally latest (much larger) run.
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id, matching_interval_duration=batch_export.interval_time_delta
+ )
+ == 10_000_000
+ )
+
+
+async def test_afetch_last_run_records_completed_matching_interval_duration(ateam):
+ """Only the latest run is considered; if its interval differs from the requested duration -> None."""
+ batch_export = await _acreate_batch_export_for_test(ateam.pk)
+ base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+
+ # An older daily run (1-day interval).
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base,
+ data_interval_end=base + dt.timedelta(days=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=9000,
+ )
+ # The most recent run is hourly (e.g. the export's frequency just changed to hourly).
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base + dt.timedelta(days=30),
+ data_interval_end=base + dt.timedelta(days=30, hours=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=50,
+ )
+
+ # Current interval matches the export's (hourly) -> latest run matches -> use it.
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id, matching_interval_duration=batch_export.interval_time_delta
+ )
+ == 50
+ )
+ # Current interval is daily -> latest run (hourly) doesn't match -> None, even though an older daily
+ # run exists: we don't search past the latest run; the next daily run will re-adjust.
+ assert (
+ await afetch_last_run_records_completed(batch_export.id, matching_interval_duration=dt.timedelta(days=1))
+ is None
+ )
+
+
+async def test_afetch_last_run_records_completed_ignores_runs_older_than(ateam):
+ batch_export = await _acreate_batch_export_for_test(ateam.pk)
+ base = dt.datetime(2024, 1, 1, tzinfo=dt.UTC)
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=base,
+ data_interval_end=base + dt.timedelta(hours=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=100,
+ )
+
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id,
+ matching_interval_duration=batch_export.interval_time_delta,
+ not_older_than=base - dt.timedelta(days=1),
+ )
+ == 100
+ )
+ assert (
+ await afetch_last_run_records_completed(
+ batch_export.id,
+ matching_interval_duration=batch_export.interval_time_delta,
+ not_older_than=base + dt.timedelta(days=1),
+ )
+ is None
+ )
+
+
[email protected]("interval", ["day"], indirect=True)
[email protected]("model", [BatchExportModel(name="events", schema=None)])
[email protected]("data_interval_end", [TEST_DATA_INTERVAL_END])
+async def test_insert_into_stage_activity_writes_dynamic_number_of_files(
+ generate_test_data,
+ interval,
+ activity_environment,
+ data_interval_start,
+ minio_client,
+ data_interval_end,
+ ateam,
+ model: BatchExportModel,
+):
+ """A previous run's row count drives how many staging files the activity writes."""
+ batch_export = await _acreate_batch_export_for_test(ateam.pk)
+ # The preceding interval (one day earlier) is what should be used as the estimate.
+ await BatchExportRun.objects.acreate(
+ batch_export_id=batch_export.id,
+ data_interval_start=data_interval_start - dt.timedelta(days=1),
+ data_interval_end=data_interval_end - dt.timedelta(days=1),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=12,
+ )
+
+ insert_inputs = BatchExportInsertIntoInternalStageInputs(
+ team_id=ateam.pk,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=data_interval_start.isoformat(),
+ data_interval_end=data_interval_end.isoformat(),
+ exclude_events=None,
+ include_events=None,
+ run_id=None,
+ batch_export_schema=None,
+ batch_export_model=model,
+ backfill_details=None,
+ destination_default_fields=None,
+ )
+
+ # 12 rows at 2 rows/file -> ceil(12 / 2) = 6 partitions (within [1, 50]).
+ with override_settings(
+ BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION=2,
+ BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=1,
+ BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=50,
+ ):
+ stage_folder = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)
+
+ _, keys = await assert_files_in_s3(
+ minio_client,
+ bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET,
+ key_prefix=stage_folder,
+ file_format="Arrow",
+ compression=None,
+ json_columns=None,
+ )
+ # The interval has ~1000 events, so every one of the 6 random partitions receives rows.
+ assert len(keys) == 6
+
+
[email protected]("interval", ["day"], indirect=True)
[email protected]("model", [BatchExportModel(name="events", schema=None)])
[email protected]("data_interval_end", [TEST_DATA_INTERVAL_END])
+async def test_insert_into_stage_activity_uses_static_default_without_previous_run(
+ generate_test_data,
+ interval,
+ activity_environment,
+ data_interval_start,
+ minio_client,
+ data_interval_end,
+ ateam,
+ model: BatchExportModel,
+):
+ """With no previous run to estimate from, the activity writes the static-default number of files."""
+ insert_inputs = BatchExportInsertIntoInternalStageInputs(
+ team_id=ateam.pk,
+ batch_export_id=str(uuid.uuid4()), # no BatchExportRun exists for this id
+ data_interval_start=data_interval_start.isoformat(),
+ data_interval_end=data_interval_end.isoformat(),
+ exclude_events=None,
+ include_events=None,
+ run_id=None,
+ batch_export_schema=None,
+ batch_export_model=model,
+ backfill_details=None,
+ destination_default_fields=None,
+ )
+
+ with override_settings(
+ BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS=4,
+ BATCH_EXPORT_CLICKHOUSE_S3_TARGET_ROWS_PER_PARTITION=2,
+ BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=1,
+ BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=50,
+ ):
+ stage_folder = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)
+
+ _, keys = await assert_files_in_s3(
+ minio_client,
+ bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET,
+ key_prefix=stage_folder,
+ file_format="Arrow",
+ compression=None,
+ json_columns=None,
+ )
+ assert len(keys) == 4