: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(observability): trace celery tasks and tag spans with team_id (#63450)
Robbie2aab4bcf602c
diff --git a/posthog/celery.py b/posthog/celery.pyindex f77fe5e60d39..8cdc55719f55 100644--- a/posthog/celery.py+++ b/posthog/celery.py@@ -19,6 +19,7 @@ from celery.signals import ()from django_structlog.celery import signalsfrom django_structlog.celery.steps import DjangoStructLogInitStep+from opentelemetry import tracefrom prometheus_client import Counter, Histogram, start_http_server# When PROMETHEUS_MULTIPROC_DIR is set (by bin/docker-worker-celery),@@ -161,12 +162,45 @@ def on_celeryd_init(**kwargs) -> None:logger.info("prometheus_multiproc_cleanup_done", removed=removed)+def _tag_celery_span_with_team_id(task_kwargs: dict | None) -> None:+ """Tag the active Celery task span (created by CeleryInstrumentor) with team_id, read+ best-effort from the task's keyword arguments. Coverage is partial by design: only tasks+ invoked with an explicit ``team_id=`` keyword are tagged. No-op when the span isn't recording."""+ try:+ team_id = (task_kwargs or {}).get("team_id")+ if not isinstance(team_id, int) or isinstance(team_id, bool):+ return+ span = trace.get_current_span()+ if span.is_recording():+ span.set_attribute("team_id", team_id)+ except Exception:+ pass+++def _celery_team_id_prerun_receiver(task_id=None, task=None, args=None, kwargs=None, **_) -> None:+ _tag_celery_span_with_team_id(kwargs)++@worker_process_init.connectdef on_worker_start(**kwargs) -> None:from posthoganalytics import setup+ from posthog.otel_instrumentation import (+ initialize_otel, # noqa: PLC0415 — keep the OTel stack off the celery import path; only the worker child loads it+ )+setup() # makes sure things like exception autocapture are initialised+ # Initialize tracing in the forked worker child (not at import / pre-fork): the+ # BatchSpanProcessor's export thread and gRPC channel do not survive fork(), so the+ # provider must be created per child. This also enables CeleryInstrumentor, which starts+ # a span per task. No-op when OTEL_SDK_DISABLED is set.+ initialize_otel()+ # Connect the team_id tagger AFTER initialize_otel (which instruments Celery) so Celery+ # dispatches it after CeleryInstrumentor's own prerun receiver — the task span is the+ # active span by then. Degrades to a no-op if that ordering ever changes.+ task_prerun.connect(_celery_team_id_prerun_receiver, weak=False)+port = int(os.getenv("CELERY_METRICS_PORT", "8001"))try:if _PROMETHEUS_MULTIPROC_DIR:diff --git a/posthog/otel_instrumentation.py b/posthog/otel_instrumentation.pyindex e875af37c023..913ec314fa64 100644--- a/posthog/otel_instrumentation.py+++ b/posthog/otel_instrumentation.py@@ -7,6 +7,7 @@ from opentelemetry import tracefrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporterfrom opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentorfrom opentelemetry.instrumentation.aiokafka import AIOKafkaInstrumentor+from opentelemetry.instrumentation.celery import CeleryInstrumentorfrom opentelemetry.instrumentation.django import DjangoInstrumentorfrom opentelemetry.instrumentation.kafka import KafkaInstrumentorfrom opentelemetry.instrumentation.psycopg import PsycopgInstrumentor@@ -89,6 +90,7 @@ def initialize_otel():)instrument_django(provider)+ instrument_celery(provider)instrument_redis(provider)instrument_psycopg(provider)instrument_kafka(provider)@@ -119,6 +121,14 @@ def instrument_django(provider: trace.TracerProvider):logger.exception("otel_instrumentation_attempt", instrumentor="DjangoInstrumentor", status="error", exc_info=e)+def instrument_celery(provider: trace.TracerProvider):+ try:+ CeleryInstrumentor().instrument(tracer_provider=provider)+ logger.info("otel_instrumentation_attempt", instrumentor="CeleryInstrumentor", status="success")+ except Exception as e:+ logger.exception("otel_instrumentation_attempt", instrumentor="CeleryInstrumentor", status="error", exc_info=e)++def instrument_redis(provider: trace.TracerProvider):try:RedisInstrumentor().instrument(tracer_provider=provider)diff --git a/posthog/test/test_celery_span_team_id.py b/posthog/test/test_celery_span_team_id.pynew file mode 100644index 000000000000..264ae3473803--- /dev/null+++ b/posthog/test/test_celery_span_team_id.py@@ -0,0 +1,39 @@+import pytest++from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter++from posthog.celery import _tag_celery_span_with_team_id+++def _provider_with_exporter():+ exporter = InMemorySpanExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ return provider, exporter+++ "task_kwargs,expected",+ [+ ({"team_id": 4242}, 4242),+ ({"team_id": 1, "other": "x"}, 1),+ ({"other": "x"}, None),+ ({"team_id": "4242"}, None),+ ({"team_id": True}, None),+ (None, None),+ ],+)+def test_tag_celery_span_with_team_id(task_kwargs, expected):+ provider, exporter = _provider_with_exporter()+ with provider.get_tracer("test").start_as_current_span("run/some_task"):+ _tag_celery_span_with_team_id(task_kwargs)++ spans = [s for s in exporter.get_finished_spans() if s.name == "run/some_task"]+ assert len(spans) == 1+ attributes = spans[0].attributes or {}+ if expected is None:+ assert "team_id" not in attributes+ else:+ assert attributes["team_id"] == expecteddiff --git a/posthog/test/test_otel_instrumentation.py b/posthog/test/test_otel_instrumentation.pyindex 737fa255e639..f6ea17f8c038 100644--- a/posthog/test/test_otel_instrumentation.py+++ b/posthog/test/test_otel_instrumentation.py@@ -38,6 +38,7 @@ class TestOtelInstrumentation(BaseTest):super().tearDown()+ @mock.patch("posthog.otel_instrumentation.CeleryInstrumentor")@mock.patch("posthog.otel_instrumentation.AIOKafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.KafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.PsycopgInstrumentor")@@ -71,6 +72,7 @@ class TestOtelInstrumentation(BaseTest):mock_psycopg_instrumentor_cls,mock_kafka_instrumentor_cls,mock_aio_kafka_instrumentor_cls,+ mock_celery_instrumentor_cls,):# Arrangemock_resource_instance = mock.Mock()@@ -115,6 +117,12 @@ class TestOtelInstrumentation(BaseTest):mock_django_instrumentor_cls.assert_called_once_with()mock_django_instrumentor_instance.instrument.assert_called_once()+ # Assert CeleryInstrumentor call+ mock_celery_instrumentor_cls.assert_called_once_with()+ mock_celery_instrumentor_cls.return_value.instrument.assert_called_once_with(+ tracer_provider=mock_provider_instance+ )+instrument_call_args = mock_django_instrumentor_instance.instrument.call_argsself.assertEqual(instrument_call_args[1]["tracer_provider"], mock_provider_instance)self.assertEqual(instrument_call_args[1]["request_hook"], _otel_django_request_hook)@@ -166,6 +174,7 @@ class TestOtelInstrumentation(BaseTest):self.assertEqual(django_otel_lib_logger.level, logging.DEBUG) # Always set to DEBUGself.assertTrue(django_otel_lib_logger.propagate)+ @mock.patch("posthog.otel_instrumentation.CeleryInstrumentor")@mock.patch("posthog.otel_instrumentation.AIOKafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.KafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.PsycopgInstrumentor")@@ -181,12 +190,14 @@ class TestOtelInstrumentation(BaseTest):mock_psycopg_instrumentor_cls,mock_kafka_instrumentor_cls,mock_aio_kafka_instrumentor_cls,+ mock_celery_instrumentor_cls,):# Actinitialize_otel()# Assertmock_django_instrumentor_cls.return_value.instrument.assert_not_called()+ mock_celery_instrumentor_cls.return_value.instrument.assert_not_called()mock_redis_instrumentor_cls.return_value.instrument.assert_not_called()mock_psycopg_instrumentor_cls.return_value.instrument.assert_not_called()mock_kafka_instrumentor_cls.return_value.instrument.assert_not_called()@@ -251,6 +262,7 @@ class TestOtelInstrumentation(BaseTest):mock_span.set_attribute.assert_not_called()+ @mock.patch("posthog.otel_instrumentation.CeleryInstrumentor")@mock.patch("posthog.otel_instrumentation.AIOKafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.KafkaInstrumentor")@mock.patch("posthog.otel_instrumentation.PsycopgInstrumentor")@@ -286,6 +298,7 @@ class TestOtelInstrumentation(BaseTest):mock_psycopg_instrumentor_cls,mock_kafka_instrumentor_cls,mock_aio_kafka_instrumentor_cls,+ mock_celery_instrumentor_cls,):# Arrangemock_resource_instance = mock.Mock()diff --git a/pyproject.toml b/pyproject.tomlindex 84517c6d434a..e04176a8d670 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -164,6 +164,7 @@ dependencies = ["opentelemetry-instrumentation-aiokafka==0.54b1","opentelemetry-instrumentation-aiohttp-client==0.54b1","opentelemetry-instrumentation-asgi==0.54b1",+ "opentelemetry-instrumentation-celery==0.54b1","opentelemetry-instrumentation-django==0.54b1","opentelemetry-instrumentation-kafka-python==0.54b1","opentelemetry-instrumentation-psycopg==0.54b1",diff --git a/uv.lock b/uv.lockindex ffd734acf7bd..eda4314e0597 100644--- a/uv.lock+++ b/uv.lock@@ -4887,6 +4887,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/20/24/7a6f0ae79cae49927f528ecee2db55a5bddd87b550e310ce03451eae7491/opentelemetry_instrumentation_asgi-0.54b1-py3-none-any.whl", hash = "sha256:84674e822b89af563b283a5283c2ebb9ed585d1b80a1c27fb3ac20b562e9f9fc", size = 16338, upload-time = "2025-05-16T19:02:22.808Z" },]+[[package]]+name = "opentelemetry-instrumentation-celery"+version = "0.54b1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "opentelemetry-api" },+ { name = "opentelemetry-instrumentation" },+ { name = "opentelemetry-semantic-conventions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/7c/71/4ac353874e0f7ca93591e1a74b7a290dec2027733bbb31bd76da3a74f97f/opentelemetry_instrumentation_celery-0.54b1.tar.gz", hash = "sha256:f2bd019afe9286214083ae2db95ed24adf9a0aa2e943177462d64ceb8380d78e", size = 14778, upload-time = "2025-05-16T19:03:37.376Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2f/be/90e2b7d26915639cfcdf6e200b309c9d64027ff752c56145bc149cd67d68/opentelemetry_instrumentation_celery-0.54b1-py3-none-any.whl", hash = "sha256:892ec6bf829a0d60cf3bffd1a8bb6fd8055f1194167b4e132e33321de8e05c24", size = 13809, upload-time = "2025-05-16T19:02:33.046Z" },+]+[[package]]name = "opentelemetry-instrumentation-dbapi"version = "0.54b1"@@ -5534,6 +5548,7 @@ dependencies = [{ name = "opentelemetry-instrumentation-aiohttp-client" },{ name = "opentelemetry-instrumentation-aiokafka" },{ name = "opentelemetry-instrumentation-asgi" },+ { name = "opentelemetry-instrumentation-celery" },{ name = "opentelemetry-instrumentation-django" },{ name = "opentelemetry-instrumentation-kafka-python" },{ name = "opentelemetry-instrumentation-psycopg" },@@ -5804,6 +5819,7 @@ requires-dist = [{ name = "opentelemetry-instrumentation-aiohttp-client", specifier = "==0.54b1" },{ name = "opentelemetry-instrumentation-aiokafka", specifier = "==0.54b1" },{ name = "opentelemetry-instrumentation-asgi", specifier = "==0.54b1" },+ { name = "opentelemetry-instrumentation-celery", specifier = "==0.54b1" },{ name = "opentelemetry-instrumentation-django", specifier = "==0.54b1" },{ name = "opentelemetry-instrumentation-kafka-python", specifier = "==0.54b1" },{ name = "opentelemetry-instrumentation-psycopg", specifier = "==0.54b1" },