: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): correlate query spans with client query ids (#104595)
Paul D'Ambra99835e72a1c6
diff --git a/docs/published/handbook/engineering/conventions/backend-coding.md b/docs/published/handbook/engineering/conventions/backend-coding.mdindex 4ec34546b1ac..95eb48911f9b 100644--- a/docs/published/handbook/engineering/conventions/backend-coding.md+++ b/docs/published/handbook/engineering/conventions/backend-coding.md@@ -3,6 +3,14 @@ title: Backend coding conventionssidebar: Handbook---+#### Query trace correlation++The `query.client_query_id` attribute on `posthog.query.process_query_model` matches the browser `query completed` event's `queryId` and the API response event's `client_query_id`.+Only UUID-shaped IDs are added to spans; other client IDs remain valid API inputs.+A matching ID links a request to its processing span. It does not prove that the request delayed page rendering.+An asynchronous query can continue in a separate trace after the submission request ends.+Check request timing against browser performance metrics, and inspect child spans and self time before choosing a performance fix.+#### LoggingAs a general rule, we should have logs for every expected and unexpected actions of the application, using the appropriate _log level_.diff --git a/posthog/api/query.py b/posthog/api/query.pyindex decbe3d48e0a..8717c86528f4 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -151,6 +151,12 @@ def _mark_explicit_date_boundaries(query: BaseModel) -> None:date_range.explicitDate = True+def set_query_id_on_span(span: trace.Span, query_id: str) -> None:+ # Client IDs are free text in the API, so only export opaque UUIDs to traces.+ if re.fullmatch(r"[0-9a-fA-F]{32}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", query_id):+ span.set_attribute("query.client_query_id", query_id)++def _process_query_request(request_data: QueryRequest, team, client_query_id: str | None = None, user=None) -> tuple[BaseModel, str, ExecutionMode]:@@ -321,6 +327,7 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)process_span.set_attribute("team_id", self.team.pk)process_span.set_attribute("query.kind", getattr(query, "kind", "Other"))process_span.set_attribute("query.is_query_service", is_query_service)+ set_query_id_on_span(process_span, client_query_id)if limit_context is not None:process_span.set_attribute("query.limit_context", limit_context.value)result = process_query_model(diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex fab636853dad..101c540025b8 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -14,7 +14,9 @@ from unittest import mockfrom unittest.mock import patchfrom django.conf import settings+from django.test import SimpleTestCase+from opentelemetry.sdk.trace import ReadableSpan, TracerProviderfrom parameterized import parameterizedfrom rest_framework import status@@ -40,6 +42,7 @@ from posthog.api.query import (CONCURRENCY_LIMIT_USER_MESSAGE,MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE,MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE,+ set_query_id_on_span,)from posthog.api.services.query import process_query_dict, process_query_modelfrom posthog.clickhouse.client import sync_execute@@ -62,6 +65,25 @@ from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_Sfrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType+class TestQueryTraceCorrelation(SimpleTestCase):+ @parameterized.expand(+ [+ ("01234567-89ab-4def-8123-456789abcdef", True),+ ("0123456789ab4def8123456789abcdef", True),+ ("[email protected]", False),+ ("", False),+ ("01234567-89ab-4def-8123-456789abcdef\n", False),+ ]+ )+ def test_query_trace_correlation_excludes_free_text(self, query_id: str, expected: bool) -> None:+ provider = TracerProvider()+ self.addCleanup(provider.shutdown)+ with provider.get_tracer(__name__).start_as_current_span("query") as span:+ set_query_id_on_span(span, query_id)+ assert isinstance(span, ReadableSpan)+ self.assertEqual(dict(span.attributes or {}), {"query.client_query_id": query_id} if expected else {})++class TestQuery(ClickhouseTestMixin, APIBaseTest):ENDPOINT = "query"