: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(tracing): report usage events for histogram, aggregate, and trace endpoints (#71492)
Jon McCallum59d30417f01f
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 6cea0a837b8f..8d073b184b0e 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -39,6 +39,7 @@ from posthog.api.mixins import PydanticModelMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.event_usage import report_user_action+from posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionModefrom ..facade.api import (@@ -211,10 +212,6 @@ class _TracingTimeseriesQueryBodySerializer(serializers.Serializer):)-class _TracingTimeseriesRequestSerializer(serializers.Serializer):- query = _TracingTimeseriesQueryBodySerializer(help_text="The sparkline / duration-histogram query to execute.")--class _TracingDurationHistogramQueryBodySerializer(_TracingTimeseriesQueryBodySerializer):rootSpans = serializers.BooleanField(required=False,@@ -644,6 +641,13 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return filter_groupreturn {"type": "AND", "values": []}+ def _report_usage(self, request: Request, event: str, properties: dict) -> None:+ # Usage telemetry must never turn a successful read into a 5xx, so swallow and record any failure.+ try:+ report_user_action(request.user, event, properties, team=self.team, request=request)+ except Exception as e:+ capture_exception(e)+@extend_schema(parameters=[_TracingServiceNamesQuerySerializer])@action(detail=False, methods=["GET"], url_path="service-names", required_scopes=["tracing:read"])def service_names(self, request: Request, *args, **kwargs) -> Response:@@ -944,13 +948,26 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)except (ValidationError, ValueError, ParseError):filter_group = None+ root_spans = query_data.get("rootSpans", True)response = run_duration_histogram_query(team=self.team,date_range=date_range,service_names=query_data.get("serviceNames", None),status_codes=query_data.get("statusCodes", None),filter_group=filter_group,- root_spans=query_data.get("rootSpans", True),+ root_spans=root_spans,+ )++ self._report_usage(+ request,+ "tracing duration histogram queried",+ {+ "buckets_count": len(response.results),+ "root_spans": root_spans,+ "has_filter_group": bool(query_data.get("filterGroup")),+ "service_names_count": len(query_data.get("serviceNames") or []),+ "status_codes_count": len(query_data.get("statusCodes") or []),+ },)return Response({"results": response.results}, status=status.HTTP_200_OK)@@ -987,6 +1004,17 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)service_names=query_data.get("serviceNames", None),)+ self._report_usage(+ request,+ "tracing aggregation queried",+ {+ "results_count": len(response.results),+ "has_compare": bool(query_data.get("compareFilter")),+ "has_filter_group": bool(query_data.get("filterGroup")),+ "service_names_count": len(query_data.get("serviceNames") or []),+ },+ )+return Response({"results": [row.model_dump() for row in response.results],@@ -1188,6 +1216,17 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)# spans whose children fall on a later page — an accepted bound, same as the prior 2000 cap.annotate_self_time(results)+ self._report_usage(+ request,+ "tracing trace fetched",+ {+ "spans_count": len(results),+ "has_more": has_more,+ "is_paginated": offset > 0,+ "has_filter_group": bool(query_data.get("filterGroup")),+ },+ )+return Response({"results": results,diff --git a/products/tracing/backend/tests/test_duration_histogram.py b/products/tracing/backend/tests/test_duration_histogram.pyindex e2ca8e15a196..2fec8b985eff 100644--- a/products/tracing/backend/tests/test_duration_histogram.py+++ b/products/tracing/backend/tests/test_duration_histogram.py@@ -1,5 +1,7 @@import datetime as dt+from unittest.mock import patch+from posthog.clickhouse.client import sync_executefrom products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase@@ -76,6 +78,15 @@ class TestTraceSpansDurationHistogram(_TraceSpansTestBase):rows = {(row["bucket_ns"], row["service"]): row["count"] for row in self._histogram(service_names=["web"])}self.assertEqual(rows, {(1 * MS, "web"): 1, (2 * MS, "web"): 2})+ def test_usage_telemetry_failure_does_not_break_the_read(self):+ # Usage reporting runs after the query succeeds; if it raises, the 200 must still be returned.+ with patch(+ "products.tracing.backend.presentation.views.report_user_action",+ side_effect=Exception("analytics unavailable"),+ ):+ rows = {(row["bucket_ns"], row["service"]): row["count"] for row in self._histogram()}+ self.assertEqual(rows, {(1 * MS, "web"): 1, (2 * MS, "web"): 2, (500 * MS, "api"): 1})+def test_root_spans_false_counts_child_spans_for_operation_scope(self):# The operation detail page scopes by span name and needs child spans counted: the 5s# 'db query' child (invisible to the root-only histogram above) must appear.