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): move query range selection out of spmc (#76702)

Rossda97d41e4059
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.py
index 88fa7a51c139..c2b97484d6b0 100644
--- a/products/batch_exports/backend/debug/debugger.py
+++ b/products/batch_exports/backend/debug/debugger.py
@@ -41,7 +41,8 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export import
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import snowflake_default_fields
from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder
-from products.batch_exports.backend.temporal.spmc import BatchExportField, use_distributed_events_recent_table
+from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
+from products.batch_exports.backend.temporal.spmc import BatchExportField
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index c1b3b8efa736..aa9581effdf7 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -38,8 +38,8 @@ from products.batch_exports.backend.service import (
update_batch_export_run,
)
from products.batch_exports.backend.temporal.metrics import get_export_finished_metric, get_export_started_metric
+from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import use_distributed_events_recent_table
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 62f1e2d690d9..5b9e92fd3d55 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -50,13 +50,13 @@ from products.batch_exports.backend.service import (
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.metrics import log_query_duration
-from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_model
-from products.batch_exports.backend.temporal.spmc import (
+from products.batch_exports.backend.temporal.pipeline.query_ranges import (
generate_query_ranges,
is_5_min_batch_export,
use_distributed_events_recent_table,
wait_for_delta_past_data_interval_end,
)
+from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_model
from products.batch_exports.backend.temporal.sql.common import get_s3_function_call
from products.batch_exports.backend.temporal.sql.events import (
EXPORT_TO_S3_FROM_DISTRIBUTED_EVENTS_RECENT,
diff --git a/products/batch_exports/backend/temporal/pipeline/producer.py b/products/batch_exports/backend/temporal/pipeline/producer.py
index 835408ef582f..d66abda3712d 100644
--- a/products/batch_exports/backend/temporal/pipeline/producer.py
+++ b/products/batch_exports/backend/temporal/pipeline/producer.py
@@ -1,3 +1,4 @@
+import math
import typing
import asyncio
import dataclasses
@@ -13,7 +14,7 @@ from posthog.temporal.common.logger import get_write_only_logger
from products.batch_exports.backend.temporal.metrics import CumulativeTimer
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder, get_s3_client
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, slice_record_batch
+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
if typing.TYPE_CHECKING:
@@ -260,3 +261,59 @@ class Producer:
for key in keys:
await semaphore.acquire()
tg.create_task(stream_with_semaphore(key))
+
+
+def slice_record_batch(
+ record_batch: pa.RecordBatch, max_record_batch_size_bytes: int = 0, min_records_per_batch: int = 100
+) -> typing.Iterator[pa.RecordBatch]:
+ """Slice a large Arrow record batch into one or more record batches.
+
+ The underlying call to `pa.RecordBatch.slice` is a zero-copy operation, so the
+ memory footprint of slicing is very low, beyond some additional metadata
+ required for the slice.
+
+ Arguments:
+ record_batch: The record batch to slice.
+ max_record_batch_size_bytes: The max size in bytes of a record batch to
+ yield. If the provided `record_batch` is larger than this, then it
+ will be sliced into multiple record batches.
+ min_records_batch_per_batch: Each slice yielded should contain at least
+ this number of records.
+ """
+ if max_record_batch_size_bytes <= 0 or max_record_batch_size_bytes > record_batch.nbytes:
+ yield record_batch
+ return
+
+ total_rows = record_batch.num_rows
+ yielded_rows = 0
+ offset = 0
+ estimated = _estimate_rows_to_fit_under_max(record_batch, max_record_batch_size_bytes, min_records_per_batch)
+ length = total_rows - estimated
+
+ while yielded_rows < total_rows:
+ sliced_record_batch = record_batch.slice(offset=offset, length=length)
+ current_rows = sliced_record_batch.num_rows
+
+ if sliced_record_batch.nbytes > max_record_batch_size_bytes and current_rows > min_records_per_batch:
+ estimated = _estimate_rows_to_fit_under_max(
+ sliced_record_batch, max_record_batch_size_bytes, min_records_per_batch
+ )
+ length -= estimated
+ continue
+
+ yield sliced_record_batch
+
+ yielded_rows += current_rows
+ offset = offset + length
+ length = total_rows - yielded_rows
+
+
+def _estimate_rows_to_fit_under_max(
+ slice: pa.RecordBatch, max_record_batch_size_bytes: int, min_records_per_batch: int
+) -> int:
+ if slice.nbytes <= max_record_batch_size_bytes or slice.num_rows <= min_records_per_batch:
+ return 0
+
+ avg_bytes_per_row = slice.nbytes / slice.num_rows
+ bytes_diff = slice.nbytes - max_record_batch_size_bytes
+ return max(math.floor(bytes_diff / avg_bytes_per_row), 1)
diff --git a/products/batch_exports/backend/temporal/pipeline/query_ranges.py b/products/batch_exports/backend/temporal/pipeline/query_ranges.py
new file mode 100644
index 000000000000..50b854c1e5ee
--- /dev/null
+++ b/products/batch_exports/backend/temporal/pipeline/query_ranges.py
@@ -0,0 +1,131 @@
+"""Working out which time ranges a batch export run needs to query, and from where.
+
+A run covers a data interval, but it may resume after a crash with part of that interval
+already exported, and which ClickHouse table to read depends on how recent the interval is.
+"""
+
+import typing
+import asyncio
+import datetime as dt
+import operator
+import collections.abc
+
+from django.conf import settings
+
+from products.batch_exports.backend.service import BackfillDetails
+
+
+def is_5_min_batch_export(full_range: tuple[dt.datetime | None, dt.datetime]) -> bool:
+ start_at, end_at = full_range
+ if start_at:
+ return (end_at - start_at) == dt.timedelta(seconds=300)
+ return False
+
+
+def use_distributed_events_recent_table(
+ is_backfill: bool, backfill_details: BackfillDetails | None, data_interval_start: dt.datetime | None
+) -> bool:
+ """We should use the distributed_events_recent table if it's not a backfill (backfill_details is None) or the
+ backfill is within the last 6 days.
+
+ We also check the data_interval_start to make sure it's also within the last 6 days (should always be the case for
+ realtime batch exports but for tests it may not be the case)
+
+ The events_recent table, and by extension, the distributed_events_recent table, only have event data from the last 7
+ days (we use 6 days to give some buffer).
+ """
+
+ if (
+ not is_backfill
+ and data_interval_start
+ and data_interval_start > (dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=6))
+ ):
+ return True
+
+ backfill_start_at = None
+ if backfill_details and backfill_details.start_at:
+ backfill_start_at = dt.datetime.fromisoformat(backfill_details.start_at)
+ if backfill_start_at and backfill_start_at > (dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=6)):
+ return True
+
+ return False
+
+
+def generate_query_ranges(
+ remaining_range: tuple[dt.datetime | None, dt.datetime],
+ done_ranges: collections.abc.Sequence[tuple[dt.datetime, dt.datetime]],
+) -> typing.Iterator[tuple[dt.datetime | None, dt.datetime]]:
+ """Recursively yield ranges of dates that need to be queried.
+
+ There are essentially 3 scenarios we are expecting:
+ 1. The batch export just started, so we expect `done_ranges` to be an empty
+ list, and thus should return the `remaining_range`.
+ 2. The batch export crashed mid-execution, so we have some `done_ranges` that
+ do not completely add up to the full range. In this case we need to yield
+ ranges in between all the done ones.
+ 3. The batch export crashed right after we finish, so we have a full list of
+ `done_ranges` adding up to the `remaining_range`. In this case we should not
+ yield anything.
+
+ Case 1 is fairly trivial and we can simply return `remaining_range` if we get
+ an empty `done_ranges`.
+
+ Case 2 is more complicated and we can expect that the ranges produced by this
+ function will lead to duplicate events selected, as our batch export query is
+ inclusive in the lower bound. Since multiple rows may have the same
+ `inserted_at` we cannot simply skip an `inserted_at` value, as there may be a
+ row that hasn't been exported as it with the same `inserted_at` as a row that
+ has been exported. So this function will return ranges with `inserted_at`
+ values that were already exported for at least one event. Ideally, this is
+ *only* one event, but we can never be certain.
+ """
+ if len(done_ranges) == 0:
+ yield remaining_range
+ return
+
+ epoch = dt.datetime.fromtimestamp(0, tz=dt.UTC)
+ list_done_ranges: list[tuple[dt.datetime, dt.datetime]] = list(done_ranges)
+
+ list_done_ranges.sort(key=operator.itemgetter(0))
+
+ while True:
+ try:
+ next_range: tuple[dt.datetime | None, dt.datetime] = list_done_ranges.pop(0)
+ except IndexError:
+ if remaining_range[0] != remaining_range[1]:
+ # If they were equal it would mean we have finished.
+ yield remaining_range
+
+ return
+ else:
+ candidate_end_at = next_range[0] if next_range[0] is not None else epoch
+
+ candidate_start_at = remaining_range[0]
+ remaining_range = (next_range[1], remaining_range[1])
+
+ if candidate_start_at is not None and candidate_start_at >= candidate_end_at:
+ # We have landed within a done range.
+ continue
+
+ if candidate_start_at is None and candidate_end_at == epoch:
+ # We have landed within the first done range of a backfill.
+ continue
+
+ yield (candidate_start_at, candidate_end_at)
+
+
+async def wait_for_delta_past_data_interval_end(
+ data_interval_end: dt.datetime, delta: dt.timedelta = dt.timedelta(seconds=30)
+) -> None:
+ """Wait for some time after `data_interval_end` before querying ClickHouse."""
+ if settings.TEST:
+ return
+
+ target = data_interval_end.astimezone(dt.UTC)
+ now = dt.datetime.now(dt.UTC)
+
+ while target + delta > now:
+ now = dt.datetime.now(dt.UTC)
+ remaining = (target + delta) - now
+ # Sleep between 1-10 seconds, there shouldn't ever be the need to wait too long.
+ await asyncio.sleep(min(max(remaining.total_seconds(), 1), 10))
diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.py
index 3e9a2f63f753..ce3d907b4cdd 100644
--- a/products/batch_exports/backend/temporal/spmc.py
+++ b/products/batch_exports/backend/temporal/spmc.py
@@ -1,19 +1,13 @@
-import math
import time
import typing
import asyncio
-import datetime as dt
-import operator
import collections.abc
-from django.conf import settings
-
import pyarrow as pa
from temporalio.common import MetricHistogram
from posthog.temporal.common.logger import get_write_only_logger
-from products.batch_exports.backend.service import BackfillDetails
from products.batch_exports.backend.temporal.metrics import get_metric_meter
LOGGER = get_write_only_logger(__name__)
@@ -179,175 +173,3 @@ class BatchExportField(typing.TypedDict):
expression: str
alias: str
-
-
-def is_5_min_batch_export(full_range: tuple[dt.datetime | None, dt.datetime]) -> bool:
- start_at, end_at = full_range
- if start_at:
- return (end_at - start_at) == dt.timedelta(seconds=300)
- return False
-
-
-def use_distributed_events_recent_table(
- is_backfill: bool, backfill_details: BackfillDetails | None, data_interval_start: dt.datetime | None
-) -> bool:
- """We should use the distributed_events_recent table if it's not a backfill (backfill_details is None) or the
- backfill is within the last 6 days.
-
- We also check the data_interval_start to make sure it's also within the last 6 days (should always be the case for
- realtime batch exports but for tests it may not be the case)
-
- The events_recent table, and by extension, the distributed_events_recent table, only have event data from the last 7
- days (we use 6 days to give some buffer).
- """
-
- if (
- not is_backfill
- and data_interval_start
- and data_interval_start > (dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=6))
- ):
- return True
-
- backfill_start_at = None
- if backfill_details and backfill_details.start_at:
- backfill_start_at = dt.datetime.fromisoformat(backfill_details.start_at)
- if backfill_start_at and backfill_start_at > (dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=6)):
- return True
-
- return False
-
-
-def slice_record_batch(
- record_batch: pa.RecordBatch, max_record_batch_size_bytes: int = 0, min_records_per_batch: int = 100
-) -> typing.Iterator[pa.RecordBatch]:
- """Slice a large Arrow record batch into one or more record batches.
-
- The underlying call to `pa.RecordBatch.slice` is a zero-copy operation, so the
- memory footprint of slicing is very low, beyond some additional metadata
- required for the slice.
-
- Arguments:
- record_batch: The record batch to slice.
- max_record_batch_size_bytes: The max size in bytes of a record batch to
- yield. If the provided `record_batch` is larger than this, then it
- will be sliced into multiple record batches.
- min_records_batch_per_batch: Each slice yielded should contain at least
- this number of records.
- """
- if max_record_batch_size_bytes <= 0 or max_record_batch_size_bytes > record_batch.nbytes:
- yield record_batch
- return
-
- total_rows = record_batch.num_rows
- yielded_rows = 0
- offset = 0
- estimated = _estimate_rows_to_fit_under_max(record_batch, max_record_batch_size_bytes, min_records_per_batch)
- length = total_rows - estimated
-
- while yielded_rows < total_rows:
- sliced_record_batch = record_batch.slice(offset=offset, length=length)
- current_rows = sliced_record_batch.num_rows
-
- if sliced_record_batch.nbytes > max_record_batch_size_bytes and current_rows > min_records_per_batch:
- estimated = _estimate_rows_to_fit_under_max(
- sliced_record_batch, max_record_batch_size_bytes, min_records_per_batch
- )
- length -= estimated
- continue
-
- yield sliced_record_batch
-
- yielded_rows += current_rows
- offset = offset + length
- length = total_rows - yielded_rows
-
-
-def _estimate_rows_to_fit_under_max(
- slice: pa.RecordBatch, max_record_batch_size_bytes: int, min_records_per_batch: int
-) -> int:
- if slice.nbytes <= max_record_batch_size_bytes or slice.num_rows <= min_records_per_batch:
- return 0
-
- avg_bytes_per_row = slice.nbytes / slice.num_rows
- bytes_diff = slice.nbytes - max_record_batch_size_bytes
- return max(math.floor(bytes_diff / avg_bytes_per_row), 1)
-
-
-def generate_query_ranges(
- remaining_range: tuple[dt.datetime | None, dt.datetime],
- done_ranges: collections.abc.Sequence[tuple[dt.datetime, dt.datetime]],
-) -> typing.Iterator[tuple[dt.datetime | None, dt.datetime]]:
- """Recursively yield ranges of dates that need to be queried.
-
- There are essentially 3 scenarios we are expecting:
- 1. The batch export just started, so we expect `done_ranges` to be an empty
- list, and thus should return the `remaining_range`.
- 2. The batch export crashed mid-execution, so we have some `done_ranges` that
- do not completely add up to the full range. In this case we need to yield
- ranges in between all the done ones.
- 3. The batch export crashed right after we finish, so we have a full list of
- `done_ranges` adding up to the `remaining_range`. In this case we should not
- yield anything.
-
- Case 1 is fairly trivial and we can simply return `remaining_range` if we get
- an empty `done_ranges`.
-
- Case 2 is more complicated and we can expect that the ranges produced by this
- function will lead to duplicate events selected, as our batch export query is
- inclusive in the lower bound. Since multiple rows may have the same
- `inserted_at` we cannot simply skip an `inserted_at` value, as there may be a
- row that hasn't been exported as it with the same `inserted_at` as a row that
- has been exported. So this function will return ranges with `inserted_at`
- values that were already exported for at least one event. Ideally, this is
- *only* one event, but we can never be certain.
- """
- if len(done_ranges) == 0:
- yield remaining_range
- return
-
- epoch = dt.datetime.fromtimestamp(0, tz=dt.UTC)
- list_done_ranges: list[tuple[dt.datetime, dt.datetime]] = list(done_ranges)
-
- list_done_ranges.sort(key=operator.itemgetter(0))
-
- while True:
- try:
- next_range: tuple[dt.datetime | None, dt.datetime] = list_done_ranges.pop(0)
- except IndexError:
- if remaining_range[0] != remaining_range[1]:
- # If they were equal it would mean we have finished.
- yield remaining_range
-
- return
- else:
- candidate_end_at = next_range[0] if next_range[0] is not None else epoch
-
- candidate_start_at = remaining_range[0]
- remaining_range = (next_range[1], remaining_range[1])
-
- if candidate_start_at is not None and candidate_start_at >= candidate_end_at:
- # We have landed within a done range.
- continue
-
- if candidate_start_at is None and candidate_end_at == epoch:
- # We have landed within the first done range of a backfill.
- continue
-
- yield (candidate_start_at, candidate_end_at)
-
-
-async def wait_for_delta_past_data_interval_end(
- data_interval_end: dt.datetime, delta: dt.timedelta = dt.timedelta(seconds=30)
-) -> None:
- """Wait for some time after `data_interval_end` before querying ClickHouse."""
- if settings.TEST:
- return
-
- target = data_interval_end.astimezone(dt.UTC)
- now = dt.datetime.now(dt.UTC)
-
- while target + delta > now:
- now = dt.datetime.now(dt.UTC)
- remaining = (target + delta) - now
- # Sleep between 1-10 seconds, there shouldn't ever be the need to wait too long.
- await asyncio.sleep(min(max(remaining.total_seconds(), 1), 10))
diff --git a/products/batch_exports/backend/tests/temporal/test_spmc.py b/products/batch_exports/backend/tests/temporal/test_spmc.py
index 96aa5edcf188..2abf45477b95 100644
--- a/products/batch_exports/backend/tests/temporal/test_spmc.py
+++ b/products/batch_exports/backend/tests/temporal/test_spmc.py
@@ -9,11 +9,9 @@ import pyarrow as pa
from products.batch_exports.backend.service import BackfillDetails
from products.batch_exports.backend.temporal.filters import InvalidFilterError, compose_filters_clause
-from products.batch_exports.backend.temporal.spmc import (
- RecordBatchQueue,
- slice_record_batch,
- use_distributed_events_recent_table,
-)
+from products.batch_exports.backend.temporal.pipeline.producer import slice_record_batch
+from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
index 7a47a3c1159d..e3fd1ae0f69e 100644
--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
@@ -7,7 +7,7 @@ from posthog.models.app_metrics2.sql import APP_METRICS2_DATA_TABLE_SQL, APP_MET
from posthog.temporal.common.asyncpa import InvalidMessageFormat
from posthog.temporal.common.clickhouse import ClickHouseClient, ClickHouseError
-from products.batch_exports.backend.temporal.spmc import slice_record_batch
+from products.batch_exports.backend.temporal.pipeline.producer import slice_record_batch
@retry(
diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
index a28da2fab076..6880e8428eb1 100644
--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
@@ -20,15 +20,15 @@ from posthog.temporal.common.logger import get_write_only_logger
from products.batch_exports.backend.service import BackfillDetails, BatchExportField
from products.batch_exports.backend.temporal.filters import compose_filters_clause
-from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel
-from products.batch_exports.backend.temporal.spmc import (
- RecordBatchQueue,
+from products.batch_exports.backend.temporal.pipeline.producer import slice_record_batch
+from products.batch_exports.backend.temporal.pipeline.query_ranges import (
generate_query_ranges,
is_5_min_batch_export,
- slice_record_batch,
use_distributed_events_recent_table,
wait_for_delta_past_data_interval_end,
)
+from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel
+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,