: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
feat(batch-exports): log export progress by records delivered (#64918)
Rossd7c7cacb7cbc
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex 747374843445..631f1f95f02e 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -445,7 +445,13 @@ class ClickHouseClient:@contextlib.asynccontextmanagerasync def apost_query(- self, query, *data, query_parameters, query_id, timeout: float | None = None+ self,+ query,+ *data,+ query_parameters,+ query_id,+ timeout: float | None = None,+ settings: dict[str, str] | None = None,) -> collections.abc.AsyncIterator[aiohttp.ClientResponse]:"""POST a query to the ClickHouse HTTP interface.@@ -459,6 +465,7 @@ class ClickHouseClient:*data: Iterable of values to include in the body of the request. For example, the tuples of VALUES for an INSERT query.query_parameters: Parameters to be formatted in the query.query_id: A query ID to pass to ClickHouse.+ settings: Extra ClickHouse HTTP-interface settings to include as query-string parameters.Returns:The response received from the ClickHouse HTTP interface.@@ -467,6 +474,8 @@ class ClickHouseClient:raise ClickHouseClientNotConnected()params = {**self.params}+ if settings is not None:+ params.update(settings)if query_id is not None:params["query_id"] = query_id@@ -572,6 +581,41 @@ class ClickHouseClient:):return None+ async def execute_query_with_summary(+ self, query, *data, query_parameters=None, query_id: str | None = None, timeout: float | None = None+ ) -> dict[str, typing.Any] | None:+ """Execute the given query and return ClickHouse's query summary, if available.++ ClickHouse reports an `X-ClickHouse-Summary` response header (a JSON object with+ counters like `written_rows`, `read_rows`, `written_bytes`). We set+ `wait_end_of_query=1` so the summary reflects the completed query and is sent as a+ regular response header (rather than a trailer). Returns the parsed summary, or+ `None` if the header is absent or cannot be parsed.++ `wait_end_of_query` is an HTTP-interface URL parameter (not a SQL setting); it makes+ ClickHouse buffer the whole response server-side until the query finishes. Only use+ this for queries whose client-bound response is small — e.g. `INSERT INTO FUNCTION+ s3(...)`, whose response body is empty (rows go to S3, counts come back in the+ header) — so the buffering is negligible regardless of `http_response_buffer_size`.+ """+ async with self.apost_query(+ query,+ *data,+ query_parameters=query_parameters,+ query_id=query_id,+ timeout=timeout,+ settings={"wait_end_of_query": "1"},+ ) as response:+ summary = response.headers.get("X-ClickHouse-Summary")+ if not summary:+ self.logger.warning("No 'X-ClickHouse-Summary' header found in response")+ return None+ try:+ return json.loads(summary)+ except json.JSONDecodeError:+ self.logger.warning("Could not JSON decode 'X-ClickHouse-Summary' header", exc_info=True)+ return None+async def read_query(self, query, query_parameters=None, query_id: str | None = None) -> bytes:"""Execute the given readonly query in ClickHouse and read the response in full.@@ -693,6 +737,45 @@ class ClickHouseClient:else:raise ClickHouseQueryNotFound(query_id)+ async def aget_written_rows_from_query_log(self, query_id: str) -> int | None:+ """Fetch the number of rows a completed query wrote, from the query log.++ Reads `written_rows` from the initiating query's `QueryFinish` entry in+ `system.query_log`. Best-effort: returns None if the query isn't found (e.g. not yet+ flushed) or the value can't be parsed.+ """+ query = """+ SELECT written_rows+ FROM clusterAllReplicas({{cluster_name:String}}, system.query_log)+ WHERE query_id = {{query_id:String}}+ AND type = 'QueryFinish'+ AND is_initial_query = 1+ AND event_date >= yesterday() AND event_time >= now() - interval 24 hour+ ORDER BY event_time DESC+ LIMIT 1+ FORMAT JSONEachRow+ """++ try:+ results = await self.read_query_as_jsonl(+ query,+ query_parameters={"query_id": query_id, "cluster_name": settings.CLICKHOUSE_CLUSTER},+ query_id=f"{query_id}-GET-WRITTEN-ROWS",+ )+ except ClickHouseError:+ self.logger.warning("Failed to fetch written rows from query log", query_id=query_id, exc_info=True)+ return None++ if not results:+ self.logger.warning("Failed to fetch written rows from query log: no results found", query_id=query_id)+ return None++ try:+ return int(results[0]["written_rows"])+ except (KeyError, TypeError, ValueError):+ self.logger.warning("Failed to read written rows from query log", query_id=query_id, exc_info=True)+ return None+async def acheck_query_in_process_list(self, query_id: str) -> bool:"""Check if a query is running in the ClickHouse process list.diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 07f1cebf24b4..12096f2a58e7 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -1387,6 +1387,8 @@ class BatchExportInsertInputs:batch_export_id: str | None = Nonedestination_default_fields: list[BatchExportField] | None = Nonestage_folder: str | None = None+ # Total rows staged for this run (from ClickHouse), used to report export progress+ records_total: int | None = Noneon_demand: bool = Falsedef get_is_backfill(self) -> bool:diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.pyindex 976329850dd7..d6dc9cc23277 100644--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py@@ -379,6 +379,7 @@ async def insert_into_azure_blob_activity_from_stage(inputs: AzureBlobInsertInpuproducer_task=producer_task,transformer=transformer,json_columns=json_columns,+ records_total=inputs.records_total,)diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex b363da83506f..b2cc5aa37969 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -1479,6 +1479,7 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)consumer=consumer,transformer=transformer,json_columns=(),+ records_total=inputs.records_total,)else:diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex 318fd7ab8ba2..4873136028ca 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -1249,6 +1249,7 @@ async def insert_into_databricks_activity_from_stage(inputs: DatabricksInsertInpconsumer=consumer,producer_task=producer_task,transformer=transformer,+ records_total=inputs.records_total,)# TODO - maybe move this into the consumer finalize method?diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.pyindex 5e3ed27bfcb0..37ede6eea7fb 100644--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py@@ -998,6 +998,7 @@ async def insert_into_postgres_activity_from_stage(inputs: PostgresInsertInputs)producer_task=producer_task,transformer=transformer,json_columns=(),+ records_total=inputs.records_total,)finally:if merge_settings.requires_merge:diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.pyindex 97694d792ab2..d319c8543fe3 100644--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py@@ -1013,6 +1013,7 @@ async def insert_into_redshift_activity_from_stage(inputs: RedshiftInsertInputs)consumer=consumer,producer_task=producer_task,transformer=transformer,+ records_total=inputs.batch_export.records_total,)if merge_settings.requires_merge is True:@@ -1379,6 +1380,7 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInpproducer_task=producer_task,transformer=transformer,json_columns=table_schemas.super_columns,+ records_total=inputs.batch_export.records_total,)if result.error is not None:diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.pyindex e7837c45a9ba..2784c08351d9 100644--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py@@ -401,6 +401,7 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchEproducer_task=producer_task,transformer=transformer,json_columns=json_columns,+ records_total=inputs.records_total,)return S3BatchExportResult(bytes_exported=result.bytes_exported,diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.pyindex bc0c1bd56e5b..b5e73ad7cfae 100644--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py@@ -1449,6 +1449,7 @@ async def insert_into_snowflake_activity_from_stage(transformer=transformer,# TODO: Deprecate this argument once all other destinations are also migrated.json_columns=(),+ records_total=inputs.records_total,)# TODO - maybe move this into the consumer finalize method?diff --git a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.pyindex 375d54d84e19..e7e03bd2e93e 100644--- a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py@@ -475,6 +475,7 @@ async def insert_into_workflows_activity_from_stage(inputs: WorkflowsInsertInputtransformer=transformer,# the CDP API expects the JSON columns to be stringsjson_columns=(),+ records_total=inputs.batch_export.records_total,)# NOTE: Nothing inside the TaskGroup raises an ExceptionGroup, so it is# impossible for a nested ExceptionGroup to be captured by except*.diff --git a/products/batch_exports/backend/temporal/pipeline/consumer.py b/products/batch_exports/backend/temporal/pipeline/consumer.pyindex 6d78129a261e..8e3b89e58c9c 100644--- a/products/batch_exports/backend/temporal/pipeline/consumer.py+++ b/products/batch_exports/backend/temporal/pipeline/consumer.py@@ -1,5 +1,6 @@import abcimport enum+import timeimport typingimport asyncioimport collections.abc@@ -18,6 +19,9 @@ from products.batch_exports.backend.temporal.utils import cast_record_batch_jsonLOGGER = get_write_only_logger(__name__)EXTERNAL_LOGGER = get_logger("EXTERNAL")+# Determines how frequently we log export progress.+PROGRESS_LOG_STEP_PCT = 10+class _WaitResult(enum.Enum):"""Enumeration of possible results when concurrently waiting for two tasks."""@@ -39,12 +43,18 @@ class Consumer:self.external_logger = EXTERNAL_LOGGER.bind()self.model = model+ # Total rows expected for this run (from the staged ClickHouse count). When set, the+ # consumer logs export progress as a percentage of records delivered to the destination.+ self.records_total: int | None = None+# Progress trackingself.total_record_batches_count = 0self.total_records_count = 0self.total_record_batch_bytes_count = 0self.total_file_bytes_count = 0self.records_failed_count = 0+ self._start_monotonic: float | None = None+ self._next_progress_pct = PROGRESS_LOG_STEP_PCT@propertydef rows_exported_counter(self) -> temporalio.common.MetricCounter:@@ -62,6 +72,8 @@ class Consumer:self.total_record_batch_bytes_count = 0self.total_file_bytes_count = 0self.records_failed_count = 0+ self._start_monotonic = None+ self._next_progress_pct = PROGRESS_LOG_STEP_PCTasync def start(self,@@ -90,6 +102,7 @@ class Consumer:"""self.reset_tracking()+ self._start_monotonic = time.monotonic()self.logger.info("Starting consumer from internal S3 stage")@@ -206,6 +219,36 @@ class Consumer:self.total_record_batches_count += 1+ self._maybe_log_progress()++ def _maybe_log_progress(self) -> None:+ """Log export progress whenever a 10% step is crossed.++ Progress is measured in records delivered to the destination against the total+ staged for this run (from ClickHouse), so it reflects how far through the export+ we actually are. We report the actual percentage reached (e.g. ~11%) rather than+ the floored step, then advance the threshold to the next 10% boundary above the+ current position. Silent when the total is unknown (e.g. the stage couldn't+ report a count).+ """+ # `_start_monotonic` is set by `start()` before the consume loop, and this is only+ # called from within it, so it should always be set during a run.+ if not self.records_total or self._start_monotonic is None:+ return++ records = min(self.total_records_count, self.records_total)+ pct = records / self.records_total * 100+ if pct < self._next_progress_pct:+ return++ elapsed = time.monotonic() - self._start_monotonic+ rows_per_second = int(records / elapsed) if elapsed > 0 else 0+ self.logger.info(+ f"Exported ~{int(pct)}% to destination "+ f"({records:,} of ~{self.records_total:,} records), ~{rows_per_second:,} rows/s"+ )+ self._next_progress_pct = (int(pct // PROGRESS_LOG_STEP_PCT) + 1) * PROGRESS_LOG_STEP_PCT+@abc.abstractmethodasync def consume_chunk(self, data: bytes):"""Consume a chunk of data."""@@ -231,6 +274,7 @@ async def run_consumer_from_stage(producer_task: asyncio.Task[None],transformer: ChunkTransformerProtocol,json_columns: collections.abc.Iterable[str] = ("properties", "person_properties", "set", "set_once"),+ records_total: int | None = None,) -> BatchExportResult:"""Run a record batch consumer to batch export to a destination.@@ -243,6 +287,8 @@ async def run_consumer_from_stage(producer_task: The task that produces record batches.transformer: The transformer used to convert record batches into their desiredexport format.+ records_total: Total rows staged for this run (from ClickHouse). When provided, the+ consumer logs export progress as a percentage of records delivered.Returns:BatchExportResult (A tuple containing):@@ -250,6 +296,7 @@ async def run_consumer_from_stage(- The total number of bytes exported (this is the size of the actual dataexported, which takes into account the file type and compression)."""+ consumer.records_total = records_totalresult = await consumer.start(queue=queue,producer_task=producer_task,diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex bcd055521075..950331405da1 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -43,6 +43,7 @@ class _BatchExportInputsProtocol(typing.Protocol):destination_default_fields: list[BatchExportField] | None = Nonestage_folder: str | None = Noneon_demand: bool = False+ records_total: int | None = Noneclass _ComposedBatchExportInputsProtocol(typing.Protocol):@@ -149,32 +150,48 @@ async def execute_batch_export_using_internal_stage(raise ValueError(f"Unsupported interval: '{interval}'")try:- stage_folder = await workflow.execute_activity(- insert_into_internal_stage_activity,- BatchExportInsertIntoInternalStageInputs(- team_id=batch_export_inputs.team_id,- batch_export_id=batch_export_inputs.batch_export_id,- data_interval_start=batch_export_inputs.data_interval_start,- data_interval_end=batch_export_inputs.data_interval_end,- exclude_events=batch_export_inputs.exclude_events,- include_events=batch_export_inputs.include_events,- run_id=batch_export_inputs.run_id,- backfill_details=batch_export_inputs.backfill_details,- batch_export_model=batch_export_inputs.batch_export_model,- is_workflows=is_workflows,- batch_export_schema=batch_export_inputs.batch_export_schema,- destination_default_fields=batch_export_inputs.destination_default_fields,- ),- start_to_close_timeout=stage_activity_start_to_close_timeout,- heartbeat_timeout=dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None,- retry_policy=RetryPolicy(+ stage_inputs = BatchExportInsertIntoInternalStageInputs(+ team_id=batch_export_inputs.team_id,+ batch_export_id=batch_export_inputs.batch_export_id,+ data_interval_start=batch_export_inputs.data_interval_start,+ data_interval_end=batch_export_inputs.data_interval_end,+ exclude_events=batch_export_inputs.exclude_events,+ include_events=batch_export_inputs.include_events,+ run_id=batch_export_inputs.run_id,+ backfill_details=batch_export_inputs.backfill_details,+ batch_export_model=batch_export_inputs.batch_export_model,+ is_workflows=is_workflows,+ batch_export_schema=batch_export_inputs.batch_export_schema,+ destination_default_fields=batch_export_inputs.destination_default_fields,+ )+ stage_activity_kwargs: dict[str, typing.Any] = {+ "start_to_close_timeout": stage_activity_start_to_close_timeout,+ "heartbeat_timeout": dt.timedelta(seconds=heartbeat_timeout_seconds) if heartbeat_timeout_seconds else None,+ "retry_policy": RetryPolicy(initial_interval=dt.timedelta(seconds=initial_retry_interval_seconds),maximum_interval=dt.timedelta(seconds=maximum_stage_retry_interval_seconds),maximum_attempts=maximum_attempts,non_retryable_error_types=["InvalidFilterError", "DataIntervalEndInFutureError"],),- )- batch_export_inputs.stage_folder = stage_folder+ }+ # The stage activity's return type changed from `str` (just the folder) to+ # `InternalStageResult`. Guard with `workflow.patched` so workflows whose history+ # recorded the old bare-string result still replay correctly during a rolling deploy.+ # TODO: clean up once new code is fully rolled out+ if workflow.patched("batch-exports-stage-result"):+ stage_result = await workflow.execute_activity(+ insert_into_internal_stage_activity, stage_inputs, **stage_activity_kwargs+ )+ batch_export_inputs.stage_folder = stage_result.stage_folder+ batch_export_inputs.records_total = stage_result.records_total+ else:+ # Pass the activity by name (not the typed callable): `execute_activity` overrides+ # `result_type` with the callable's annotation, which would force the old recorded+ # `str` result to deserialize as `InternalStageResult` and fail. The string form+ # honors `result_type=str`.+ batch_export_inputs.stage_folder = await workflow.execute_activity(+ "insert_into_internal_stage_activity", stage_inputs, result_type=str, **stage_activity_kwargs+ )result = await workflow.execute_activity(activity,inputs,diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 0280ee765a18..01345ae1cd9b 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -187,6 +187,15 @@ class S3StagingFolder:url: str+@dataclass+class InternalStageResult:+ """Result of staging a batch export run's data in the internal S3 area."""++ stage_folder: str+ # Total rows written to the stage (from ClickHouse's query summary), or None if unknown.+ records_total: int | None = None++@dataclassclass BatchExportInsertIntoInternalStageInputs:"""Base dataclass for batch export insert inputs containing common fields."""@@ -224,11 +233,13 @@ class BatchExportInsertIntoInternalStageInputs:@activity.defn-async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInternalStageInputs) -> str:+async def insert_into_internal_stage_activity(+ inputs: BatchExportInsertIntoInternalStageInputs,+) -> InternalStageResult:"""Write record batches to our own internal S3 staging area.Returns:- The S3 staging folder where the data was written to.+ The S3 staging folder where the data was written to, and the total number of rows staged."""bind_contextvars(team_id=inputs.team_id,@@ -291,7 +302,7 @@ async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInter)query_or_model = query- await _write_batch_export_record_batches_to_internal_stage(+ records_total = await _write_batch_export_record_batches_to_internal_stage(query_or_model=query_or_model,full_range=full_range,query_parameters=query_parameters,@@ -302,8 +313,8 @@ async def insert_into_internal_stage_activity(inputs: BatchExportInsertIntoInters3_staging_folder_url=s3_staging_folder.url,num_partitions=num_partitions,)- logger.info("Staging data completed successfully")- return s3_staging_folder.folder+ logger.info("Staging data completed successfully", records_total=records_total)+ return InternalStageResult(stage_folder=s3_staging_folder.folder, records_total=records_total)async def compute_num_partitions(@@ -542,8 +553,12 @@ async def _write_batch_export_record_batches_to_internal_stage(data_interval_end: str,s3_staging_folder_url: str,num_partitions: int | None = None,-):- """Write record batches to our own internal S3 staging area."""+) -> 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+ determined.+ """logger = LOGGER.bind()clickhouse_url = None@@ -583,6 +598,7 @@ 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 usagefor interval_start, interval_end in generate_query_ranges(full_range, done_ranges):@@ -623,32 +639,61 @@ async def _write_batch_export_record_batches_to_internal_stage(raisetry:- await _execute_query(client, query, query_parameters)+ written_rows = await _execute_query(client, query, query_parameters)except ClickHouseError:logger.exception("ClickHouse error occurred while writing record batches to 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-async def _execute_query(client: ClickHouseClient, query: str, query_parameters: dict[str, typing.Any]) -> None:+ return total_written_rows+++def _written_rows_from_summary(summary: dict[str, typing.Any] | None) -> int | None:+ """Extract `written_rows` from a ClickHouse query summary (its values are strings)."""+ if not summary or "written_rows" not in summary:+ return None+ try:+ return int(summary["written_rows"])+ except (TypeError, ValueError):+ return None+++async def _execute_query(client: ClickHouseClient, query: str, query_parameters: dict[str, typing.Any]) -> int | None:"""Execute the batch exports query and wait for it to complete.If the query takes longer than 300 seconds, we time out and wait for the query to complete by checking the query logand process list.If the query fails, we will raise an error.++ Returns the number of rows the query wrote to the stage, or None if it couldn't be+ determined. On the happy path this comes from ClickHouse's response summary; on the+ timeout path (where the summary is lost) we recover it from the query log."""query_id = str(uuid.uuid4())logger = LOGGER.bind(query_id=query_id)with log_query_duration(logger=logger, query_id=query_id, query_type="insert_into_internal_stage"):try:- await client.execute_query(query, query_parameters=query_parameters, query_id=query_id, timeout=300)+ summary = await client.execute_query_with_summary(+ query, query_parameters=query_parameters, query_id=query_id, timeout=300+ )except ClickHouseClientTimeoutError:logger.warning("Timed-out waiting for insert into S3. Will attempt to check query status and wait for completion",timeout=300,)await _wait_for_query_completion(client, query_id)+ # The summary is gone with the timed-out response, but the query has finished, so+ # recover the written-row count from its query log entry.+ return await client.aget_written_rows_from_query_log(query_id)+ return _written_rows_from_summary(summary)async def _wait_for_query_completion(client: ClickHouseClient, query_id: str) -> None:diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_activity.pyindex 6ab754059dfc..300264eb0460 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_activity.py@@ -34,7 +34,7 @@ async def run_activity("""Run the Azure Blob export activity with internal staging."""assert inputs.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=inputs.team_id,@@ -50,7 +50,8 @@ async def run_activity(destination_default_fields=azure_blob_default_fields(),),)- inputs.stage_folder = stage_folder+ inputs.stage_folder = stage_result.stage_folder+ inputs.records_total = stage_result.records_totalreturn await activity_environment.run(insert_into_azure_blob_activity_from_stage,diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.pyindex b0f1289b3a90..4a42b41e7502 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py@@ -21,7 +21,10 @@ from products.batch_exports.backend.temporal.destinations.azure_blob_batch_exporAzureBlobBatchExportWorkflow,insert_into_azure_blob_activity_from_stage,)-from products.batch_exports.backend.temporal.pipeline.internal_stage import BatchExportInsertIntoInternalStageInputs+from products.batch_exports.backend.temporal.pipeline.internal_stage import (+ BatchExportInsertIntoInternalStageInputs,+ InternalStageResult,+)from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_runpytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -56,7 +59,7 @@ async def test_workflow_sets_failed_retryable_on_transient_error(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)async with await WorkflowEnvironment.start_time_skipping() as activity_environment:async with Worker(@@ -118,7 +121,7 @@ async def test_workflow_sets_failed_on_container_not_found(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)async with await WorkflowEnvironment.start_time_skipping() as activity_environment:async with Worker(@@ -179,7 +182,7 @@ async def test_workflow_sets_failed_on_invalid_credentials(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)async with await WorkflowEnvironment.start_time_skipping() as activity_environment:async with Worker(@@ -240,7 +243,7 @@ async def test_workflow_sets_cancelled_on_cancellation(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)@activity.defn(name="insert_into_azure_blob_activity_from_stage")async def never_finish_activity(_):diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.pyindex e428dfaeaf6b..cea274868c4c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py@@ -93,7 +93,7 @@ async def _run_activity(assert insert_inputs.batch_export_id is not None# we first need to run the insert_into_internal_stage_activity so that we have data to export- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -109,7 +109,8 @@ async def _run_activity(destination_default_fields=bigquery_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_bigquery_activity_from_stage, insert_inputs)await assert_clickhouse_records_in_bigquery(diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.pyindex b44c0377b217..2d544e1b7c95 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py@@ -84,7 +84,7 @@ async def test_export_to_file_download_bucket_puts_data_into_s3(f"batch-exports/{batch_export_id}/{run_id}/{data_interval_start.isoformat()}-{data_interval_end.isoformat()}")- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=ateam.pk,@@ -105,7 +105,8 @@ async def test_export_to_file_download_bucket_puts_data_into_s3(batch_export=BatchExportInsertInputs(team_id=ateam.pk,run_id=run_id,- stage_folder=stage_folder,+ stage_folder=stage_result.stage_folder,+ records_total=stage_result.records_total,batch_export_model=batch_export_model,batch_export_schema=batch_export_schema,batch_export_id=batch_export_id,diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_activity.pyindex a0088f20f7a0..652f00ed9f51 100644--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_activity.py@@ -78,7 +78,7 @@ async def _run_activity(# we first need to run the insert_into_internal_stage_activity so that we have data to exportassert insert_inputs.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -94,7 +94,8 @@ async def _run_activity(destination_default_fields=postgres_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_postgres_activity_from_stage, insert_inputs)await assert_clickhouse_records_in_postgres(@@ -480,7 +481,7 @@ async def test_insert_into_postgres_activity_inserts_fails_on_missing_primary_kewith override_settings(BATCH_EXPORT_POSTGRES_UPLOAD_CHUNK_SIZE_BYTES=5 * 1024**2):# First run the internal stage activityassert insert_inputs.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -496,7 +497,8 @@ async def test_insert_into_postgres_activity_inserts_fails_on_missing_primary_kedestination_default_fields=postgres_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_postgres_activity_from_stage, insert_inputs)assert result.error is not Nonediff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_activity.pyindex 3464811bee7e..f93fae20917b 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_activity.py@@ -90,7 +90,7 @@ async def _run_activity(assert insert_inputs.batch_export.batch_export_id is not None# we first need to run the insert_into_internal_stage_activity so that we have data to export- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.batch_export.team_id,@@ -106,7 +106,8 @@ async def _run_activity(destination_default_fields=redshift_default_fields(),),)- insert_inputs.batch_export.stage_folder = stage_folder+ insert_inputs.batch_export.stage_folder = stage_result.stage_folder+ insert_inputs.batch_export.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_redshift_activity_from_stage, insert_inputs)await assert_clickhouse_records_in_redshift(diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.pyindex 831bb72923f1..5268bff1167b 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_copy_activity.py@@ -129,7 +129,7 @@ async def _run_activity()assert copy_inputs.batch_export.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=copy_inputs.batch_export.team_id,@@ -145,7 +145,8 @@ async def _run_activity(destination_default_fields=redshift_default_fields(),),)- copy_inputs.batch_export.stage_folder = stage_folder+ copy_inputs.batch_export.stage_folder = stage_result.stage_folder+ copy_inputs.batch_export.records_total = stage_result.records_totalresult = await activity_environment.run(copy_into_redshift_activity_from_stage, copy_inputs)if not assert_records:diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.pyindex dba5ab8e9ce2..48b6e4b8ed9b 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py@@ -30,6 +30,7 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export import)from products.batch_exports.backend.temporal.pipeline.internal_stage import (BatchExportInsertIntoInternalStageInputs,+ InternalStageResult,insert_into_internal_stage_activity,)from products.batch_exports.backend.tests.temporal.destinations.s3.utils import assert_clickhouse_records_in_s3@@ -67,7 +68,7 @@ async def test_s3_export_workflow_handles_unexpected_insert_activity_errors(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)async with await WorkflowEnvironment.start_time_skipping() as activity_environment:async with Worker(@@ -133,7 +134,7 @@ async def test_s3_export_workflow_handles_insert_activity_non_retryable_errors(@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)async with await WorkflowEnvironment.start_time_skipping() as activity_environment:async with Worker(@@ -186,7 +187,7 @@ async def test_s3_export_workflow_handles_cancellation(ateam, s3_compatible_batc@activity.defn(name="insert_into_internal_stage_activity")async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):- return+ return InternalStageResult(stage_folder="test-stage-folder", records_total=None)@activity.defn(name="insert_into_s3_activity_from_stage")async def never_finish_activity_from_stage(_):diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.pyindex b7c8f524a4fc..bab147b20187 100644--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py@@ -453,7 +453,7 @@ async def run_activity(activity_environment: ActivityEnvironment, insert_inputs:BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES=5 * 1024**2,):assert insert_inputs.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -469,7 +469,8 @@ async def run_activity(activity_environment: ActivityEnvironment, insert_inputs:destination_default_fields=s3_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_s3_activity_from_stage, insert_inputs)return resultdiff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.pyindex 8562b51eab2a..577946ff02b2 100644--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py@@ -82,7 +82,7 @@ async def _run_activity(assert insert_inputs.batch_export_id is not None# we first need to run the insert_into_internal_stage_activity so that we have data to export- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -98,7 +98,8 @@ async def _run_activity(destination_default_fields=snowflake_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalresult = await activity_environment.run(insert_into_snowflake_activity_from_stage, insert_inputs)if assert_clickhouse_records:@@ -478,7 +479,7 @@ async def test_insert_into_snowflake_activity_heartbeats(with override_settings(BATCH_EXPORT_SNOWFLAKE_UPLOAD_CHUNK_SIZE_BYTES=0):assert insert_inputs.batch_export_id is not None- stage_folder = await activity_environment.run(+ stage_result = await activity_environment.run(insert_into_internal_stage_activity,BatchExportInsertIntoInternalStageInputs(team_id=insert_inputs.team_id,@@ -494,7 +495,8 @@ async def test_insert_into_snowflake_activity_heartbeats(destination_default_fields=snowflake_default_fields(),),)- insert_inputs.stage_folder = stage_folder+ insert_inputs.stage_folder = stage_result.stage_folder+ insert_inputs.records_total = stage_result.records_totalawait activity_environment.run(insert_into_snowflake_activity_from_stage, insert_inputs)# It's not guaranteed we will heartbeat right after every file.diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py b/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.pynew file mode 100644index 000000000000..c9ded7e83373--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py@@ -0,0 +1,149 @@+import asyncio++import pytest+from unittest.mock import MagicMock, patch++import pyarrow as pa+from structlog.testing import capture_logs++from products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stage+from products.batch_exports.backend.temporal.pipeline.transformer import Chunk+from products.batch_exports.backend.temporal.spmc import RecordBatchQueue++pytestmark = [pytest.mark.asyncio]+++class NoOpConsumer(Consumer):+ async def consume_chunk(self, data: bytes):+ pass++ async def finalize_file(self):+ pass++ async def finalize(self):+ pass+++class FakeTransformer:+ """Transformer yielding one fixed-size chunk per record batch."""++ def __init__(self, chunk_size: int = 10):+ self.chunk_size = chunk_size++ async def iter(self, record_batches):+ async for _ in record_batches:+ yield Chunk(b"x" * self.chunk_size, True)+++def get_progress_logs(cap_logs) -> list[str]:+ """Returns the captured logs that are related to progress logging.++ `capture_logs` grabs the structured event dict before rendering, so the message is under+ "event". In production these go through LogMessagesRenderer and are emitted as JSON strings,+ so this dict-indexing only works under the test logging setup.+ """+ return [log["event"] for log in cap_logs if log["event"].startswith("Exported ~")]+++def consumer() -> NoOpConsumer:+ consumer = NoOpConsumer()+ consumer._start_monotonic = 0.0+ return consumer+++ "records_done,records_total,expected_pct",+ [+ (0, 1000, None),+ (99, 1000, None),+ (100, 1000, 10),+ # Actual percentage is reported, not floored to the 10% step.+ (115, 1000, 11),+ (230, 1000, 23),+ (1000, 1000, 100),+ # Going over the estimate is clamped to 100%. Shouldn't happen in practice.+ (1500, 1000, 100),+ ],+)+async def test_maybe_log_progress_reports_actual_pct(consumer, records_done, records_total, expected_pct):+ consumer.records_total = records_total+ consumer.total_records_count = records_done++ with capture_logs() as cap_logs:+ consumer._maybe_log_progress()++ progress_logs = get_progress_logs(cap_logs)+ if expected_pct is None:+ assert progress_logs == []+ else:+ assert len(progress_logs) == 1+ assert progress_logs[0].startswith(f"Exported ~{expected_pct}%")++[email protected]("records_total", [None, 0])+async def test_maybe_log_progress_is_silent_without_known_total(consumer, records_total):+ consumer.records_total = records_total+ consumer.total_records_count = 100++ with capture_logs() as cap_logs:+ consumer._maybe_log_progress()++ assert get_progress_logs(cap_logs) == []+++async def test_maybe_log_progress_logs_each_step_once(consumer):+ consumer.records_total = 1000+ consumer.total_records_count = 110++ with capture_logs() as cap_logs:+ consumer._maybe_log_progress()+ consumer._maybe_log_progress()+ # Still within the same 10% step (19% < next threshold of 20%), so no new log.+ consumer.total_records_count = 190+ consumer._maybe_log_progress()+ consumer.total_records_count = 210+ consumer._maybe_log_progress()++ progress_logs = get_progress_logs(cap_logs)+ assert len(progress_logs) == 2+ assert progress_logs[0].startswith("Exported ~11%")+ assert progress_logs[1].startswith("Exported ~21%")+++async def _put_record_batches_and_finish(queue: RecordBatchQueue, record_batches: list[pa.RecordBatch]) -> None:+ for record_batch in record_batches:+ await queue.put(record_batch)+++def mock_metrics():+ consumer_module = "products.batch_exports.backend.temporal.pipeline.consumer"+ with (+ patch(f"{consumer_module}.get_rows_exported_metric", return_value=MagicMock()),+ patch(f"{consumer_module}.get_bytes_exported_metric", return_value=MagicMock()),+ ):+ yield+++async def test_run_consumer_from_stage_logs_progress_throughout(mock_metrics):+ consumer = NoOpConsumer()+ queue = RecordBatchQueue()+ # 10 batches of 10 records against a known total of 100, so each batch crosses a 10% step.+ record_batches = [pa.RecordBatch.from_pydict({"value": list(range(10))}) for _ in range(10)]+ producer_task = asyncio.create_task(_put_record_batches_and_finish(queue, record_batches))++ with capture_logs() as cap_logs:+ result = await run_consumer_from_stage(+ queue=queue,+ consumer=consumer,+ producer_task=producer_task,+ transformer=FakeTransformer(chunk_size=10),+ json_columns=(),+ records_total=100,+ )++ assert consumer.records_total == 100+ assert result.records_completed == 100+ progress_logs = get_progress_logs(cap_logs)+ assert [log.split("%")[0] for log in progress_logs] == [f"Exported ~{step}" for step in range(10, 101, 10)]diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.pyindex 2517d7b48559..83a7af5532ff 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py@@ -13,10 +13,11 @@ from django.test.utils import override_settingsimport pyarrow as paimport pytest_asyncio+from structlog.testing import capture_logsfrom temporalio.testing import ActivityEnvironmentfrom posthog.models.scoping import team_scope-from posthog.temporal.common.clickhouse import ClickHouseClient+from posthog.temporal.common.clickhouse import ClickHouseClient, ClickHouseClientTimeoutError, ClickHouseQueryStatusfrom products.batch_exports.backend.models.batch_export import (BatchExport,@@ -28,6 +29,7 @@ from products.batch_exports.backend.service import BackfillDetails, BatchExportMfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (BatchExportInsertIntoInternalStageInputs,DataIntervalEndInFutureError,+ _execute_query,_write_batch_export_record_batches_to_internal_stage,compute_num_partitions,insert_into_internal_stage_activity,@@ -278,7 +280,8 @@ async def _run_activity(destination_default_fields=None,)- stage_folder = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_result = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_folder = stage_result.stage_folderawait assert_files_in_s3(minio_client,bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET,@@ -336,6 +339,56 @@ async def test_insert_into_stage_activity_for_events_model(assert len(records_exported) == len(events_to_export_created)[email protected]("interval", ["day"], indirect=True)+ "model",+ [+ BatchExportModel(name="events", schema=None),+ ],+)[email protected]("data_interval_end", [TEST_DATA_INTERVAL_END])+async def test_insert_into_stage_activity_reports_records_total_for_events_model(+ generate_test_data,+ interval,+ activity_environment,+ data_interval_start,+ minio_client,+ data_interval_end,+ ateam,+ model: BatchExportModel,+):+ """The activity reports the number of rows written to the stage, from ClickHouse's query summary."""++ with capture_logs() as cap_logs:+ records_exported = await _run_activity(+ activity_environment=activity_environment,+ minio_client=minio_client,+ team_id=ateam.pk,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ model=model,+ )++ events_to_export_created = generate_test_data[0]+ completed_logs = [log for log in cap_logs if log["event"] == "Staging data completed successfully"]+ assert len(completed_logs) == 1+ assert completed_logs[0]["records_total"] == len(events_to_export_created) == len(records_exported)++[email protected]("query_log_written_rows", [4242, None])+async def test_execute_query_recovers_written_rows_from_query_log_on_timeout(query_log_written_rows):+ """When the insert times out client-side, the row count is recovered from the query log."""+ client = AsyncMock()+ client.execute_query_with_summary.side_effect = ClickHouseClientTimeoutError("INSERT ...", "test-query-id")+ client.acheck_query.return_value = ClickHouseQueryStatus.FINISHED+ client.aget_written_rows_from_query_log.return_value = query_log_written_rows++ result = await _execute_query(client, "INSERT INTO FUNCTION s3(...) SELECT ...", {})++ assert result == query_log_written_rows+ client.aget_written_rows_from_query_log.assert_awaited_once()++class PersonToExport(t.TypedDict):team_id: intperson_id: str@@ -943,7 +996,8 @@ async def test_insert_into_stage_activity_writes_dynamic_number_of_files(BATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=1,BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=50,):- stage_folder = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_result = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_folder = stage_result.stage_folder_, keys = await assert_files_in_s3(minio_client,@@ -991,7 +1045,8 @@ async def test_insert_into_stage_activity_uses_static_default_without_previous_rBATCH_EXPORT_CLICKHOUSE_S3_MIN_PARTITIONS=1,BATCH_EXPORT_CLICKHOUSE_S3_MAX_PARTITIONS=50,):- stage_folder = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_result = await activity_environment.run(insert_into_internal_stage_activity, insert_inputs)+ stage_folder = stage_result.stage_folder_, keys = await assert_files_in_s3(minio_client,diff --git a/products/batch_exports/backend/tests/temporal/utils/mock_clickhouse.py b/products/batch_exports/backend/tests/temporal/utils/mock_clickhouse.pyindex 9870ccc6cdd5..c9b820d3f796 100644--- a/products/batch_exports/backend/tests/temporal/utils/mock_clickhouse.py+++ b/products/batch_exports/backend/tests/temporal/utils/mock_clickhouse.py@@ -32,11 +32,13 @@ class MockClickHouseClient:def __init__(self,read_query_as_jsonl_responses: JsonResponseSequence | None = None,+ written_rows: int = 0,):self.calls: list[CapturedCall] = []self.mock_client = AsyncMock(spec=ClickHouseClient)self.mock_client.read_query_as_jsonl = self._capture_read_query_as_jsonlself.mock_client.execute_query = self._capture_execute_query+ self.mock_client.execute_query_with_summary = self._capture_execute_query_with_summaryself.mock_client_cm = mock.AsyncMock()self.mock_client_cm.__aenter__.return_value = self.mock_clientself.mock_client_cm.__aexit__.return_value = None@@ -45,6 +47,9 @@ class MockClickHouseClient:# Each call pops from the front; the last value is reused for any extra calls.self.read_query_as_jsonl_responses: JsonResponseSequence = read_query_as_jsonl_responses or []+ # `written_rows` reported back in the query summary by `execute_query_with_summary`.+ self.written_rows = written_rows+# -- recording helpers ---------------------------------------------------def _snapshot_call(self, query: str, query_parameters: dict | None, query_id: str | None) -> None:@@ -67,6 +72,10 @@ class MockClickHouseClient:async def _capture_execute_query(self, query, *data, query_parameters=None, query_id=None, **kwargs):self._snapshot_call(query, query_parameters, query_id)+ async def _capture_execute_query_with_summary(self, query, *data, query_parameters=None, query_id=None, **kwargs):+ self._snapshot_call(query, query_parameters, query_id)+ return {"written_rows": str(self.written_rows)}+# -- assertion helpers ---------------------------------------------------def expect_query_count(self, expected: int) -> None: