: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(signals): add APM spans to inbox load endpoints (#65502)
Paul D'Ambrae86fa8547c60
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex a322a8f4bd1f..1b428ba788a4 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -4,6 +4,8 @@ from collections.abc import Mappingfrom typing import castfrom asgiref.sync import async_to_sync+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCodefrom rest_framework import serializersfrom posthog.models import User@@ -21,6 +23,7 @@ from .models import (from .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_memberslogger = logging.getLogger(__name__)+tracer = trace.get_tracer(__name__)DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1@@ -61,6 +64,9 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):ext_source_type, schema_name = mappingreturn self._get_data_import_status(obj.team_id, ext_source_type, schema_name)+ # Per-row Temporal RPC: serializing N source configs issues N of these on inbox load.+ # The span surfaces that cost so the N+1 is visible per request in APM.+ @tracer.start_as_current_span("signals.source_config.session_analysis_status")def _get_session_analysis_status(self, team_id: int) -> str | None:""" "running" iff any `summarize-session` workflow for this team is currently executing."""query = f'PostHogTeamId = {team_id} AND WorkflowType = "summarize-session" AND ExecutionStatus = "Running"'@@ -76,6 +82,11 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):if async_to_sync(has_running)():return "running"except Exception as e:+ # The except swallows the error, so OTel won't auto-record it on the span — mark it+ # failed explicitly, else an unreachable Temporal looks like a successful no-op in APM.+ span = trace.get_current_span()+ span.record_exception(e)+ span.set_status(Status(StatusCode.ERROR))logger.warning("Failed to list session summarization workflows: %s", e)return Nonediff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex b335c27cfbe8..84d53342140a 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -212,6 +212,13 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "task"queryset = SignalSourceConfig.objects.all().order_by("-updated_at")+ @tracer.start_as_current_span("signals.source_configs.list")+ def list(self, request, *args, **kwargs):+ # This list is fetched on inbox load. The default serializer resolves a per-row `status`,+ # which for session-analysis rows makes a synchronous Temporal RPC — a potential N+1. The+ # span lets us see how much of the inbox load this endpoint accounts for.+ return super().list(request, *args, **kwargs)+def _is_scout_source(self, source_product: str | None, source_type: str | None) -> bool:return (source_product == SignalSourceConfig.SourceProduct.SIGNALS_SCOUT@@ -1067,14 +1074,24 @@ class SignalReportViewSet(),],)+ @tracer.start_as_current_span("signals.reports.list")def list(self, request, *args, **kwargs):- queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)- reports = list(page if page is not None else queryset)+ # The reports list is the primary inbox-load endpoint. Each phase gets its own child span+ # so a slow load can be attributed to Postgres (queryset annotations), ClickHouse (source+ # products), the task facade (PR urls), or serialization, rather than one opaque request.+ with tracer.start_as_current_span("signals.reports.list.queryset"):+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)+ reports = list(page if page is not None else queryset)report_ids = [str(r.id) for r in reports]- source_products_map = fetch_source_products_for_reports(self.team, report_ids) if report_ids else {}- implementation_pr_url_map = fetch_implementation_pr_urls_for_reports(report_ids)+ trace.get_current_span().set_attribute("signals.reports.list.count", len(report_ids))++ with tracer.start_as_current_span("signals.reports.list.fetch_source_products"):+ source_products_map = fetch_source_products_for_reports(self.team, report_ids) if report_ids else {}++ with tracer.start_as_current_span("signals.reports.list.fetch_implementation_pr_urls"):+ implementation_pr_url_map = fetch_implementation_pr_urls_for_reports(report_ids)context = {**self.get_serializer_context(),@@ -1083,9 +1100,12 @@ class SignalReportViewSet(}serializer = self.get_serializer(reports, many=True, context=context)+ with tracer.start_as_current_span("signals.reports.list.serialize"):+ data = serializer.data+if page is not None:- return self.get_paginated_response(serializer.data)- return Response(serializer.data)+ return self.get_paginated_response(data)+ return Response(data)@extend_schema(exclude=True)@action(detail=False, methods=["get"], url_path="available_reviewers", required_scopes=["task:read"])