: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): make sparkline traces/spans aware (#64900)
Jon McCallum26322a7ad3d1
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 31854d084acf..0cc0df8a84dd 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2987,6 +2987,8 @@ const api = {serviceNames?: string[]statusCodes?: number[]filterGroup?: PropertyGroupFilter+ // true counts root spans only (Traces view); false/absent counts every span (Spans view).+ rootSpans?: boolean},signal?: AbortSignal): Promise<{diff --git a/posthog/clickhouse/traces/spans.py b/posthog/clickhouse/traces/spans.pyindex d80d840c7316..de7f16c71b85 100644--- a/posthog/clickhouse/traces/spans.py+++ b/posthog/clickhouse/traces/spans.py@@ -55,6 +55,10 @@ CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NA`_bytes_compressed` UInt64 CODEC(DoubleDelta, ZSTD(1)),`_record_count` UInt64 CODEC(DoubleDelta, ZSTD(1)),+ -- Powers the Spans-view sparkline (count of spans per minute). The Traces-view sparkline instead+ -- counts distinct traces per minute (uniqExactIf(trace_id, is_root_span = 1)) and currently+ -- raw-scans, since this count() projection can't serve a distinct-trace aggregate; a sibling+ -- uniqExactState(trace_id) projection would let it use a projection too. Tracked as a follow-up.PROJECTION projection_aggregate_counts(SELECTdiff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 33d72508a5b1..07a77ab9c7ae 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -185,9 +185,8 @@ class _TracingQueryRequestSerializer(serializers.Serializer):class _TracingTimeseriesQueryBodySerializer(serializers.Serializer):- # The sparkline and duration-histogram actions read only these filter fields. They deliberately do- # NOT subclass the span-query body: that body's result-shaping fields (orderBy, limit, pagination,- # rootSpans, flatSpans, …) are silently ignored here, so advertising them would mislead callers.+ # Shared filter fields for the timeseries actions; deliberately not a subclass of the span-query+ # body, whose result-shaping fields (orderBy, limit, pagination, flatSpans, …) don't apply here.dateRange = _TracingDateRangeSerializer(required=False,help_text="Date range for the query. Defaults to last hour.",@@ -214,6 +213,21 @@ class _TracingTimeseriesRequestSerializer(serializers.Serializer):query = _TracingTimeseriesQueryBodySerializer(help_text="The sparkline / duration-histogram query to execute.")+class _TracingSparklineQueryBodySerializer(_TracingTimeseriesQueryBodySerializer):+ rootSpans = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "When true, count only root spans (one per trace) so the bars reflect the Traces view. "+ "When false (default), count every matching span — the Spans view's volume."+ ),+ )+++class _TracingSparklineRequestSerializer(serializers.Serializer):+ query = _TracingSparklineQueryBodySerializer(help_text="The sparkline query to execute.")++class _TracingTraceRequestSerializer(serializers.Serializer):dateRange = _TracingDateRangeSerializer(required=False,@@ -830,7 +844,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)status=status.HTTP_200_OK,)- @extend_schema(request=_TracingTimeseriesRequestSerializer)+ @extend_schema(request=_TracingSparklineRequestSerializer)@action(detail=False, methods=["POST"], required_scopes=["tracing:read"])def sparkline(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)@@ -851,6 +865,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)serviceNames=query_data.get("serviceNames", None),statusCodes=query_data.get("statusCodes", None),filterGroup=filter_group,+ rootSpans=query_data.get("rootSpans", False),)runner = TraceSpansSparklineQueryRunner(spans_query, self.team)diff --git a/products/tracing/backend/sparkline_query_runner.py b/products/tracing/backend/sparkline_query_runner.pyindex e99ed5fea135..fcb175f98782 100644--- a/products/tracing/backend/sparkline_query_runner.py+++ b/products/tracing/backend/sparkline_query_runner.py@@ -3,7 +3,7 @@ from zoneinfo import ZoneInfofrom posthog.schema import TraceSpansQueryResponsefrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workload@@ -37,6 +37,17 @@ class TraceSpansSparklineQueryRunner(TraceSpansQueryRunner):return TraceSpansQueryResponse(results=results)def to_query(self) -> ast.SelectQuery:+ # Spans view counts every matching span. Traces view counts distinct traces — the SAME aggregate+ # the count label uses (count_query_runner: uniqExactIf(trace_id, is_root_span = 1)), so the bars+ # tie out to "N traces matching filters" even for malformed traces with 0 or >1 root spans.+ # uniqExactIf can't use the count() projection (it needs trace_id), so traces mode raw-scans until+ # a distinct-trace projection (uniqExactState(trace_id)) is added — see the comment in spans.py.+ event_count_expr: ast.Expr = (+ parse_expr("uniqExactIf(trace_id, is_root_span = 1)")+ if self.query.rootSpans is True+ else parse_expr("count()")+ )+query = parse_select("""SELECT@@ -64,7 +75,7 @@ class TraceSpansSparklineQueryRunner(TraceSpansQueryRunner):SELECTtoStartOfInterval({time_field}, {one_interval_period}) AS time,{breakdown_field},- count() AS event_count+ {event_count} AS event_countFROM posthog.trace_spansWHERE {where} AND time >= {date_from_start_of_interval} AND time <= {date_to}GROUP BY {breakdown_field}, time@@ -81,6 +92,7 @@ class TraceSpansSparklineQueryRunner(TraceSpansQueryRunner):if self.query_date_range.interval_name != "second"else ast.Field(chain=["timestamp"]),"where": self.where(),+ "event_count": event_count_expr,"breakdown_field": ast.Field(chain=["service_name"]),},)diff --git a/products/tracing/backend/tests/test_sparkline.py b/products/tracing/backend/tests/test_sparkline.pyindex 1c42d85899f7..ed2a29464cb5 100644--- a/products/tracing/backend/tests/test_sparkline.py+++ b/products/tracing/backend/tests/test_sparkline.py@@ -24,13 +24,19 @@ class TestTraceSpansSparkline(_TraceSpansTestBase):super().setUpTestData()cls._recreate_trace_spans_tables()+ def setUp(self):+ super().setUp()+ # ClickHouse rows aren't rolled back between tests, and the table is recreated only once per+ # class. Truncate and re-seed the base spans each test so the per-test inserts below+ # (childsvc / multirootsvc) stay isolated instead of leaking into sibling tests' counts.+ sync_execute("TRUNCATE TABLE trace_spans")rows: list[str] = []for i, (timestamp, service, status_code) in enumerate(SPANS):trace_id = _b64(i.to_bytes(16, "big"))span_id = _b64((1000 + i).to_bytes(8, "big"))ts_str = timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")rows.append(- f"('019e8757-0000-0000-0000-{i:012d}', {cls.team.id}, '{trace_id}', '{span_id}', '', "+ f"('019e8757-0000-0000-0000-{i:012d}', {self.team.id}, '{trace_id}', '{span_id}', '', "f"'GET /api', 2, '{ts_str}', '{ts_str}', '{ts_str}', {status_code}, '{service}')")sync_execute(@@ -43,12 +49,15 @@ class TestTraceSpansSparkline(_TraceSpansTestBase):*,service_names: list[str] | None = None,status_codes: list[int] | None = None,+ root_spans: bool | None = None,) -> list[dict]:query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}}if service_names is not None:query["serviceNames"] = service_namesif status_codes is not None:query["statusCodes"] = status_codes+ if root_spans is not None:+ query["rootSpans"] = root_spansresponse = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/sparkline/",{"query": query},@@ -77,3 +86,50 @@ class TestTraceSpansSparkline(_TraceSpansTestBase):def test_service_filter_flows_through(self):rows = self._sparkline(service_names=["web"])self.assertEqual(sum(row["count"] for row in rows), 6)++ def test_root_spans_counts_only_root_spans(self):+ # One trace on its own service: 1 root + 2 children. Spans mode counts all 3 spans; rootSpans+ # (Traces mode) counts only the root — matching the root-match list and the trace count label.+ trace_id = _b64((900).to_bytes(16, "big"))+ root_span_id = _b64((9000).to_bytes(8, "big"))+ ts = "2026-06-02 08:15:00.000000"+ spans = [+ (root_span_id, ""), # root: empty parent → is_root_span = 1+ (_b64((9001).to_bytes(8, "big")), root_span_id), # child+ (_b64((9002).to_bytes(8, "big")), root_span_id), # child+ ]+ rows = [+ f"('019e8757-0000-0000-0000-{9000 + i:012d}', {self.team.id}, '{trace_id}', '{span_id}', "+ f"'{parent}', 'op', 2, '{ts}', '{ts}', '{ts}', 0, 'childsvc')"+ for i, (span_id, parent) in enumerate(spans)+ ]+ sync_execute(+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)+ )++ self.assertEqual(sum(r["count"] for r in self._sparkline(service_names=["childsvc"])), 3)+ self.assertEqual(sum(r["count"] for r in self._sparkline(service_names=["childsvc"], root_spans=True)), 1)++ def test_root_spans_counts_distinct_traces_not_root_rows(self):+ # A malformed trace with TWO root spans (both empty parent_span_id). Spans mode counts both+ # spans (2); Traces mode must count the trace once (1) — it counts distinct traces, like the+ # "N traces matching filters" label, not root-span rows.+ trace_id = _b64((901).to_bytes(16, "big"))+ ts = "2026-06-02 08:20:00.000000"+ spans = [+ (_b64((9100).to_bytes(8, "big")), ""), # root 1+ (_b64((9101).to_bytes(8, "big")), ""), # root 2, same trace_id+ ]+ rows = [+ f"('019e8757-0000-0000-0000-{9100 + i:012d}', {self.team.id}, '{trace_id}', '{span_id}', "+ f"'{parent}', 'op', 2, '{ts}', '{ts}', '{ts}', 0, 'multirootsvc')"+ for i, (span_id, parent) in enumerate(spans)+ ]+ sync_execute(+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)+ )++ self.assertEqual(sum(r["count"] for r in self._sparkline(service_names=["multirootsvc"])), 2)+ self.assertEqual(sum(r["count"] for r in self._sparkline(service_names=["multirootsvc"], root_spans=True)), 1)diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex c7481a6c0e06..bd955d1808e0 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -312,6 +312,24 @@ export interface _TracingQueryRequestApi {query: _TracingQueryBodyApi}+export interface _TracingSparklineQueryBodyApi {+ /** Date range for the query. Defaults to last hour. */+ dateRange?: _TracingDateRangeApi+ /** Filter by service names. */+ serviceNames?: string[]+ /** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */+ statusCodes?: number[]+ /** Property filters for the query. */+ filterGroup?: _SpanPropertyFilterApi[]+ /** When true, count only root spans (one per trace) so the bars reflect the Traces view. When false (default), count every matching span — the Spans view's volume. */+ rootSpans?: boolean+}++export interface _TracingSparklineRequestApi {+ /** The sparkline query to execute. */+ query: _TracingSparklineQueryBodyApi+}+export interface _SymbolStatsSymbolApi {/*** Opaque identifier (e.g. the function name) echoed back on the matching result row.diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 1a6b4d29c0bf..9d2ad4f0ffcc 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -21,6 +21,7 @@ import type {_TracingCountRequestApi,_TracingCountResponseApi,_TracingQueryRequestApi,+ _TracingSparklineRequestApi,_TracingTimeseriesRequestApi,_TracingTraceRequestApi,_TracingTreeRequestApi,@@ -191,14 +192,14 @@ export const getTracingSpansSparklineCreateUrl = (projectId: string) => {export const tracingSpansSparklineCreate = async (projectId: string,- _tracingTimeseriesRequestApi: _TracingTimeseriesRequestApi,+ _tracingSparklineRequestApi: _TracingSparklineRequestApi,options?: RequestInit): Promise<void> => {return apiMutator<void>(getTracingSpansSparklineCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(_tracingTimeseriesRequestApi),+ body: JSON.stringify(_tracingSparklineRequestApi),})}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 01c577b0135c..7ffb64ed1b8a 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -489,6 +489,7 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({})export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []+export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = falseexport const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -560,8 +561,14 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({).default(tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),+ rootSpans: zod+ .boolean()+ .default(tracingSpansSparklineCreateBodyQueryOneRootSpansDefault)+ .describe(+ "When true, count only root spans (one per trace) so the bars reflect the Traces view. When false (default), count every matching span — the Spans view's volume."+ ),})- .describe('The sparkline \/ duration-histogram query to execute.'),+ .describe('The sparkline query to execute.'),})export const TracingSpansSymbolStatsCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.tsindex dc43add42603..ea5a3f5ed376 100644--- a/products/tracing/frontend/tracingDataLogic.test.ts+++ b/products/tracing/frontend/tracingDataLogic.test.ts@@ -235,6 +235,20 @@ describe('tracingDataLogic', () => {tracingFiltersLogic().actions.setViewMode('spans')expect(logic.values.totalMatchingFilters).toBe(5000)})++ it('sparkline counts root spans in traces mode and all spans in spans mode', async () => {+ const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })+ logic = mountWithSpans([])+ await logic.asyncActions.fetchSparkline()+ expect(sparklineSpy).toHaveBeenCalledWith(expect.objectContaining({ rootSpans: true }), expect.anything())+ tracingFiltersLogic().actions.setViewMode('spans')+ await logic.asyncActions.fetchSparkline()+ expect(sparklineSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({ rootSpans: false }),+ expect.anything()+ )+ sparklineSpy.mockRestore()+ })})describe('matching counts', () => {@@ -270,14 +284,15 @@ describe('tracingDataLogic', () => {})describe('sparkline', () => {- it('does not re-fetch the sparkline when only the view mode changes', async () => {+ it('re-fetches the sparkline when the view mode changes', async () => {const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })logic = mountWithSpans([])await logic.asyncActions.fetchSparkline()tracingFiltersLogic().actions.setViewMode('spans')await logic.asyncActions.fetchSparkline()- // The sparkline is view-mode-independent, so the second run reuses the cached result.- expect(sparklineSpy).toHaveBeenCalledTimes(1)+ // The sparkline counts root spans in 'traces' mode and all spans in 'spans' mode, so a+ // view-mode toggle changes its scope and must re-fetch.+ expect(sparklineSpy).toHaveBeenCalledTimes(2)sparklineSpy.mockRestore()})diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex fc19c8f39476..7dcd8e9d3012 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -481,13 +481,16 @@ export const tracingDataLogic = kea<tracingDataLogicType>([[] as SparklineRow[],{fetchSparkline: async () => {- // Like the count, the sparkline depends only on the data scope (date range,- // services, filters) — not on view mode, sort, or compare. Skip the re-fetch (and its- // spinner overlay) when a Traces/Spans toggle re-runs the query without changing scope.+ // The sparkline counts root spans in 'traces' mode and every span in 'spans' mode+ // (via rootSpans below), so it depends on the data scope (date range, services,+ // filters) AND the view mode — but not on sort or compare. Skip the re-fetch (and+ // its spinner overlay) only when a sort/compare toggle re-runs the query without+ // changing scope or view mode.const scopeKey = JSON.stringify([values.utcDateRange,values.filters.serviceNames,values.filters.filterGroup,+ values.filters.viewMode,])if (scopeKey === cache.sparklineScope) {return values.rawSparklineData@@ -502,6 +505,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([serviceNames:values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.filters.filterGroup as PropertyGroupFilter,+ rootSpans: values.filters.viewMode === 'traces',},controller.signal)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex acdf9e7f9a06..69ce8fcbbe69 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53936,6 +53936,24 @@ export namespace Schemas {query: _TracingQueryBody;}+ export interface _TracingSparklineQueryBody {+ /** Date range for the query. Defaults to last hour. */+ dateRange?: _TracingDateRange;+ /** Filter by service names. */+ serviceNames?: string[];+ /** Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans. */+ statusCodes?: number[];+ /** Property filters for the query. */+ filterGroup?: _SpanPropertyFilter[];+ /** When true, count only root spans (one per trace) so the bars reflect the Traces view. When false (default), count every matching span — the Spans view's volume. */+ rootSpans?: boolean;+ }++ export interface _TracingSparklineRequest {+ /** The sparkline query to execute. */+ query: _TracingSparklineQueryBody;+ }+export interface _TracingTimeseriesQueryBody {/** Date range for the query. Defaults to last hour. */dateRange?: _TracingDateRange;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 8d290975b125..18099b9f5b19 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -588,6 +588,7 @@ export const TracingSpansSparklineCreateParams = /* @__PURE__ */ zod.object({})export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []+export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = falseexport const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -659,8 +660,14 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({).default(tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),+ rootSpans: zod+ .boolean()+ .default(tracingSpansSparklineCreateBodyQueryOneRootSpansDefault)+ .describe(+ "When true, count only root spans (one per trace) so the bars reflect the Traces view. When false (default), count every matching span — the Spans view's volume."+ ),})- .describe('The sparkline / duration-histogram query to execute.'),+ .describe('The sparkline query to execute.'),})export const tracingSpansTraceCreatePathTraceIdRegExp = new RegExp('^[a-zA-Z0-9]+$')diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.jsonindex 0ead90f92166..250c99898af9 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-sparkline.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"query": {- "description": "The sparkline / duration-histogram query to execute.",+ "description": "The sparkline query to execute.","properties": {"dateRange": {"description": "Date range for the query. Defaults to last hour.",@@ -71,6 +71,11 @@},"type": "array"},+ "rootSpans": {+ "default": false,+ "description": "When true, count only root spans (one per trace) so the bars reflect the Traces view. When false (default), count every matching span — the Spans view's volume.",+ "type": "boolean"+ },"serviceNames": {"description": "Filter by service names.","items": {