: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): tag django and temporal spans with team_id (#63449)
Robbie9d3f121b462a
diff --git a/posthog/api/routing.py b/posthog/api/routing.pyindex 9ef81e94114f..42048589be08 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -5,6 +5,7 @@ from uuid import UUIDfrom django.db.models.query import QuerySet+from opentelemetry import tracefrom rest_framework.exceptions import AuthenticationFailed, NotFound, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.viewsets import GenericViewSet@@ -247,6 +248,12 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):# touches a scoped model will get TeamScopeError, which is the# correct fail-closed behavior.return+ # Tag the request (root) span as soon as the team is resolved, so the whole+ # trace is attributable to a team. DjangoInstrumentor's request span is the+ # current span here (no manual span has opened yet); a no-op when tracing is off.+ request_span = trace.get_current_span()+ if request_span.is_recording():+ request_span.set_attribute("team_id", team_id)# Compute canonical team_id. self.team is a @cached_property# (line ~297) usually loaded by the permission checks above, so# this is free. Reading via __dict__ rather than attribute accessdiff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.pyindex 83268c2b0a77..297706adab28 100644--- a/posthog/api/test/test_routing.py+++ b/posthog/api/test/test_routing.py@@ -12,6 +12,9 @@ from django.test import override_settingsfrom django.urls import include, pathfrom django.utils import timezone+from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom rest_framework import viewsetsfrom rest_framework.decorators import actionfrom rest_framework.response import Response@@ -75,6 +78,37 @@ urlpatterns = []+@override_settings(ROOT_URLCONF=__name__)+class TestTeamAndOrgViewSetMixinSpanTagging(APIBaseTest):+ """The request (root) span should be tagged with team_id for team/project views."""++ def _recording_tracer(self):+ exporter = InMemorySpanExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ return provider.get_tracer("test"), exporter++ def _root_span(self, exporter):+ spans = [s for s in exporter.get_finished_spans() if s.name == "test-request-root"]+ self.assertEqual(len(spans), 1)+ return spans[0]++ def test_team_view_tags_request_span_with_team_id(self):+ tracer, exporter = self._recording_tracer()+ with tracer.start_as_current_span("test-request-root"):+ response = self.client.get(f"/api/environments/{self.team.id}/foos/")+ self.assertEqual(response.status_code, 200)+ self.assertEqual(self._root_span(exporter).attributes["team_id"], self.team.id)++ def test_organization_view_does_not_tag_team_id(self):+ # Org-scoped views have no single team, so the stamp must not fire.+ tracer, exporter = self._recording_tracer()+ with tracer.start_as_current_span("test-request-root"):+ response = self.client.get(f"/api/organizations/{self.organization.id}/foos/")+ self.assertEqual(response.status_code, 200)+ self.assertNotIn("team_id", self._root_span(exporter).attributes or {})++@override_settings(ROOT_URLCONF=__name__) # Use `urlpatterns` from this file and not from `posthog.urls`class TestTeamAndOrgViewSetMixin(APIBaseTest):test_annotation: Annotationdiff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex e33a80e3f394..c258d9f24dce 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -2,6 +2,7 @@ from dataclasses import is_dataclassfrom typing import Any, Optionalimport temporalio.exceptions+from opentelemetry import tracefrom posthoganalytics import api_key, capture_exceptionfrom temporalio import activity, workflowfrom temporalio.worker import (@@ -19,6 +20,26 @@ from posthog.temporal.common.logger import get_write_only_loggerlogger = get_write_only_logger()+def _tag_team_id_on_current_span(input: ExecuteActivityInput | ExecuteWorkflowInput) -> None:+ """Tag the active span (the Temporal RunActivity/RunWorkflow span, when OTel tracing is+ enabled on the worker) with team_id read from the activity/workflow input.++ team_id is named consistently across PostHog's Temporal input dataclasses, so a reflective+ read covers nearly all of them without per-workflow opt-in. Best-effort: span bookkeeping+ must never break execution, and set_attribute is a non-IO no-op when the span isn't recording."""+ try:+ if not (len(input.args) == 1 and is_dataclass(input.args[0])):+ return+ team_id = getattr(input.args[0], "team_id", None)+ 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++async def _add_inputs_to_capture_kwargs(capture_kwargs: dict[str, Any],input: ExecuteActivityInput | ExecuteWorkflowInput,@@ -40,6 +61,7 @@ async def _add_inputs_to_capture_kwargs(class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):async def execute_activity(self, input: ExecuteActivityInput) -> Any:+ _tag_team_id_on_current_span(input)try:return await super().execute_activity(input)except Exception as e:@@ -69,6 +91,7 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):class _PostHogClientWorkflowInterceptor(WorkflowInboundInterceptor):async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any:+ _tag_team_id_on_current_span(input)try:return await super().execute_workflow(input)except Exception as e:@@ -100,7 +123,8 @@ class _PostHogClientWorkflowInterceptor(WorkflowInboundInterceptor):class PostHogClientInterceptor(Interceptor):- """PostHog Interceptor class which will report workflow & activity exceptions to PostHog"""+ """PostHog Interceptor: reports workflow & activity exceptions to PostHog and tags the+ Temporal span of each execution with team_id (read reflectively from the input)."""task_queue = ALL_TASK_QUEUESdiff --git a/posthog/temporal/tests/common/test_posthog_client_team_id.py b/posthog/temporal/tests/common/test_posthog_client_team_id.pynew file mode 100644index 000000000000..67e51dac3af0--- /dev/null+++ b/posthog/temporal/tests/common/test_posthog_client_team_id.py@@ -0,0 +1,76 @@+from dataclasses import dataclass++import pytest+from unittest.mock import AsyncMock, MagicMock++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 temporalio.worker import ExecuteActivityInput, ExecuteWorkflowInput++from posthog.temporal.common.posthog_client import (+ _PostHogClientActivityInboundInterceptor,+ _PostHogClientWorkflowInterceptor,+)+++@dataclass+class _InputWithTeam:+ team_id: int+++@dataclass+class _InputWithoutTeam:+ something_else: str+++def _provider_with_exporter() -> tuple[TracerProvider, InMemorySpanExporter]:+ exporter = InMemorySpanExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ return provider, exporter+++def _span_named(exporter: InMemorySpanExporter, name: str):+ spans = [s for s in exporter.get_finished_spans() if s.name == name]+ assert len(spans) == 1+ return spans[0]+++ "interceptor_cls,input_spec,execute_method,span_name",+ [+ (_PostHogClientActivityInboundInterceptor, ExecuteActivityInput, "execute_activity", "RunActivity"),+ (_PostHogClientWorkflowInterceptor, ExecuteWorkflowInput, "execute_workflow", "RunWorkflow"),+ ],+)+class TestPostHogClientTeamIdTagging:+ async def test_tags_team_id_on_current_span(self, interceptor_cls, input_spec, execute_method, span_name):+ provider, exporter = _provider_with_exporter()+ next_interceptor = AsyncMock()+ getattr(next_interceptor, execute_method).return_value = "result"+ interceptor = interceptor_cls(next_interceptor)++ mock_input = MagicMock(spec=input_spec)+ mock_input.args = [_InputWithTeam(team_id=4242)]++ with provider.get_tracer("test").start_as_current_span(span_name):+ result = await getattr(interceptor, execute_method)(mock_input)++ assert result == "result"+ assert _span_named(exporter, span_name).attributes["team_id"] == 4242++ async def test_no_team_id_when_input_lacks_field(self, interceptor_cls, input_spec, execute_method, span_name):+ provider, exporter = _provider_with_exporter()+ next_interceptor = AsyncMock()+ getattr(next_interceptor, execute_method).return_value = "result"+ interceptor = interceptor_cls(next_interceptor)++ mock_input = MagicMock(spec=input_spec)+ mock_input.args = [_InputWithoutTeam(something_else="x")]++ with provider.get_tracer("test").start_as_current_span(span_name):+ await getattr(interceptor, execute_method)(mock_input)++ assert "team_id" not in (_span_named(exporter, span_name).attributes or {})