: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): move previous producer into test utils (#75982)
Rossfccbe5f31cfc
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 10acd10b1a7e..2b79eec3518b 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -49,9 +49,8 @@ from products.batch_exports.backend.service import ()from products.batch_exports.backend.temporal.batch_exports import default_fieldsfrom products.batch_exports.backend.temporal.metrics import log_query_duration-from products.batch_exports.backend.temporal.record_batch_model import resolve_batch_exports_model+from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_modelfrom products.batch_exports.backend.temporal.spmc import (- RecordBatchModel,compose_filters_clause,generate_query_ranges,is_5_min_batch_export,diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.pyindex 9716e225e7a8..855cd61521af 100644--- a/products/batch_exports/backend/temporal/spmc.py+++ b/products/batch_exports/backend/temporal/spmc.py@@ -1,6 +1,5 @@import mathimport time-import uuidimport typingimport asyncioimport datetime as dt@@ -24,22 +23,10 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.visitor import TraversingVisitorfrom posthog.models import Team-from posthog.sync import database_sync_to_async-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_loggerfrom products.batch_exports.backend.service import SUPPORTED_FILTER_TYPES, BackfillDetailsfrom products.batch_exports.backend.temporal.metrics import get_metric_meter-from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel-from products.batch_exports.backend.temporal.sql.events import (- SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,- SELECT_FROM_EVENTS_VIEW,- SELECT_FROM_EVENTS_VIEW_BACKFILL,- SELECT_FROM_EVENTS_VIEW_RECENT,- SELECT_FROM_EVENTS_VIEW_UNBOUNDED,- SELECT_FROM_EVENTS_WORKFLOWS,-)-from products.batch_exports.backend.temporal.sql.persons import SELECT_FROM_PERSONS, SELECT_FROM_PERSONS_BACKFILLLOGGER = get_write_only_logger(__name__)@@ -206,25 +193,6 @@ class BatchExportField(typing.TypedDict):alias: str-def default_fields() -> list[BatchExportField]:- """Return list of default batch export Fields."""- return [- BatchExportField(expression="uuid", alias="uuid"),- BatchExportField(expression="team_id", alias="team_id"),- BatchExportField(expression="timestamp", alias="timestamp"),- BatchExportField(expression="_inserted_at", alias="_inserted_at"),- BatchExportField(expression="created_at", alias="created_at"),- BatchExportField(expression="event", alias="event"),- BatchExportField(expression="properties", alias="properties"),- BatchExportField(expression="distinct_id", alias="distinct_id"),- BatchExportField(expression="set", alias="set"),- BatchExportField(- expression="set_once",- alias="set_once",- ),- ]--def is_5_min_batch_export(full_range: tuple[dt.datetime | None, dt.datetime]) -> bool:start_at, end_at = full_rangeif start_at:@@ -261,278 +229,6 @@ def use_distributed_events_recent_table(return False-class Producer:- """Async producer for batch exports.-- Attributes:- clickhouse_client: ClickHouse client used to produce RecordBatches.- _task: Used to keep track of producer background task.- """-- def __init__(self, model: RecordBatchModel | None = None):- self.model = model- self.logger = LOGGER.bind()- self._task: asyncio.Task | None = None-- @property- def task(self) -> asyncio.Task:- if self._task is None:- raise ValueError("Producer task is not initialized, have you called `Producer.start()`?")- return self._task-- async def start(- 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,- min_records_per_batch: int = 100,- **kwargs,- ) -> asyncio.Task:- """Dispatch to one of two implementations, depending on `self.model`."""- if self.model is not None:- return await self.start_with_model(- queue=queue,- 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(- queue=queue,- 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,- )-- async def start_with_model(- 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,- ):- assert self.model is not None-- self._task = asyncio.create_task(- 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,- min_records_per_batch=min_records_per_batch,- team_id=self.model.team_id,- ),- name="record_batch_producer",- )- return self._task-- async def start_without_model(- self,- queue: RecordBatchQueue,- model_name: str,- # TODO: remove once all backfill inputs are migrated- is_backfill: bool,- 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,- min_records_per_batch: int = 100,- filters: list[dict[str, str | list[str] | None]] | None = None,- order_columns: collections.abc.Iterable[str] | None = ("_inserted_at", "event"),- is_workflows: bool = False,- **parameters,- ) -> asyncio.Task:- if fields is None:- if destination_default_fields is None:- fields = default_fields()- else:- fields = destination_default_fields-- extra_query_parameters = parameters.pop("extra_query_parameters", {}) or {}-- if filters is not None and len(filters) > 0:- filters_str, extra_query_parameters = await database_sync_to_async(compose_filters_clause)(- filters, team_id=team_id, values=extra_query_parameters- )- else:- filters_str, extra_query_parameters = "", extra_query_parameters-- # TODO: this can be simplified once all backfill inputs are migrated- is_backfill = (backfill_details is not None) or is_backfill-- if model_name == "persons":- if is_backfill and full_range[0] is None:- query = SELECT_FROM_PERSONS_BACKFILL- else:- query = SELECT_FROM_PERSONS- else:- if parameters.get("exclude_events", None):- parameters["exclude_events"] = list(parameters["exclude_events"])- else:- parameters["exclude_events"] = []-- if parameters.get("include_events", None):- parameters["include_events"] = list(parameters["include_events"])- else:- parameters["include_events"] = []-- # for 5 min batch exports we query the events_recent table, which is known to have zero replication lag, but- # may not be able to handle the load from all batch exports- if is_5_min_batch_export(full_range=full_range) and not is_backfill and not is_workflows:- self.logger.debug("Using events_recent table for 5 min batch export")- query_template = SELECT_FROM_EVENTS_VIEW_RECENT- # for other batch exports that should use `events_recent` we use the `distributed_events_recent` table- # which is a distributed table that sits in front of the `events_recent` table- elif (- use_distributed_events_recent_table(- is_backfill=is_backfill, backfill_details=backfill_details, data_interval_start=full_range[0]- )- and not is_workflows- ):- self.logger.debug("Using distributed_events_recent table for batch export")- query_template = SELECT_FROM_DISTRIBUTED_EVENTS_RECENT- elif is_workflows:- self.logger.debug("Using workflows events query for batch export")- query_template = SELECT_FROM_EVENTS_WORKFLOWS- elif str(team_id) in settings.UNCONSTRAINED_TIMESTAMP_TEAM_IDS:- self.logger.debug("Using events_batch_export_unbounded view for batch export")- query_template = SELECT_FROM_EVENTS_VIEW_UNBOUNDED- elif is_backfill:- self.logger.debug("Using events_batch_export_backfill view for batch export")- query_template = SELECT_FROM_EVENTS_VIEW_BACKFILL- else:- self.logger.debug("Using events_batch_export view for batch export")- query_template = SELECT_FROM_EVENTS_VIEW- lookback_days = settings.OVERRIDE_TIMESTAMP_TEAM_IDS.get(- team_id, settings.DEFAULT_TIMESTAMP_LOOKBACK_DAYS- )- parameters["lookback_days"] = lookback_days-- if "_inserted_at" not in [field["alias"] for field in fields]:- control_fields = [BatchExportField(expression="_inserted_at", alias="_inserted_at")]- else:- control_fields = []-- query_fields = ",".join(f"{field['expression']} AS {field['alias']}" for field in fields + control_fields)-- if filters_str:- filters_str = f"AND {filters_str}"-- if str(team_id) in settings.BATCH_EXPORT_ORDERLESS_TEAM_IDS or not order_columns:- order = ""- else:- order = f"ORDER BY {','.join(order_columns)}"-- query = query_template.safe_substitute(fields=query_fields, filters=filters_str, order=order)-- parameters["team_id"] = team_id- parameters = {**parameters, **extra_query_parameters}-- self._task = asyncio.create_task(- 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,- min_records_per_batch=min_records_per_batch,- team_id=team_id,- ),- name="record_batch_producer",- )-- return self.task-- async def produce_batch_export_record_batches_from_range(- 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,- max_record_batch_size_bytes: int = 0,- min_records_per_batch: int = 100,- ):- """Produce Arrow record batches for a given date range into `queue`.-- Arguments:- 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.- max_record_batch_size_bytes: The max size in bytes of a record batch to insert in `queue`.- If a record batch is larger than this, `slice_record_batch` will be used to slice it- into smaller record batches.- min_records_batch_per_batch: If slicing a record batch, each slice should contain at least- this number of records.- """- clickhouse_url = None- # 5 min batch exports should query a single node, which is known to have zero replication lag- if is_5_min_batch_export(full_range=full_range):- clickhouse_url = settings.CLICKHOUSE_OFFLINE_5MIN_CLUSTER_HOST-- # Data can sometimes take a while to settle, so for 5 min batch exports we wait several seconds just to be safe.- # For all other batch exports we wait for 1 minute since we're querying the events_recent table using a- # distributed table and setting `max_replica_delay_for_distributed_queries` to 1 minute- if is_5_min_batch_export(full_range):- 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)-- 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)- ):- 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--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]: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 2f8f6a15b3a9..61a978f27cf8 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@@ -27,7 +27,8 @@ from products.batch_exports.backend.temporal.destinations.azure_blob_batch_expor)from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activityfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue@@ -175,7 +176,11 @@ async def assert_clickhouse_records_in_azure_blob(expected_records = []queue = RecordBatchQueue()- producer = Producer(model=SessionsRecordBatchModel(team_id)) if model_name == "sessions" else Producer()+ producer = (+ ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))+ if model_name == "sessions"+ else ClickHouseTestProducer()+ )producer_task = await producer.start(queue=queue,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 cffab19063f6..8abf51407448 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@@ -40,7 +40,8 @@ from products.batch_exports.backend.temporal.batch_exports import finish_batch_efrom products.batch_exports.backend.temporal.metrics import BATCH_EXPORT_ACTIVITY_TYPES, BATCH_EXPORT_WORKFLOW_TYPESfrom products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activityfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import (get_record_batch_from_queue,remove_duplicates_from_records,@@ -238,9 +239,9 @@ async def _get_records_from_clickhouse(records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()producer_task = await producer.start(queue=queue,diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.pyindex cb5a54e665fc..afb4dd2bb074 100644--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py@@ -18,7 +18,8 @@ from products.batch_exports.backend.temporal.destinations.bigquery_batch_exportget_our_google_cloud_credentials,)from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queueSKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS = pytest.mark.skipif(@@ -149,9 +150,9 @@ async def assert_clickhouse_records_in_bigquery(expected_records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()for data_interval_start, data_interval_end in date_ranges:producer_task = await producer.start(diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.pyindex 934b062f2eb9..13d3cdfa2d5d 100644--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py@@ -12,7 +12,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.postgres_batch_export import postgres_default_fieldsfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import (get_record_batch_from_queue,remove_duplicates_from_records,@@ -136,9 +137,9 @@ async def assert_clickhouse_records_in_postgres(expected_records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()producer_task = await producer.start(queue=queue,diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.pyindex 5e7d16ad5f0a..75bc52284cd7 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py@@ -11,8 +11,9 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.redshift_batch_export import redshift_default_fieldsfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueuefrom products.batch_exports.backend.temporal.temporary_file import remove_escaped_whitespace_recursive+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import (get_record_batch_from_queue,remove_duplicates_from_records,@@ -175,9 +176,9 @@ async def assert_clickhouse_records_in_redshift(expected_records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()for data_interval_start, data_interval_end in date_ranges:producer_task = await producer.start(diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.pyindex 7268a8aba5b6..ef1e2f3545b4 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py@@ -42,7 +42,8 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (insert_into_internal_stage_activity,)from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queuefrom products.batch_exports.backend.tests.temporal.utils.s3 import assert_file_in_s3, assert_no_files_in_s3@@ -260,9 +261,9 @@ async def assert_clickhouse_records_in_s3(queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()producer_task = await producer.start(queue=queue,model_name=model_name,diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.pyindex c8ef34e779f3..69141afa3cde 100644--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py@@ -21,7 +21,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.snowflake_batch_export import snowflake_default_fieldsfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import (get_record_batch_from_queue,remove_duplicates_from_records,@@ -451,9 +452,9 @@ async def assert_clickhouse_records_in_snowflake(expected_records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()producer_task = await producer.start(queue=queue,diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.pyindex 02cbaabb7672..88ae36f69d0b 100644--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py@@ -8,7 +8,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.workflows_batch_export import workflows_default_fieldsfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel-from products.batch_exports.backend.temporal.spmc import Producer, RecordBatchQueue+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue+from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducerfrom products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queueTeamId = str@@ -66,9 +67,9 @@ async def assert_clickhouse_records_were_handled(expected_records = []queue = RecordBatchQueue()if model_name == "sessions":- producer = Producer(model=SessionsRecordBatchModel(team_id))+ producer = ClickHouseTestProducer(model=SessionsRecordBatchModel(team_id))else:- producer = Producer()+ producer = ClickHouseTestProducer()for data_interval_start, data_interval_end in date_ranges:producer_task = await producer.start(diff --git a/products/batch_exports/backend/tests/temporal/test_spmc.py b/products/batch_exports/backend/tests/temporal/test_spmc.pyindex f7ee229c41d5..f6e29f7ce2d9 100644--- a/products/batch_exports/backend/tests/temporal/test_spmc.py+++ b/products/batch_exports/backend/tests/temporal/test_spmc.py@@ -1,4 +1,3 @@-import randomimport typingimport asyncioimport datetime as dt@@ -8,12 +7,9 @@ import pytestimport pyarrow as pa-from posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse-from products.batch_exports.backend.service import BackfillDetailsfrom products.batch_exports.backend.temporal.spmc import (InvalidFilterError,- Producer,RecordBatchQueue,compose_filters_clause,slice_record_batch,@@ -87,76 +83,6 @@ async def test_record_batch_queue_str_and_repr():assert "record_batches=1 bytes=24 schema='test: int64'" in repr(queue)-async def get_record_batch_from_queue(queue, produce_task):- while not queue.empty() or not produce_task.done():- try:- record_batch = queue.get_nowait()- except asyncio.QueueEmpty:- if produce_task.done():- break- else:- await asyncio.sleep(0.1)- continue-- return record_batch- return None---async def get_all_record_batches_from_queue(queue, produce_task):- records = []- while not queue.empty() or not produce_task.done():- record_batch = await get_record_batch_from_queue(queue, produce_task)- if record_batch is None:- break-- for record in record_batch.to_pylist():- records.append(record)- return records---async def test_record_batch_producer_uses_extra_query_parameters(clickhouse_client):- """Test RecordBatch Producer uses a HogQL value."""- team_id = random.randint(1, 1000000)- data_interval_end = dt.datetime.fromisoformat("2023-04-25T14:31:00.000000+00:00")- data_interval_start = dt.datetime.fromisoformat("2023-04-25T14:30:00.000000+00:00")-- (events, _, _) = await generate_test_events_in_clickhouse(- client=clickhouse_client,- team_id=team_id,- start_time=data_interval_start,- end_time=data_interval_end,- count=10,- count_outside_range=0,- count_other_team=0,- duplicate=False,- properties={"$browser": "Chrome", "$os": "Mac OS X", "custom": 3},- )-- queue = RecordBatchQueue()- producer = Producer()- producer_task = await producer.start(- queue=queue,- team_id=team_id,- is_backfill=False,- backfill_details=None,- model_name="events",- full_range=(data_interval_start, data_interval_end),- done_ranges=[],- fields=[- {"expression": "JSONExtractInt(properties, %(hogql_val_0)s)", "alias": "custom_prop"},- ],- extra_query_parameters={"hogql_val_0": "custom"},- )-- records = await get_all_record_batches_from_queue(queue, producer_task)-- for expected, record in zip(events, records):- if expected["properties"] is None:- raise ValueError("Empty properties")-- assert record["custom_prop"] == expected["properties"]["custom"]--def test_slice_record_batch_into_single_record_slices():"""Test we slice a record batch into slices with a single record."""n_legs = pa.array([2, 2, 4, 4, 5, 100])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.pynew file mode 100644index 000000000000..2828a21e1884--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py@@ -0,0 +1,336 @@+"""A record batch producer that reads ClickHouse directly, for use as a test reference.++Production batch exports read from the internal S3 staging area via+``temporal.pipeline.producer.Producer``. This producer instead queries ClickHouse directly+with the ``SELECT_FROM_*`` templates. Having this separate from the production producer+ensures that we can independently verify the pipeline's output.+"""++import uuid+import typing+import asyncio+import datetime as dt+import collections.abc++from django.conf import settings++from posthog.sync import database_sync_to_async+from posthog.temporal.common.clickhouse import get_client+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.record_batch_model import RecordBatchModel+from products.batch_exports.backend.temporal.spmc import (+ RecordBatchQueue,+ compose_filters_clause,+ 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.sql.events import (+ SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,+ SELECT_FROM_EVENTS_VIEW,+ SELECT_FROM_EVENTS_VIEW_BACKFILL,+ SELECT_FROM_EVENTS_VIEW_RECENT,+ SELECT_FROM_EVENTS_VIEW_UNBOUNDED,+ SELECT_FROM_EVENTS_WORKFLOWS,+)+from products.batch_exports.backend.temporal.sql.persons import SELECT_FROM_PERSONS, SELECT_FROM_PERSONS_BACKFILL++LOGGER = get_write_only_logger(__name__)+++def default_fields() -> list[BatchExportField]:+ """Return list of default batch export Fields."""+ return [+ BatchExportField(expression="uuid", alias="uuid"),+ BatchExportField(expression="team_id", alias="team_id"),+ BatchExportField(expression="timestamp", alias="timestamp"),+ BatchExportField(expression="_inserted_at", alias="_inserted_at"),+ BatchExportField(expression="created_at", alias="created_at"),+ BatchExportField(expression="event", alias="event"),+ BatchExportField(expression="properties", alias="properties"),+ BatchExportField(expression="distinct_id", alias="distinct_id"),+ BatchExportField(expression="set", alias="set"),+ BatchExportField(+ expression="set_once",+ alias="set_once",+ ),+ ]+++class ClickHouseTestProducer:+ """Async producer used in batch exports tests, which reads from ClickHouse directly.++ This used to be the SPMC producer used in production batch exports before we switched over to+ the internal stage architecture.++ Attributes:+ clickhouse_client: ClickHouse client used to produce RecordBatches.+ _task: Used to keep track of producer background task.+ """++ def __init__(self, model: RecordBatchModel | None = None):+ self.model = model+ self.logger = LOGGER.bind()+ self._task: asyncio.Task | None = None++ @property+ def task(self) -> asyncio.Task:+ if self._task is None:+ raise ValueError("Producer task is not initialized, have you called `ClickHouseTestProducer.start()`?")+ return self._task++ async def start(+ 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,+ min_records_per_batch: int = 100,+ **kwargs,+ ) -> asyncio.Task:+ """Dispatch to one of two implementations, depending on `self.model`."""+ if self.model is not None:+ return await self.start_with_model(+ queue=queue,+ 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(+ queue=queue,+ 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,+ )++ async def start_with_model(+ 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,+ ):+ assert self.model is not None++ self._task = asyncio.create_task(+ 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,+ min_records_per_batch=min_records_per_batch,+ team_id=self.model.team_id,+ ),+ name="record_batch_producer",+ )+ return self._task++ async def start_without_model(+ self,+ queue: RecordBatchQueue,+ model_name: str,+ # TODO: remove once all backfill inputs are migrated+ is_backfill: bool,+ 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,+ min_records_per_batch: int = 100,+ filters: list[dict[str, str | list[str] | None]] | None = None,+ order_columns: collections.abc.Iterable[str] | None = ("_inserted_at", "event"),+ is_workflows: bool = False,+ **parameters,+ ) -> asyncio.Task:+ if fields is None:+ if destination_default_fields is None:+ fields = default_fields()+ else:+ fields = destination_default_fields++ extra_query_parameters = parameters.pop("extra_query_parameters", {}) or {}++ if filters is not None and len(filters) > 0:+ filters_str, extra_query_parameters = await database_sync_to_async(compose_filters_clause)(+ filters, team_id=team_id, values=extra_query_parameters+ )+ else:+ filters_str, extra_query_parameters = "", extra_query_parameters++ # TODO: this can be simplified once all backfill inputs are migrated+ is_backfill = (backfill_details is not None) or is_backfill++ if model_name == "persons":+ if is_backfill and full_range[0] is None:+ query = SELECT_FROM_PERSONS_BACKFILL+ else:+ query = SELECT_FROM_PERSONS+ else:+ if parameters.get("exclude_events", None):+ parameters["exclude_events"] = list(parameters["exclude_events"])+ else:+ parameters["exclude_events"] = []++ if parameters.get("include_events", None):+ parameters["include_events"] = list(parameters["include_events"])+ else:+ parameters["include_events"] = []++ # for 5 min batch exports we query the events_recent table, which is known to have zero replication lag, but+ # may not be able to handle the load from all batch exports+ if is_5_min_batch_export(full_range=full_range) and not is_backfill and not is_workflows:+ self.logger.debug("Using events_recent table for 5 min batch export")+ query_template = SELECT_FROM_EVENTS_VIEW_RECENT+ # for other batch exports that should use `events_recent` we use the `distributed_events_recent` table+ # which is a distributed table that sits in front of the `events_recent` table+ elif (+ use_distributed_events_recent_table(+ is_backfill=is_backfill, backfill_details=backfill_details, data_interval_start=full_range[0]+ )+ and not is_workflows+ ):+ self.logger.debug("Using distributed_events_recent table for batch export")+ query_template = SELECT_FROM_DISTRIBUTED_EVENTS_RECENT+ elif is_workflows:+ self.logger.debug("Using workflows events query for batch export")+ query_template = SELECT_FROM_EVENTS_WORKFLOWS+ elif str(team_id) in settings.UNCONSTRAINED_TIMESTAMP_TEAM_IDS:+ self.logger.debug("Using events_batch_export_unbounded view for batch export")+ query_template = SELECT_FROM_EVENTS_VIEW_UNBOUNDED+ elif is_backfill:+ self.logger.debug("Using events_batch_export_backfill view for batch export")+ query_template = SELECT_FROM_EVENTS_VIEW_BACKFILL+ else:+ self.logger.debug("Using events_batch_export view for batch export")+ query_template = SELECT_FROM_EVENTS_VIEW+ lookback_days = settings.OVERRIDE_TIMESTAMP_TEAM_IDS.get(+ team_id, settings.DEFAULT_TIMESTAMP_LOOKBACK_DAYS+ )+ parameters["lookback_days"] = lookback_days++ if "_inserted_at" not in [field["alias"] for field in fields]:+ control_fields = [BatchExportField(expression="_inserted_at", alias="_inserted_at")]+ else:+ control_fields = []++ query_fields = ",".join(f"{field['expression']} AS {field['alias']}" for field in fields + control_fields)++ if filters_str:+ filters_str = f"AND {filters_str}"++ if str(team_id) in settings.BATCH_EXPORT_ORDERLESS_TEAM_IDS or not order_columns:+ order = ""+ else:+ order = f"ORDER BY {','.join(order_columns)}"++ query = query_template.safe_substitute(fields=query_fields, filters=filters_str, order=order)++ parameters["team_id"] = team_id+ parameters = {**parameters, **extra_query_parameters}++ self._task = asyncio.create_task(+ 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,+ min_records_per_batch=min_records_per_batch,+ team_id=team_id,+ ),+ name="record_batch_producer",+ )++ return self.task++ async def produce_batch_export_record_batches_from_range(+ 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,+ max_record_batch_size_bytes: int = 0,+ min_records_per_batch: int = 100,+ ):+ """Produce Arrow record batches for a given date range into `queue`.++ Arguments:+ 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.+ max_record_batch_size_bytes: The max size in bytes of a record batch to insert in `queue`.+ If a record batch is larger than this, `slice_record_batch` will be used to slice it+ into smaller record batches.+ min_records_batch_per_batch: If slicing a record batch, each slice should contain at least+ this number of records.+ """+ clickhouse_url = None+ # 5 min batch exports should query a single node, which is known to have zero replication lag+ if is_5_min_batch_export(full_range=full_range):+ clickhouse_url = settings.CLICKHOUSE_OFFLINE_5MIN_CLUSTER_HOST++ # Data can sometimes take a while to settle, so for 5 min batch exports we wait several seconds just to be safe.+ # For all other batch exports we wait for 1 minute since we're querying the events_recent table using a+ # distributed table and setting `max_replica_delay_for_distributed_queries` to 1 minute+ if is_5_min_batch_export(full_range):+ 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)++ 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)+ ):+ 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