: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(experiments): add tracing spans to the list endpoint (#64502)
Anders22e44969eb2c
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex d7af82c06b2b..e9eac97ba44b 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -9,6 +9,7 @@ ViewSet remains in experiments.py.from typing import Anyfrom drf_spectacular.utils import extend_schema_field+from opentelemetry import tracefrom pydantic import RootModel as PydanticRootModelfrom rest_framework import serializersfrom rest_framework.exceptions import ValidationError@@ -40,6 +41,8 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializerfrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer+tracer = trace.get_tracer(__name__)+class _ExperimentApiMetricsList(PydanticRootModel):"""List wrapper for OpenAPI schema generation — the field stores an array of metrics."""@@ -115,8 +118,10 @@ class ExperimentListSerializer(serializers.ListSerializer):serializer context, so a 100-experiment page does one action query instead of hundreds."""+ @tracer.start_as_current_span("ExperimentListSerializer.to_representation")def to_representation(self, data):instances = list(data)+ trace.get_current_span().set_attribute("experiment_count", len(instances))metric_queries: list[dict[str, Any] | None] = []team: Team | None = None@@ -345,6 +350,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSedef get_feature_flag(self, obj):return MinimalFeatureFlagSerializer(obj.feature_flag).data if obj.feature_flag else None+ @tracer.start_as_current_span("ExperimentSerializer.to_representation")def to_representation(self, instance):data = super().to_representation(instance)# Normalize query date ranges to the experiment's current range@@ -376,23 +382,26 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe# Update date ranges in saved metrics# Note: Action name refresh is handled by ExperimentToSavedMetricSerializer.to_representation- for saved_metric in data.get("saved_metrics", []):- if saved_metric.get("query"):- if saved_metric["query"].get("count_query", {}).get("dateRange"):- saved_metric["query"]["count_query"]["dateRange"] = new_date_range- if saved_metric["query"].get("funnels_query", {}).get("dateRange"):- saved_metric["query"]["funnels_query"]["dateRange"] = new_date_range-- # Add fingerprint to saved metric returned from API- # so that frontend knows what timeseries records to query- saved_metric["query"]["fingerprint"] = compute_metric_fingerprint(- saved_metric["query"],- instance.start_date,- get_experiment_stats_method(instance),- instance.exposure_criteria,- only_count_matured_users=instance.only_count_matured_users,- excluded_variants=(instance.parameters or {}).get("excluded_variants"),- )+ saved_metrics = data.get("saved_metrics", [])+ with tracer.start_as_current_span("ExperimentSerializer.saved_metric_fingerprints") as span:+ span.set_attribute("saved_metric_count", len(saved_metrics))+ for saved_metric in saved_metrics:+ if saved_metric.get("query"):+ if saved_metric["query"].get("count_query", {}).get("dateRange"):+ saved_metric["query"]["count_query"]["dateRange"] = new_date_range+ if saved_metric["query"].get("funnels_query", {}).get("dateRange"):+ saved_metric["query"]["funnels_query"]["dateRange"] = new_date_range++ # Add fingerprint to saved metric returned from API+ # so that frontend knows what timeseries records to query+ saved_metric["query"]["fingerprint"] = compute_metric_fingerprint(+ saved_metric["query"],+ instance.start_date,+ get_experiment_stats_method(instance),+ instance.exposure_criteria,+ only_count_matured_users=instance.only_count_matured_users,+ excluded_variants=(instance.parameters or {}).get("excluded_variants"),+ )return datadiff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex fccff7cad2e3..14398f233c73 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -18,6 +18,7 @@ from django.utils.text import slugifyimport posthoganalyticsfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view+from opentelemetry import tracefrom rest_framework import viewsetsfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Request@@ -86,6 +87,8 @@ from products.surveys.backend.models import Surveyfrom ee.clickhouse.queries.experiments.utils import requires_flag_warning+tracer = trace.get_tracer(__name__)+PROMPT_EXPERIMENTS_FEATURE_FLAG = "experiments-llm-prompts"@@ -276,6 +279,11 @@ class EnterpriseExperimentsViewSet()ordering = "-created_at"+ @tracer.start_as_current_span("ExperimentViewSet.list")+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return super().list(request, *args, **kwargs)++ @tracer.start_as_current_span("ExperimentViewSet.safely_get_queryset")def safely_get_queryset(self, queryset) -> QuerySet:request = getattr(self, "request", None)service = ExperimentService(team=self.team, user=getattr(request, "user", None))