: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
chore(batch-exports): add batch export attributes to worker traces (#67772)
Ross108806a7368d
diff --git a/posthog/temporal/common/client.py b/posthog/temporal/common/client.pyindex 9971a38664df..f3be263786ff 100644--- a/posthog/temporal/common/client.py+++ b/posthog/temporal/common/client.py@@ -1,4 +1,5 @@import dataclasses+import collections.abcfrom typing import Anyfrom django.conf import settings as django_settings@@ -6,7 +7,7 @@ from django.conf import settings as django_settingsimport temporalio.converterimport temporalio.contrib.opentelemetryfrom asgiref.sync import async_to_sync-from temporalio.client import Client, TLSConfig+from temporalio.client import Client, Plugin, TLSConfigfrom temporalio.contrib.pydantic import pydantic_data_converterfrom temporalio.runtime import Runtime@@ -24,6 +25,7 @@ async def connect(settings: Any | None = django_settings,use_pydantic_converter: bool = False,add_otel_tracing_interceptor: bool = True,+ plugins: collections.abc.Sequence[Plugin] = (),) -> Client:tls: TLSConfig | bool = Falseif client_cert and client_key:@@ -46,9 +48,10 @@ async def connect(# The classic TracingInterceptor injects trace context into workflow start headers (so a# caller's span becomes the parent of the workflow) AND creates spans for activity/workflow# execution on any worker built from this client. Worker processes disable it via- # `add_otel_tracing_interceptor=False` because they trace execution through the worker's- # OpenTelemetryPlugin instead; leaving both on double-instruments every activity and workflow.- # Non-worker callers (Django, Celery, the CLI, schedules) keep it for start-context propagation.+ # `add_otel_tracing_interceptor=False` because they trace execution through the+ # OpenTelemetryPlugin (passed via `plugins`) instead; leaving both on double-instruments+ # every activity and workflow. Non-worker callers (Django, Celery, the CLI, schedules) keep+ # it for start-context propagation.interceptors: list[temporalio.client.Interceptor] = []if add_otel_tracing_interceptor:interceptors.append(temporalio.contrib.opentelemetry.TracingInterceptor())@@ -60,6 +63,7 @@ async def connect(runtime=runtime,interceptors=interceptors,data_converter=data_converter,+ plugins=list(plugins),)return clientdiff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex 1a3eac688125..a34e4ebc31c3 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -9,9 +9,10 @@ from dataclasses import dataclassfrom django.conf import settingsfrom prometheus_client import REGISTRY+from temporalio.client import Pluginfrom temporalio.contrib.opentelemetry import OpenTelemetryPluginfrom temporalio.runtime import PrometheusConfig, Runtime, TelemetryConfig-from temporalio.worker import Plugin, ResourceBasedSlotConfig, UnsandboxedWorkflowRunner, Worker, WorkerTuner+from temporalio.worker import ResourceBasedSlotConfig, UnsandboxedWorkflowRunner, Worker, WorkerTunerfrom posthog.temporal.ai_observability.eval_reports.metrics import (EVAL_REPORTS_LATENCY_HISTOGRAM_BUCKETS,@@ -238,6 +239,7 @@ async def create_worker(Defaults to 1.0. Only takes effect if target_memory_usage is set.enable_combined_metrics_server: Whether to start the combined metrics server. Defaults to True.Set to False to disable the metrics server (useful when it causes GIL contention issues).+ enable_open_telemetry_plugin: Whether to trace execution with OTel spans. Requires initialize_otel."""metrics_server: CombinedMetricsServer | None = None@@ -257,11 +259,6 @@ async def create_worker(# Expose Temporal SDK metrics directly on the public metrics port.temporal_metrics_bind_address = f"0.0.0.0:{metrics_port}"- if enable_open_telemetry_plugin:- plugins: collections.abc.Sequence[Plugin] = (OpenTelemetryPlugin(add_temporal_spans=True),)- else:- plugins = ()-histogram_bucket_overrides: dict[str, list[float]] = (dict(zip(@@ -341,6 +338,12 @@ async def create_worker(),))+ # Register the OpenTelemetryPlugin on the client, not the worker, following the SDK's guidance+ # (temporalio/contrib/opentelemetry/README.md).+ plugins: collections.abc.Sequence[Plugin] = (+ (OpenTelemetryPlugin(add_temporal_spans=True),) if enable_open_telemetry_plugin else ()+ )+client = await connect(host,port,@@ -350,10 +353,11 @@ async def create_worker(client_key=client_key,runtime=runtime,use_pydantic_converter=use_pydantic_converter,- # This worker traces activity/workflow execution through the OpenTelemetryPlugin below.+ # This worker traces activity/workflow execution through the OpenTelemetryPlugin above.# Keeping the client-level TracingInterceptor as well would emit a second, duplicate span# for every activity and workflow, so drop it here.add_otel_tracing_interceptor=False,+ plugins=plugins,)supported_interceptors = [interceptor() for interceptor in ALL_INTERCEPTOR_CLASSES if is_task_queue_supported(task_queue, interceptor)@@ -378,7 +382,6 @@ async def create_worker(# Worker will flush heartbeats every# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).max_heartbeat_throttle_interval=dt.timedelta(seconds=5),- plugins=plugins,)else:worker = Worker(@@ -395,7 +398,6 @@ async def create_worker(# Worker will flush heartbeats every# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).max_heartbeat_throttle_interval=dt.timedelta(seconds=5),- plugins=plugins,)return ManagedWorker(worker=worker, metrics_server=metrics_server)diff --git a/products/batch_exports/backend/temporal/metrics.py b/products/batch_exports/backend/temporal/metrics.pyindex 3996ac72de79..8944dfd3fe13 100644--- a/products/batch_exports/backend/temporal/metrics.py+++ b/products/batch_exports/backend/temporal/metrics.py@@ -7,6 +7,7 @@ from contextlib import contextmanagerfrom django.conf import settingsimport structlog+from opentelemetry import tracefrom temporalio import activity, workflowfrom temporalio.common import MetricCounter, MetricMeterfrom temporalio.worker import (@@ -113,8 +114,32 @@ def get_metric_meter(additional_attributes: Attributes | None = None) -> MetricMreturn meter+def _tag_span_with_batch_export_context(attributes: dict[str, str | int | float | bool | None]) -> None:+ """Enrich the active OTel span (the RunActivity/RunWorkflow span emitted by the OTel plugin)+ with batch export metadata.++ This annotates traces, not the Prometheus meters above. Best-effort: span bookkeeping must+ never break execution, and set_attribute is a no-op when the span isn't recording (e.g. tracing+ disabled, or during workflow replay). None-valued attributes are skipped.+ """+ try:+ span = trace.get_current_span()+ if not span.is_recording():+ return+ for key, value in attributes.items():+ if value is not None:+ span.set_attribute(key, value)+ except Exception:+ pass++class BatchExportsMetricsInterceptor(Interceptor):- """Interceptor to emit Prometheus metrics for batch exports."""+ """Interceptor for batch export observability.++ Emits Prometheus metrics (execution latency, attempt counters) and enriches the active OTel+ trace span with batch export metadata (id, destination, interval, model) via+ _tag_span_with_batch_export_context.+ """task_queue = (settings.BATCH_EXPORTS_TASK_QUEUE, settings.SYNC_BATCH_EXPORTS_TASK_QUEUE)@@ -148,6 +173,21 @@ class _BatchExportsMetricsActivityInboundInterceptor(ActivityInboundInterceptor)data_interval_end = Noneinterval = None+ # Enrich the trace span with batch export identity, mirroring the metric attributes below.+ details = getattr(input.args[0], "batch_export", input.args[0])+ workflow_type = activity.info().workflow_type+ model = getattr(details, "batch_export_model", None)+ _tag_span_with_batch_export_context(+ {+ "batch_export.id": getattr(details, "batch_export_id", None),+ "batch_export.destination": workflow_type.removesuffix("-export") if workflow_type else None,+ "batch_export.interval": interval,+ "batch_export.model": getattr(model, "name", None),+ "batch_export.run_id": getattr(details, "run_id", None),+ "attempt": activity.info().attempt,+ }+ )+if not interval:LOGGER.error("Failed to parse interval bounds ('%s', '%s'), will not record latency for '%s'",@@ -200,6 +240,16 @@ class _BatchExportsMetricsWorkflowInterceptor(WorkflowInboundInterceptor):interval = input.args[0].interval.replace(" ", "_")histogram_attributes: Attributes = {"interval": interval}+ model = getattr(input.args[0], "batch_export_model", None)+ _tag_span_with_batch_export_context(+ {+ "batch_export.id": getattr(input.args[0], "batch_export_id", None),+ "batch_export.destination": workflow_type.removesuffix("-export"),+ "batch_export.interval": interval,+ "batch_export.model": getattr(model, "name", None),+ }+ )+async with SLAWaiter(batch_export_id=workflow_info.workflow_id, sla=get_sla_from_interval(interval)):with ExecutionTimeRecorder("batch_exports_workflow_interval_execution_latency",