Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(batch-exports): add pipeline spans for bottleneck attribution (#68233)

Ross913d6b9ad67d
diff --git a/products/batch_exports/backend/temporal/metrics.py b/products/batch_exports/backend/temporal/metrics.py
index 8944dfd3fe13..a7f2b5f45894 100644
--- a/products/batch_exports/backend/temporal/metrics.py
+++ b/products/batch_exports/backend/temporal/metrics.py
@@ -79,6 +79,21 @@ def get_export_finished_metric(status: str, model: str) -> MetricCounter:
)
+class CumulativeTimer:
+ """Accumulate wall-clock time spent across many timed sections."""
+
+ def __init__(self) -> None:
+ self.total_seconds: float = 0.0
+
+ @contextmanager
+ def time(self) -> typing.Iterator[None]:
+ start = time.perf_counter()
+ try:
+ yield
+ finally:
+ self.total_seconds += time.perf_counter() - start
+
+
Attributes = dict[str, str | int | float | bool]
diff --git a/products/batch_exports/backend/temporal/pipeline/consumer.py b/products/batch_exports/backend/temporal/pipeline/consumer.py
index 8e3b89e58c9c..9ad383cda614 100644
--- a/products/batch_exports/backend/temporal/pipeline/consumer.py
+++ b/products/batch_exports/backend/temporal/pipeline/consumer.py
@@ -7,10 +7,15 @@ import collections.abc
import pyarrow as pa
import temporalio.common
+from opentelemetry import trace
from posthog.temporal.common.logger import get_logger, get_write_only_logger
-from products.batch_exports.backend.temporal.metrics import get_bytes_exported_metric, get_rows_exported_metric
+from products.batch_exports.backend.temporal.metrics import (
+ CumulativeTimer,
+ get_bytes_exported_metric,
+ get_rows_exported_metric,
+)
from products.batch_exports.backend.temporal.pipeline.transformer import ChunkTransformerProtocol
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, raise_on_task_failure
@@ -18,6 +23,7 @@ from products.batch_exports.backend.temporal.utils import cast_record_batch_json
LOGGER = get_write_only_logger(__name__)
EXTERNAL_LOGGER = get_logger("EXTERNAL")
+TRACER = trace.get_tracer(__name__)
# Determines how frequently we log export progress.
PROGRESS_LOG_STEP_PCT = 10
@@ -56,6 +62,13 @@ class Consumer:
self._start_monotonic: float | None = None
self._next_progress_pct = PROGRESS_LOG_STEP_PCT
+ # Stage-attribution timers, reported as span attributes:
+ # Queue-get wait is time spent starved waiting for the producer
+ self._queue_get_wait_timer = CumulativeTimer()
+ # consume time is time spent handing chunks to the destination consumer
+ # (`consume_chunk`/`finalize_file`/`finalize`).
+ self._consume_timer = CumulativeTimer()
+
@property
def rows_exported_counter(self) -> temporalio.common.MetricCounter:
"""Access the rows exported metric counter."""
@@ -74,6 +87,8 @@ class Consumer:
self.records_failed_count = 0
self._start_monotonic = None
self._next_progress_pct = PROGRESS_LOG_STEP_PCT
+ self._queue_get_wait_timer = CumulativeTimer()
+ self._consume_timer = CumulativeTimer()
async def start(
self,
@@ -102,28 +117,35 @@ class Consumer:
"""
self.reset_tracking()
- self._start_monotonic = time.monotonic()
+ start_monotonic = time.monotonic()
+ self._start_monotonic = start_monotonic
self.logger.info("Starting consumer from internal S3 stage")
- try:
- async for chunk, is_eof in transformer.iter(
- self.generate_record_batches_from_queue(queue, producer_task, json_columns),
- ):
- chunk_size = len(chunk)
- self.total_file_bytes_count += chunk_size
+ with TRACER.start_as_current_span("batch_export.consumer") as span:
+ try:
+ async for chunk, is_eof in transformer.iter(
+ self.generate_record_batches_from_queue(queue, producer_task, json_columns),
+ ):
+ chunk_size = len(chunk)
+ self.total_file_bytes_count += chunk_size
- await self.consume_chunk(data=chunk)
- self.bytes_exported_counter.add(chunk_size)
+ with self._consume_timer.time():
+ await self.consume_chunk(data=chunk)
+ self.bytes_exported_counter.add(chunk_size)
- if is_eof:
- await self.finalize_file()
+ if is_eof:
+ with self._consume_timer.time():
+ await self.finalize_file()
- await self.finalize()
+ with self._consume_timer.time():
+ await self.finalize()
- except Exception:
- self.logger.exception("Unexpected error occurred while consuming record batches")
- raise
+ except Exception:
+ self.logger.exception("Unexpected error occurred while consuming record batches")
+ raise
+ finally:
+ self._set_stage_attribution_span_attributes(span, elapsed=time.monotonic() - start_monotonic)
self.logger.info(
f"Finished consuming {self.total_records_count:,} records, {self.total_record_batch_bytes_count / 1024**2:.2f} MiB "
@@ -132,6 +154,29 @@ class Consumer:
)
return BatchExportResult(self.total_records_count, self.total_file_bytes_count)
+ def _set_stage_attribution_span_attributes(self, span: trace.Span, elapsed: float) -> None:
+ """Report where consumer time went as attributes on the consumer span.
+
+ It's unrealistic to create spans for each individual call to queue.get(), consume_chunk(),
+ etc. as there could be thousands of these for larger batch exports. However, tracking and
+ reporting the cumulative time spent in each of these tasks is useful for monitoring where
+ potential bottlenecks lie.
+ """
+ consume_seconds = self._consume_timer.total_seconds
+ queue_get_wait_seconds = self._queue_get_wait_timer.total_seconds
+ # What's left after subtracting consume time and queue starvation is
+ # transformation time, plus a small amount of loop overhead.
+ transform_seconds = max(0.0, elapsed - consume_seconds - queue_get_wait_seconds)
+ span.set_attributes(
+ {
+ "batch_export.consumer.records_consumed": self.total_records_count,
+ "batch_export.consumer.bytes_exported": self.total_file_bytes_count,
+ "batch_export.consumer.total_queue_get_wait_seconds": queue_get_wait_seconds,
+ "batch_export.consumer.total_consume_seconds": consume_seconds,
+ "batch_export.consumer.total_transform_seconds": transform_seconds,
+ }
+ )
+
def collect_result(self) -> BatchExportResult:
"""Collect the result of the consumer.
@@ -170,7 +215,8 @@ class Consumer:
while True:
get_task = asyncio.create_task(queue.get())
- _ = await asyncio.wait((get_task, producer_task), return_when=asyncio.FIRST_COMPLETED)
+ with self._queue_get_wait_timer.time():
+ _ = await asyncio.wait((get_task, producer_task), return_when=asyncio.FIRST_COMPLETED)
wait_result = _WaitResult((get_task.done(), producer_task.done()))
match wait_result:
@@ -185,7 +231,8 @@ class Consumer:
get_task.cancel()
break
else:
- record_batch = await get_task
+ with self._queue_get_wait_timer.time():
+ record_batch = await get_task
case _:
typing.assert_never(wait_result)
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 01345ae1cd9b..d2a7184ed911 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -13,6 +13,7 @@ from django.conf import settings
import aioboto3
from aiobotocore.config import AioConfig
from aiobotocore.httpsession import AIOHTTPSession as BaseAIOHTTPSession
+from opentelemetry import trace
from temporalio import activity
from posthog.clickhouse import query_tagging
@@ -70,6 +71,7 @@ from products.batch_exports.backend.temporal.sql import (
from products.batch_exports.backend.temporal.utils import set_status_to_running_task
LOGGER = get_write_only_logger()
+TRACER = trace.get_tracer(__name__)
class DataIntervalEndInFutureError(Exception):
@@ -579,7 +581,8 @@ async def _write_batch_export_record_batches_to_internal_stage(
# Some tests create data in the future, so we do not check this.
raise DataIntervalEndInFutureError(end_at)
- await wait_for_delta_past_data_interval_end(end_at, delta)
+ with TRACER.start_as_current_span("batch_export.stage.wait_for_delta"):
+ await wait_for_delta_past_data_interval_end(end_at, delta)
done_ranges: list[tuple[dt.datetime, dt.datetime]] = []
async with get_client(
@@ -629,9 +632,10 @@ async def _write_batch_export_record_batches_to_internal_stage(
# however, since we only make use of the most recent attempt, we can save on storage space by deleting the
# files here.
try:
- await _delete_all_from_bucket_with_prefix(
- bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, key_prefix=base_s3_staging_folder
- )
+ with TRACER.start_as_current_span("batch_export.stage.delete_existing_objects"):
+ await _delete_all_from_bucket_with_prefix(
+ bucket_name=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, key_prefix=base_s3_staging_folder
+ )
except Exception:
logger.exception(
"Unexpected error occurred while deleting existing objects from internal S3 staging bucket",
@@ -639,7 +643,10 @@ async def _write_batch_export_record_batches_to_internal_stage(
raise
try:
- written_rows = await _execute_query(client, query, query_parameters)
+ with TRACER.start_as_current_span("batch_export.stage.clickhouse_query") as query_span:
+ written_rows = await _execute_query(client, query, query_parameters)
+ if written_rows is not None:
+ query_span.set_attribute("batch_export.stage.written_rows", written_rows)
except ClickHouseError:
logger.exception(
"ClickHouse error occurred while writing record batches to internal S3 staging bucket",
diff --git a/products/batch_exports/backend/temporal/pipeline/producer.py b/products/batch_exports/backend/temporal/pipeline/producer.py
index 2e065987af93..8befc874a713 100644
--- a/products/batch_exports/backend/temporal/pipeline/producer.py
+++ b/products/batch_exports/backend/temporal/pipeline/producer.py
@@ -4,10 +4,12 @@ import asyncio
from django.conf import settings
from aiobotocore.response import StreamingBody
+from opentelemetry import trace
import posthog.temporal.common.asyncpa as asyncpa
from posthog.temporal.common.logger import get_write_only_logger
+from products.batch_exports.backend.temporal.metrics import CumulativeTimer
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder, get_s3_client
from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, slice_record_batch
from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
@@ -17,6 +19,7 @@ if typing.TYPE_CHECKING:
LOGGER = get_write_only_logger(__name__)
+TRACER = trace.get_tracer(__name__)
class Producer:
@@ -29,6 +32,14 @@ class Producer:
self.logger = LOGGER.bind()
self._task: asyncio.Task | None = None
+ # Stage-attribution counters, reported as span attributes. The put-wait timer sums the
+ # time readers spend blocked on `queue.put()` (i.e. downstream backpressure).
+ # Note: since we have up to BATCH_EXPORT_PRODUCER_MAX_CONCURRENT_FILE_READS concurrent
+ # readers this is cumulative task-seconds and can exceed wall-clock time.
+ self._queue_put_wait_timer = CumulativeTimer()
+ self.records_produced: int = 0
+ self.bytes_produced: int = 0
+
@property
def task(self) -> asyncio.Task:
if self._task is None:
@@ -77,24 +88,40 @@ class Producer:
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
)
- async with get_s3_client() as s3_client:
- response = await s3_client.list_objects_v2(
- Bucket=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, Prefix=stage_folder
- )
- if not (contents := response.get("Contents", [])):
- self.logger.info(f"No files found in S3 with prefix '{stage_folder}' -> assuming no data to export")
- return
- keys = [obj["Key"] for obj in contents if "Key" in obj]
- self.logger.info(f"Producer found {len(keys)} files in S3 stage, with prefix '{stage_folder}'")
-
- # Read in batches
- try:
- await self._stream_record_batches_from_s3(
- s3_client, keys, queue, max_record_batch_size_bytes, min_records_per_batch
- )
- except Exception as e:
- self.logger.exception("Unexpected error occurred while producing record batches", exc_info=e)
- raise
+ with TRACER.start_as_current_span("batch_export.producer") as span:
+ async with get_s3_client() as s3_client:
+ try:
+ keys = await self._list_keys(s3_client, stage_folder)
+ span.set_attribute("batch_export.producer.num_files", len(keys))
+ if not keys:
+ return
+
+ # Read in batches
+ await self._stream_record_batches_from_s3(
+ s3_client, keys, queue, max_record_batch_size_bytes, min_records_per_batch
+ )
+ except Exception as e:
+ self.logger.exception("Unexpected error occurred while producing record batches", exc_info=e)
+ raise
+ finally:
+ span.set_attributes(
+ {
+ "batch_export.producer.records_produced": self.records_produced,
+ "batch_export.producer.bytes_produced": self.bytes_produced,
+ "batch_export.producer.total_queue_put_wait_seconds": self._queue_put_wait_timer.total_seconds,
+ }
+ )
+
+ async def _list_keys(self, s3_client: "S3Client", stage_folder: str) -> list[str]:
+ response = await s3_client.list_objects_v2(
+ Bucket=settings.BATCH_EXPORT_INTERNAL_STAGING_BUCKET, Prefix=stage_folder
+ )
+ if not (contents := response.get("Contents", [])):
+ self.logger.info(f"No files found in S3 with prefix '{stage_folder}' -> assuming no data to export")
+ return []
+ keys = [obj["Key"] for obj in contents if "Key" in obj]
+ self.logger.info(f"Producer found {len(keys)} files in S3 stage, with prefix '{stage_folder}'")
+ return keys
async def _stream_record_batches_from_s3(
self,
@@ -115,7 +142,10 @@ class Producer:
async for batch in reader:
for record_batch_slice in slice_record_batch(batch, max_record_batch_size_bytes, min_records_per_batch):
- await queue.put(record_batch_slice)
+ with self._queue_put_wait_timer.time():
+ await queue.put(record_batch_slice)
+ self.records_produced += record_batch_slice.num_rows
+ self.bytes_produced += record_batch_slice.nbytes
self.logger.info("Finished stream", key=key)