: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
refactor(batch-exports): delete abandoned resume-from-heartbeat code (#90134)
Ross15b01c6cec2d
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex b9c0aa885b16..e91938bb5f37 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -2,7 +2,6 @@ import uuidimport typingimport asyncioimport datetime as dt-import operatorimport dataclassesimport collections.abcfrom zoneinfo import ZoneInfo@@ -196,69 +195,6 @@ class TaskNotDoneError(Exception):super().__init__(f"Expected task '{task}' to be done by now")-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)--def iter_records(client: ClickHouseClient,team_id: int,diff --git a/products/batch_exports/backend/temporal/heartbeat.py b/products/batch_exports/backend/temporal/heartbeat.pydeleted file mode 100644index 45b77f5af8d2..000000000000--- a/products/batch_exports/backend/temporal/heartbeat.py+++ /dev/null@@ -1,227 +0,0 @@-import typing-import datetime as dt-import dataclasses-import collections.abc--from posthog.temporal.common.heartbeat import (- EmptyHeartbeatError,- HeartbeatDetails,- HeartbeatParseError,- NotEnoughHeartbeatValuesError,-)-from posthog.temporal.common.logger import get_write_only_logger--DateRange = tuple[dt.datetime, dt.datetime]--logger = get_write_only_logger()---class BatchExportRangeHeartbeatDetails(HeartbeatDetails):- """Details included in every batch export heartbeat.-- Attributes:- done_ranges: Date ranges that have been successfully exported.- _remaining: Anything else in the activity details.- """-- done_ranges: list[DateRange] = dataclasses.field(default_factory=list)- records_completed: int = 0- _remaining: collections.abc.Sequence[typing.Any] = dataclasses.field(default_factory=tuple)-- @classmethod- def deserialize_details(cls, details: collections.abc.Sequence[typing.Any]) -> dict[str, typing.Any]:- """Deserialize this from Temporal activity details.-- We expect done ranges to be available in the first index of remaining- values. Moreover, we expect datetime values to be ISO-formatted strings.- """- done_ranges: list[DateRange] = []- records_completed = 0- remaining = super().deserialize_details(details)-- if len(remaining["_remaining"]) == 0:- return {"done_ranges": done_ranges, "records_completed": records_completed, **remaining}-- first_detail = remaining["_remaining"][0]- remaining["_remaining"] = remaining["_remaining"][1:]-- for date_str_tuple in first_detail:- try:- range_start, range_end = date_str_tuple- datetime_bounds = (- dt.datetime.fromisoformat(range_start),- dt.datetime.fromisoformat(range_end),- )- except (TypeError, ValueError) as e:- raise HeartbeatParseError("done_ranges") from e-- done_ranges.append(datetime_bounds)-- if len(remaining["_remaining"]) == 0:- return {"done_ranges": done_ranges, "records_completed": records_completed, **remaining}-- next_detail = remaining["_remaining"][0]- remaining["_remaining"] = remaining["_remaining"][1:]-- try:- records_completed = int(next_detail)- except (TypeError, ValueError) as e:- raise HeartbeatParseError("records_completed") from e-- return {"done_ranges": done_ranges, "records_completed": records_completed, **remaining}-- def serialize_details(self) -> tuple[typing.Any, ...]:- """Serialize this into a tuple.-- Each datetime from `self.done_ranges` must be cast to string as values must- be JSON-serializable.- """- serialized_done_ranges = [- (start.isoformat() if start is not None else start, end.isoformat()) for (start, end) in self.done_ranges- ]- serialized_parent_details = super().serialize_details()- return (*serialized_parent_details[:-1], serialized_done_ranges, self.records_completed, self._remaining)-- @property- def empty(self) -> bool:- return len(self.done_ranges) == 0-- def track_done_range(- self, done_range: DateRange, data_interval_start_input: str | dt.datetime | None, merge: bool = True- ):- """Track a range of datetime values that has been exported successfully.-- If this is the first `done_range` then we override the beginning of the- range to ensure it covers the range from `data_interval_start_input`.-- Arguments:- done_range: A date range of values that have been exported.- data_interval_start_input: The `data_interval_start` input passed to- the batch export- merge: Whether to merge the new range with existing ones.- """- if self.empty is True:- if data_interval_start_input is None:- data_interval_start = dt.datetime.fromtimestamp(0, tz=dt.UTC)- elif isinstance(data_interval_start_input, str):- data_interval_start = dt.datetime.fromisoformat(data_interval_start_input)- else:- data_interval_start = data_interval_start_input-- done_range = (data_interval_start, done_range[1])-- self.insert_done_range(done_range, merge=merge)-- def insert_done_range(self, done_range: DateRange, merge: bool = True):- """Insert a date range into `self.done_ranges` in order."""- for index, range in enumerate(self.done_ranges, start=0):- if done_range[0] > range[1]:- continue-- # We have found the index where this date range should go in.- if done_range[0] == range[1]:- self.done_ranges.insert(index + 1, done_range)- else:- self.done_ranges.insert(index, done_range)- break- else:- # Date range should go at the end- self.done_ranges.append(done_range)-- if merge:- self.merge_done_ranges()-- def merge_done_ranges(self):- """Merge as many date ranges together as possible in `self.done_ranges`.-- This method looks for ranges whose opposite ends are touching and merges- them together. Notice that this method does not have enough information- to merge ranges that are not touching.- """- marked_for_deletion = set()- for index, range in enumerate(self.done_ranges, start=0):- if index in marked_for_deletion:- continue- try:- next_range = self.done_ranges[index + 1]- except IndexError:- continue-- if next_range[0] == range[1]:- # Touching start of next range with end of range.- # End of next range set as end of existing range.- # Next range marked for deletion as it's now covered by range.- self.done_ranges[index] = (range[0], next_range[1])- marked_for_deletion.add(index + 1)-- for index in marked_for_deletion:- self.done_ranges.pop(index)-- def complete_done_ranges(self, data_interval_end_input: str | dt.datetime):- """Complete the entire range covered by the batch export.-- This is meant to be called at the end of a batch export to ensure- `self.done_ranges` covers the entire batch period from whichever was the- first range tracked until `data_interval_end_input`.-- All ranges will be essentially merged into one (well, replaced by one)- covering everything, so it is very important to only call this once- everything is done.- """- if isinstance(data_interval_end_input, str):- data_interval_end = dt.datetime.fromisoformat(data_interval_end_input)- else:- data_interval_end = data_interval_end_input-- self.done_ranges = [(self.done_ranges[0][0], data_interval_end)]---HeartbeatType = typing.TypeVar("HeartbeatType", bound=HeartbeatDetails)---async def should_resume_from_activity_heartbeat(- activity, heartbeat_type: type[HeartbeatType]-) -> tuple[bool, HeartbeatType | None]:- """Check if a batch export should resume from an activity's heartbeat details.-- We understand that a batch export should resume any time that we receive heartbeat details and- those details can be correctly parsed. However, the decision is ultimately up to the batch export- activity to decide if it must resume and how to do so.-- Returns:- A tuple with the first element indicating if the batch export should resume. If the first element- is True, the second tuple element will be the heartbeat details themselves, otherwise None.- """- try:- heartbeat_details = heartbeat_type.from_activity(activity)-- except EmptyHeartbeatError:- # We don't log this as it's the expected exception when heartbeat is empty.- heartbeat_details = None- received = False-- except NotEnoughHeartbeatValuesError:- heartbeat_details = None- received = False- await logger.awarning("Details from previous activity execution did not contain the expected amount of values")-- except HeartbeatParseError:- heartbeat_details = None- received = False- await logger.awarning("Details from previous activity execution could not be parsed.")-- except Exception:- # We should start from the beginning, but we make a point to log unexpected errors.- # Ideally, any new exceptions should be added to the previous blocks after the first time and we will never land here.- heartbeat_details = None- received = False- await logger.aexception("Did not receive details from previous activity Execution due to an unexpected error")-- else:- received = True- await logger.adebug(- f"Received details from previous activity: {heartbeat_details}",- )-- return received, heartbeat_detailsdiff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex ae650621c842..745c4b6448c1 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -55,7 +55,6 @@ from products.batch_exports.backend.temporal.batch_exports import default_fieldsfrom products.batch_exports.backend.temporal.filters import compose_filters_clausefrom products.batch_exports.backend.temporal.metrics import log_query_durationfrom 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,@@ -627,7 +626,7 @@ async def _write_batch_export_record_batches_to_internal_stage() -> int | None:"""Write record batches to our own internal S3 staging area.- Returns the total number of rows written to the stage, or None if the count couldn't be+ Returns the number of rows written to the stage, or None if the count couldn't bedetermined."""logger = LOGGER.bind()@@ -644,17 +643,16 @@ async def _write_batch_export_record_batches_to_internal_stage(delta = dt.timedelta(seconds=30)else:delta = dt.timedelta(minutes=1)- end_at = full_range[1]+ interval_start, interval_end = full_range- if _is_local_dev_or_test() is False and end_at > dt.datetime.now(dt.UTC):+ if _is_local_dev_or_test() is False and interval_end > dt.datetime.now(dt.UTC):# Some tests create data in the future, so we do not check this.- raise DataIntervalEndInFutureError(end_at)+ raise DataIntervalEndInFutureError(interval_end)if not isinstance(query_or_model, RecordBatchModel) or query_or_model.wait_for_data_interval_end:with TRACER.start_as_current_span("batch_export.stage.wait_for_delta"):- await wait_for_delta_past_data_interval_end(end_at, delta)+ await wait_for_delta_past_data_interval_end(interval_end, delta)- done_ranges: list[tuple[dt.datetime, dt.datetime]] = []async with get_client(team_id=team_id,clickhouse_url=clickhouse_url,@@ -671,66 +669,57 @@ async def _write_batch_export_record_batches_to_internal_stage(if not await client.is_alive():raise ConnectionError("Cannot establish connection to ClickHouse")- total_written_rows: int | None = 0- # TODO - in future we might want to catch any ClickHouse memory usage errors and break down the interval into- # sub-intervals to reduce memory usage- for interval_start, interval_end in generate_query_ranges(full_range, done_ranges):- if interval_start is not None:- query_parameters["interval_start"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")- query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")-- if isinstance(query_or_model, RecordBatchModel):- query, query_parameters = await query_or_model.as_insert_into_s3_query_with_parameters(- data_interval_start=interval_start,- data_interval_end=interval_end,- s3_folder=s3_staging_folder_url,- credentials=_get_s3_credentials(),- num_partitions=num_partitions or settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS,- )- query_settings = query_or_model.get_clickhouse_request_settings()- else:- query = query_or_model- query_settings = {}-- base_s3_staging_folder = get_base_s3_staging_folder(- batch_export_id=batch_export_id,- data_interval_start=data_interval_start,- data_interval_end=data_interval_end,+ # TODO - in future we might want to catch any ClickHouse memory usage errors and split the+ # interval into sub-intervals, running one query per sub-interval, to reduce memory usage+ if interval_start is not None:+ query_parameters["interval_start"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")+ query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")++ if isinstance(query_or_model, RecordBatchModel):+ query, query_parameters = await query_or_model.as_insert_into_s3_query_with_parameters(+ data_interval_start=interval_start,+ data_interval_end=interval_end,+ s3_folder=s3_staging_folder_url,+ credentials=_get_s3_credentials(),+ num_partitions=num_partitions or settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS,)- # First delete any existing files in the staging folder.- # We technically don't need to do this, since the Temporal activity attempt number is used in the S3 key,- # however, since we only make use of the most recent attempt, we can save on storage space by deleting the- # files here.- try:- with TRACER.start_as_current_span("batch_export.stage.delete_existing_objects"):- await _delete_all_from_bucket_with_prefix(- bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, key_prefix=base_s3_staging_folder- )- except Exception:- logger.exception(- "Unexpected error occurred while deleting existing objects from internal S3 staging bucket",- )- raise+ query_settings = query_or_model.get_clickhouse_request_settings()+ else:+ query = query_or_model+ query_settings = {}- try:- with TRACER.start_as_current_span("batch_export.stage.clickhouse_query") as query_span:- written_rows = await _execute_query(client, query, query_parameters, query_settings)- if written_rows is not None:- query_span.set_attribute("batch_export.stage.written_rows", written_rows)- except ClickHouseError:- logger.exception(- "ClickHouse error occurred while writing record batches to internal S3 staging bucket",+ base_s3_staging_folder = get_base_s3_staging_folder(+ batch_export_id=batch_export_id,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ )+ # First delete any existing files in the staging folder.+ # We technically don't need to do this, since the Temporal activity attempt number is used in the S3 key,+ # however, since we only make use of the most recent attempt, we can save on storage space by deleting the+ # files here.+ try:+ with TRACER.start_as_current_span("batch_export.stage.delete_existing_objects"):+ await _delete_all_from_bucket_with_prefix(+ bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, key_prefix=base_s3_staging_folder)- raise+ except Exception:+ logger.exception(+ "Unexpected error occurred while deleting existing objects from internal S3 staging bucket",+ )+ raise- # if any query fails to return written rows then set total to None so that we don't- # return a partial result- if written_rows is None:- total_written_rows = None- elif total_written_rows is not None:- total_written_rows += written_rows+ try:+ with TRACER.start_as_current_span("batch_export.stage.clickhouse_query") as query_span:+ written_rows = await _execute_query(client, query, query_parameters, query_settings)+ if written_rows is not None:+ query_span.set_attribute("batch_export.stage.written_rows", written_rows)+ except ClickHouseError:+ logger.exception(+ "ClickHouse error occurred while writing record batches to internal S3 staging bucket",+ )+ raise- return total_written_rows+ return written_rowsdef _written_rows_from_summary(summary: dict[str, typing.Any] | None) -> int | None:diff --git a/products/batch_exports/backend/temporal/pipeline/query_ranges.py b/products/batch_exports/backend/temporal/pipeline/query_ranges.pyindex 4a41c53a64f5..775ad551e068 100644--- a/products/batch_exports/backend/temporal/pipeline/query_ranges.py+++ b/products/batch_exports/backend/temporal/pipeline/query_ranges.py@@ -1,14 +1,5 @@-"""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 typingimport asyncioimport datetime as dt-import operator-import collections.abcfrom django.conf import settings@@ -51,69 +42,6 @@ def use_distributed_events_recent_table(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:diff --git a/products/batch_exports/backend/temporal/temporary_file.py b/products/batch_exports/backend/temporal/temporary_file.pyindex 6826ae1f00cc..aed6916225f8 100644--- a/products/batch_exports/backend/temporal/temporary_file.py+++ b/products/batch_exports/backend/temporal/temporary_file.py@@ -21,10 +21,10 @@ from psycopg import sqlfrom posthog.temporal.common.logger import get_write_only_logger-from products.batch_exports.backend.temporal.heartbeat import DateRange-logger = get_write_only_logger()+DateRange = tuple[dt.datetime, dt.datetime]+def replace_broken_unicode(obj):if isinstance(obj, str):diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.pyindex e4b31e28271b..0c26539407ee 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py@@ -187,7 +187,6 @@ async def assert_clickhouse_records_in_azure_blob(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=azure_blob_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.pyindex 0f9c11a9f285..56173d0dc02c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py+++ b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py@@ -248,7 +248,6 @@ async def _get_records_from_clickhouse(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=destination_default_fields,diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.pyindex 79825907de90..ea1bcd4fecb8 100644--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py@@ -160,7 +160,6 @@ async def assert_clickhouse_records_in_bigquery(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=bigquery_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.pyindex 50af3035cfaa..e2af6c856752 100644--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py@@ -146,7 +146,6 @@ async def assert_clickhouse_records_in_postgres(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=postgres_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.pyindex 1ffd9dcbbca1..fcacb5d672b3 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py@@ -186,7 +186,6 @@ async def assert_clickhouse_records_in_redshift(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=redshift_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.pyindex f592a9257590..65617c0a480a 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py@@ -269,7 +269,6 @@ async def assert_clickhouse_records_in_s3(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=s3_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.pyindex 86a767f2de0f..3d8de3583876 100644--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py@@ -461,7 +461,6 @@ async def assert_clickhouse_records_in_snowflake(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,destination_default_fields=snowflake_default_fields(),diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.pyindex 2f4c7e8a00e6..50dfaf9327e2 100644--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py@@ -77,7 +77,6 @@ async def assert_clickhouse_records_were_handled(model_name=model_name,team_id=team_id,full_range=(data_interval_start, data_interval_end),- done_ranges=[],fields=fields,filters=filters,exclude_events=exclude_events,diff --git a/products/batch_exports/backend/tests/temporal/test_batch_exports.py b/products/batch_exports/backend/tests/temporal/test_batch_exports.pyindex b32157e62f6d..b04fb0efba1e 100644--- a/products/batch_exports/backend/tests/temporal/test_batch_exports.py+++ b/products/batch_exports/backend/tests/temporal/test_batch_exports.py@@ -9,12 +9,7 @@ from django.test import override_settingsfrom posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse-from products.batch_exports.backend.temporal.batch_exports import (- DataInterval,- generate_query_ranges,- get_data_interval,- iter_records,-)+from products.batch_exports.backend.temporal.batch_exports import DataInterval, get_data_interval, iter_recordspytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -384,122 +379,6 @@ def test_get_data_interval_dst_transition(interval, data_interval_end, expected_)- "remaining_range,done_ranges,expected",- [- # Case 1: One done range at the beginning- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [(dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC))],- [- (- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC),- )- ],- ),- # Case 2: Single done range equal to full range.- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [(dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC))],- [],- ),- # Case 3: Disconnected done ranges cover full range.- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC)),- (- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC),- ),- ],- [],- ),- # Case 4: Disconnect done ranges within full range.- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [- (- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 50, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 55, 0, tzinfo=dt.UTC),- ),- ],- [- (- dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 50, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 55, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC),- ),- ],- ),- # Case 5: Empty done ranges.- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [],- [- (- dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC),- ),- ],- ),- # Case 6: Disconnect done ranges within full range and one last done range connected to the end.- (- (dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC), dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC)),- [- (- dt.datetime(2023, 7, 31, 12, 15, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 25, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 50, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 13, 0, 0, tzinfo=dt.UTC),- ),- ],- [- (- dt.datetime(2023, 7, 31, 12, 0, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 15, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 25, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 30, 0, tzinfo=dt.UTC),- ),- (- dt.datetime(2023, 7, 31, 12, 45, 0, tzinfo=dt.UTC),- dt.datetime(2023, 7, 31, 12, 50, 0, tzinfo=dt.UTC),- ),- ],- ),- ],- ids=["1", "2", "3", "4", "5", "6"],-)-def test_generate_query_ranges(remaining_range, done_ranges, expected):- """Test generate_query_ranges returns the expected query ranges."""- result = list(generate_query_ranges(remaining_range, done_ranges))- assert result == expected--@pytest.mark.parametrize("delta", [dt.timedelta(0), dt.timedelta(hours=1)])def test_data_interval_accepts_ordered_bounds(delta: dt.timedelta) -> None:end = dt.datetime(2023, 8, 1, tzinfo=dt.UTC)diff --git a/products/batch_exports/backend/tests/temporal/test_heartbeat.py b/products/batch_exports/backend/tests/temporal/test_heartbeat.pydeleted file mode 100644index 244a6951bd6c..000000000000--- a/products/batch_exports/backend/tests/temporal/test_heartbeat.py+++ /dev/null@@ -1,104 +0,0 @@-import datetime as dt--import pytest--from products.batch_exports.backend.temporal.heartbeat import BatchExportRangeHeartbeatDetails--- "initial_done_ranges,done_range,expected_index",- [- # Case 1: Inserting into an empty initial list.- ([], (dt.datetime.fromtimestamp(5), dt.datetime.fromtimestamp(6)), 0),- # Case 2: Inserting into middle of initial list.- (- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(6), dt.datetime.fromtimestamp(10)),- ],- (dt.datetime.fromtimestamp(5), dt.datetime.fromtimestamp(6)),- 1,- ),- # Case 3: Inserting into beginning of initial list.- (- [- (dt.datetime.fromtimestamp(1), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(6), dt.datetime.fromtimestamp(10)),- ],- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(1)),- 0,- ),- # Case 4: Inserting into end of initial list.- (- [(dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(10))],- (dt.datetime.fromtimestamp(10), dt.datetime.fromtimestamp(11)),- 1,- ),- # Case 5: Inserting disconnected range into middle of initial list.- (- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(10)),- (dt.datetime.fromtimestamp(15), dt.datetime.fromtimestamp(20)),- ],- (dt.datetime.fromtimestamp(12), dt.datetime.fromtimestamp(13)),- 1,- ),- ],-)-def test_insert_done_range(initial_done_ranges, done_range, expected_index):- """Test `BatchExportRangeHeartbeatDetails` inserts a done range in the expected index.-- We avoid merging ranges to maintain the original index so we can assert it matches- the expected index.- """- heartbeat_details = BatchExportRangeHeartbeatDetails()- heartbeat_details.done_ranges.extend(initial_done_ranges)- heartbeat_details.insert_done_range(done_range, merge=False)-- assert len(heartbeat_details.done_ranges) == len(initial_done_ranges) + 1- assert heartbeat_details.done_ranges.index(done_range) == expected_index--- "initial_done_ranges,expected_done_ranges",- [- # Case 1: Disconnected ranges are not merged.- (- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(6), dt.datetime.fromtimestamp(10)),- ],- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(6), dt.datetime.fromtimestamp(10)),- ],- ),- # Case 2: Connected ranges are merged.- (- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(5), dt.datetime.fromtimestamp(10)),- ],- [(dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(10))],- ),- # Case 3: Connected ranges are merged, but disconnected are not.- (- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(5)),- (dt.datetime.fromtimestamp(5), dt.datetime.fromtimestamp(10)),- (dt.datetime.fromtimestamp(11), dt.datetime.fromtimestamp(12)),- ],- [- (dt.datetime.fromtimestamp(0), dt.datetime.fromtimestamp(10)),- (dt.datetime.fromtimestamp(11), dt.datetime.fromtimestamp(12)),- ],- ),- ],-)-def test_merge_done_ranges(initial_done_ranges, expected_done_ranges):- """Test `BatchExportRangeHeartbeatDetails` merges done ranges."""- heartbeat_details = BatchExportRangeHeartbeatDetails()- heartbeat_details.done_ranges.extend(initial_done_ranges)- heartbeat_details.merge_done_ranges()-- assert heartbeat_details.done_ranges == expected_done_rangesdiff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.pyindex 1dd6a058f9fc..7740e50722b7 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@@ -22,7 +22,6 @@ from products.batch_exports.backend.service import BackfillDetails, BatchExportFfrom products.batch_exports.backend.temporal.filters import compose_filters_clausefrom products.batch_exports.backend.temporal.pipeline.producer import slice_record_batchfrom 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,@@ -87,7 +86,6 @@ class ClickHouseTestProducer:self,queue: RecordBatchQueue,full_range: tuple[dt.datetime | None, dt.datetime],- done_ranges: list[tuple[dt.datetime, dt.datetime]],is_backfill: bool,backfill_details: BackfillDetails | None,max_record_batch_size_bytes: int = 0,@@ -101,7 +99,6 @@ class ClickHouseTestProducer:max_record_batch_size_bytes=max_record_batch_size_bytes,min_records_per_batch=min_records_per_batch,full_range=full_range,- done_ranges=done_ranges,)else:return await self.start_without_model(@@ -109,7 +106,6 @@ class ClickHouseTestProducer:max_record_batch_size_bytes=max_record_batch_size_bytes,min_records_per_batch=min_records_per_batch,full_range=full_range,- done_ranges=done_ranges,is_backfill=is_backfill,backfill_details=backfill_details,**kwargs,@@ -119,7 +115,6 @@ class ClickHouseTestProducer:self,queue: RecordBatchQueue,full_range: tuple[dt.datetime | None, dt.datetime],- done_ranges: list[tuple[dt.datetime, dt.datetime]],max_record_batch_size_bytes: int = 0,min_records_per_batch: int = 100,):@@ -129,7 +124,6 @@ class ClickHouseTestProducer:self.produce_batch_export_record_batches_from_range(query_or_model=self.model,full_range=full_range,- done_ranges=done_ranges,queue=queue,query_parameters={},max_record_batch_size_bytes=max_record_batch_size_bytes,@@ -149,7 +143,6 @@ class ClickHouseTestProducer:backfill_details: BackfillDetails | None,team_id: int,full_range: tuple[dt.datetime | None, dt.datetime],- done_ranges: list[tuple[dt.datetime, dt.datetime]],fields: list[BatchExportField] | None = None,destination_default_fields: list[BatchExportField] | None = None,max_record_batch_size_bytes: int = 0,@@ -249,7 +242,6 @@ class ClickHouseTestProducer:self.produce_batch_export_record_batches_from_range(query_or_model=query,full_range=full_range,- done_ranges=done_ranges,queue=queue,query_parameters=parameters,max_record_batch_size_bytes=max_record_batch_size_bytes,@@ -265,7 +257,6 @@ class ClickHouseTestProducer:self,query_or_model: str | RecordBatchModel,full_range: tuple[dt.datetime | None, dt.datetime],- done_ranges: collections.abc.Sequence[tuple[dt.datetime, dt.datetime]],queue: RecordBatchQueue,query_parameters: dict[str, typing.Any],team_id: int,@@ -278,8 +269,6 @@ class ClickHouseTestProducer:query: The ClickHouse query used to obtain record batches. The query should be have a`FORMAT ArrowStream` clause, although we do not enforce this.full_range: The full date range of record batches to produce.- done_ranges: Date ranges of record batches that have already been exported, and thus- should be skipped.queue: The queue where to produce record batches.query_parameters: Additional query parameters.team_id: The team ID of the batch export.@@ -301,36 +290,33 @@ class ClickHouseTestProducer:delta = dt.timedelta(seconds=30)else:delta = dt.timedelta(minutes=1)- end_at = full_range[1]- await wait_for_delta_past_data_interval_end(end_at, delta)+ interval_start, interval_end = full_range+ await wait_for_delta_past_data_interval_end(interval_end, delta)async with get_client(team_id=team_id, clickhouse_url=clickhouse_url) as client:if not await client.is_alive():raise ConnectionError("Cannot establish connection to ClickHouse")- for interval_start, interval_end in generate_query_ranges(full_range, done_ranges):- if interval_start is not None:- query_parameters["interval_start"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")- query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")- query_id = uuid.uuid4()- self.logger.debug("Executing query with ID '%s'", query_id)-- if isinstance(query_or_model, RecordBatchModel):- query, query_parameters = await query_or_model.as_query_with_parameters(- interval_start, interval_end- )- else:- query = query_or_model-- try:- async for record_batch in client.astream_query_as_arrow(- query, query_parameters=query_parameters, query_id=str(query_id)+ if interval_start is not None:+ query_parameters["interval_start"] = interval_start.strftime("%Y-%m-%d %H:%M:%S.%f")+ query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")+ query_id = uuid.uuid4()+ self.logger.debug("Executing query with ID '%s'", query_id)++ if isinstance(query_or_model, RecordBatchModel):+ query, query_parameters = await query_or_model.as_query_with_parameters(interval_start, interval_end)+ else:+ query = query_or_model++ try:+ async for record_batch in client.astream_query_as_arrow(+ query, query_parameters=query_parameters, query_id=str(query_id)+ ):+ for record_batch_slice in slice_record_batch(+ record_batch, max_record_batch_size_bytes, min_records_per_batch):- for record_batch_slice in slice_record_batch(- record_batch, max_record_batch_size_bytes, min_records_per_batch- ):- await queue.put(record_batch_slice)-- except Exception as e:- self.logger.exception("Unexpected error occurred while producing record batches", exc_info=e)- raise+ await queue.put(record_batch_slice)++ except Exception as e:+ self.logger.exception("Unexpected error occurred while producing record batches", exc_info=e)+ raise