: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): show a duration histogram when sorting by duration (#62745)
Jon McCallum89587a6979fa
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5b147ad5b884..ea5b41dd2e56 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2910,6 +2910,19 @@ const api = {}> {return new ApiRequest().tracingSpans().withAction('sparkline').create({ signal, data: { query } })},+ async durationHistogram(+ query: {+ dateRange?: { date_from?: string | null; date_to?: string | null }+ serviceNames?: string[]+ statusCodes?: number[]+ filterGroup?: PropertyGroupFilter+ },+ signal?: AbortSignal+ ): Promise<{+ results: { bucket_ns: number; service: string; count: number }[]+ }> {+ return new ApiRequest().tracingSpans().withAction('duration-histogram').create({ signal, data: { query } })+ },async aggregate(query: {dateRange?: { date_from?: string | null; date_to?: string | null }diff --git a/products/tracing/backend/duration_histogram_query_runner.py b/products/tracing/backend/duration_histogram_query_runner.pynew file mode 100644index 000000000000..bc8cbb161f35--- /dev/null+++ b/products/tracing/backend/duration_histogram_query_runner.py@@ -0,0 +1,117 @@+from typing import TYPE_CHECKING++from posthog.schema import (+ CachedTraceSpansQueryResponse,+ DateRange,+ PropertyGroupFilter,+ TraceSpansQuery,+ TraceSpansQueryResponse,+)++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.hogql_queries.query_runner import ExecutionMode++from products.tracing.backend.logic import TraceSpansQueryRunner++if TYPE_CHECKING:+ from posthog.models import Team+++class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):+ """Trace counts per logarithmic duration bucket, stacked by service.++ Feeds the sparkline when the span list is sorted by duration: x = 1-2-5 series duration+ buckets (1ms, 2ms, 5ms, 10ms, ...), bars = count of traces whose ROOT span falls in the+ bucket (the root is the row the list displays), grouped by service. Only non-empty buckets+ are returned; the frontend fills gaps along the series so the axis is continuous.++ Root scoping is unconditional — `query.rootSpans` is deliberately ignored. The histogram is a+ distribution of *traces*; counting child spans would mix units. The 1-2-5 bucketing below is+ mirrored in `frontend/durationBuckets.ts` (snapDurationToBucket), which re-snaps client-side+ only to place the scroll highlight — change the series in BOTH places.+ """++ def _calculate(self) -> TraceSpansQueryResponse:+ response = execute_hogql_query(+ query_type="TraceSpansDurationHistogramQuery",+ query=self.to_query(),+ modifiers=self.modifiers,+ team=self.team,+ workload=Workload.LOGS,+ timings=self.timings,+ limit_context=self.limit_context,+ settings=self.settings,+ )++ results = []+ for row in response.results:+ results.append(+ {+ "bucket_ns": int(row[0]),+ "service": row[1],+ "count": row[2],+ }+ )++ return TraceSpansQueryResponse(results=results)++ def to_query(self) -> ast.SelectQuery:+ # Bucket a duration onto the 1-2-5 series: take its decade (power of ten) and snap the+ # mantissa down to 1, 2 or 5. `greatest(..., 1)` parks zero-duration spans in the 1ns+ # bucket instead of feeding log10(0). The mantissa expression repeats the decade rather+ # than referencing its alias so HogQL resolution never depends on sibling aliases;+ # ClickHouse collapses the common subexpression. `round()` before the cast absorbs float+ # wobble in pow/log10 (e.g. 4.9999...e8 → 5e8).+ query = parse_select(+ """+ SELECT+ toInt(round(+ pow(10, floor(log10(greatest(duration_nano, 1)))) * multiIf(+ duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 2, 1,+ duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 5, 2,+ 5+ )+ )) AS bucket_ns,+ service_name AS service,+ count() AS count+ FROM posthog.trace_spans+ WHERE {where}+ AND is_root_span = 1+ AND timestamp >= {date_from} AND timestamp < {date_to}+ GROUP BY bucket_ns, service+ ORDER BY bucket_ns ASC, count DESC+ LIMIT 10 BY bucket_ns+ LIMIT 10000+ """,+ placeholders={+ **self.query_date_range.to_placeholders(),+ "where": self.where(),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query+++def run_duration_histogram_query(+ *,+ team: "Team",+ date_range: DateRange,+ service_names: list[str] | None = None,+ status_codes: list[int] | None = None,+ filter_group: PropertyGroupFilter | None = None,+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:+ """Facade-friendly entry point for running a duration histogram query."""+ query = TraceSpansQuery(+ dateRange=date_range,+ serviceNames=service_names,+ statusCodes=status_codes,+ filterGroup=filter_group,+ )+ runner = TraceSpansDurationHistogramQueryRunner(query, team)+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)+ return responsediff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.pyindex f02f4882bcc4..10404e6994c5 100644--- a/products/tracing/backend/facade/api.py+++ b/products/tracing/backend/facade/api.py@@ -21,6 +21,9 @@ from typing import TYPE_CHECKINGfrom posthog.schema import CachedTraceSpansQueryResponse, DateRange, PropertyGroupFilter, TraceSpansQueryResponsefrom products.tracing.backend.count_query_runner import run_count_query as _run_count_query+from products.tracing.backend.duration_histogram_query_runner import (+ run_duration_histogram_query as _run_duration_histogram_query,+)if TYPE_CHECKING:from posthog.models import Team@@ -49,3 +52,21 @@ def run_count_query(status_codes=status_codes,filter_group=filter_group,)+++def run_duration_histogram_query(+ *,+ team: "Team",+ date_range: DateRange,+ service_names: list[str] | None = None,+ status_codes: list[int] | None = None,+ filter_group: PropertyGroupFilter | None = None,+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:+ """Run the per-bucket trace-duration histogram (root spans, stacked by service)."""+ return _run_duration_histogram_query(+ team=team,+ date_range=date_range,+ service_names=service_names,+ status_codes=status_codes,+ filter_group=filter_group,+ )diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex e3ed9cfc87c9..5a328fe1c319 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -38,7 +38,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.event_usage import report_user_actionfrom posthog.hogql_queries.query_runner import ExecutionMode-from ..facade.api import run_count_query+from ..facade.api import run_count_query, run_duration_histogram_queryfrom ..has_spans_query_runner import team_has_spansfrom ..logic import (TraceSpansQueryRunner,@@ -542,6 +542,32 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response({"results": response.results}, status=status.HTTP_200_OK)+ @extend_schema(request=_TracingQueryRequestSerializer)+ @action(detail=False, methods=["POST"], url_path="duration-histogram", required_scopes=["tracing:read"])+ def duration_histogram(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)+ query_data = request.data.get("query", {})+ date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)++ try:+ filter_group = (+ self.get_model(self._normalize_filter_group(query_data["filterGroup"]), PropertyGroupFilter)+ if query_data.get("filterGroup")+ else None+ )+ except (ValidationError, ValueError, ParseError):+ filter_group = None++ 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,+ )++ return Response({"results": response.results}, status=status.HTTP_200_OK)+@extend_schema(request=_TracingAggregationRequestSerializer)@action(detail=False, methods=["POST"], url_path="aggregate", required_scopes=["tracing:read"])def aggregate(self, request: Request, *args, **kwargs) -> Response:diff --git a/products/tracing/backend/tests/test_duration_histogram.py b/products/tracing/backend/tests/test_duration_histogram.pynew file mode 100644index 000000000000..2ac862326be2--- /dev/null+++ b/products/tracing/backend/tests/test_duration_histogram.py@@ -0,0 +1,77 @@+import datetime as dt++from posthog.clickhouse.client import sync_execute++from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase++# Root durations chosen to straddle 1-2-5 bucket boundaries: 1.5ms → 1ms bucket, 3ms and+# 3.5ms → 2ms bucket, 700ms → 500ms bucket. Trace 0 also gets a 5s child span, which must+# not appear anywhere — the histogram counts traces by ROOT duration (what the list shows).+TRACES = [+ # (root duration, child duration, service)+ (dt.timedelta(milliseconds=1.5), dt.timedelta(seconds=5), "web"),+ (dt.timedelta(milliseconds=3), None, "web"),+ (dt.timedelta(milliseconds=3.5), None, "web"),+ (dt.timedelta(milliseconds=700), None, "api"),+]++MS = 1_000_000 # ns per ms+++class TestTraceSpansDurationHistogram(_TraceSpansTestBase):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls._recreate_trace_spans_tables()++ base = dt.datetime(2026, 6, 2, 8, 0, 0)+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")+ rows: list[str] = []+ for i, (root_duration, child_duration, service) in enumerate(TRACES):+ trace_id = _b64(i.to_bytes(16, "big"))+ root_span_id = _b64((1000 + i * 2).to_bytes(8, "big"))+ root_end = (base + root_duration).strftime("%Y-%m-%d %H:%M:%S.%f")+ rows.append(+ f"('019e8756-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{root_span_id}', '', "+ f"'GET /api', 2, '{ts_str}', '{root_end}', '{ts_str}', 0, '{service}')"+ )+ if child_duration is not None:+ child_span_id = _b64((1001 + i * 2).to_bytes(8, "big"))+ child_end = (base + child_duration).strftime("%Y-%m-%d %H:%M:%S.%f")+ rows.append(+ f"('019e8756-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{child_span_id}', "+ f"'{root_span_id}', 'db query', 2, '{ts_str}', '{child_end}', '{ts_str}', 0, '{service}')"+ )+ 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)+ )++ def _histogram(self, *, service_names: list[str] | None = None) -> list[dict]:+ query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}}+ if service_names is not None:+ query["serviceNames"] = service_names+ response = self.client.post(+ f"/api/projects/{self.team.id}/tracing/spans/duration-histogram/",+ {"query": query},+ format="json",+ )+ self.assertEqual(response.status_code, 200, response.content)+ return response.json()["results"]++ def test_buckets_root_durations_on_the_1_2_5_series(self):+ rows = {(row["bucket_ns"], row["service"]): row["count"] for row in self._histogram()}+ self.assertEqual(+ rows,+ {+ (1 * MS, "web"): 1, # 1.5ms → 1ms bucket+ (2 * MS, "web"): 2, # 3ms + 3.5ms → 2ms bucket+ (500 * MS, "api"): 1, # 700ms → 500ms bucket+ },+ )+ # Implicit in the equality above, but make the design constraint loud: the 5s child span+ # must not produce a 5s bucket — only root durations count.++ def test_service_filter_flows_through(self):+ 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})diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 9a6c9e1f0795..cce5a573fdae 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -65,6 +65,10 @@ function TracingSceneContents(): JSX.Element {compareFlameSpanName,hasMoreToLoad,visibleRowDateRange,+ durationHistogramData,+ durationHistogramLoading,+ visibleRowDurationRange,+ isDurationMode,expandedSpanIds,} = useValues(tracingSceneLogic())const {@@ -149,11 +153,13 @@ function TracingSceneContents(): JSX.Element {<TracingSetupPrompt><TracingSparklinesparklineData={sparklineData}- sparklineLoading={sparklineLoading}+ sparklineLoading={sparklineLoading || (isDurationMode && durationHistogramLoading)}onDateRangeChange={setDateRange}displayTimezone="UTC"compare={compareConfig}visibleRowDateRange={visibleRowDateRange}+ durationHistogram={isDurationMode ? durationHistogramData : null}+ visibleRowDurationRange={visibleRowDurationRange}/><SceneDivider /><TracingFilterBar />diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsxindex 79ba356c461e..33b0f4f2d774 100644--- a/products/tracing/frontend/TracingSparkline.tsx+++ b/products/tracing/frontend/TracingSparkline.tsx@@ -10,6 +10,7 @@ import { cn } from 'lib/utils/css-classes'import { DateRange } from '~/queries/schema/schema-general'+import { type TracingDurationHistogramData, type VisibleDurationRange, snapDurationToBucket } from './durationBuckets'import { SparklineCompareOverlay } from './SparklineCompareOverlay'import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'@@ -28,6 +29,9 @@ interface TracingSparklineProps {displayTimezone: stringcompare?: CompareConfigvisibleRowDateRange?: VisibleSpanTimeRange | null+ /** When set, render a duration histogram instead of the time series (list sorted by duration). */+ durationHistogram?: TracingDurationHistogramData | null+ visibleRowDurationRange?: VisibleDurationRange | null}export function TracingSparkline({@@ -37,8 +41,11 @@ export function TracingSparkline({displayTimezone,compare,visibleRowDateRange,+ durationHistogram,+ visibleRowDurationRange,}: TracingSparklineProps): JSX.Element | null {const [collapsed, setCollapsed] = useState(false)+ const durationMode = durationHistogram != nullconst { timeUnit, tickFormat } = useMemo(() => {if (!sparklineData.dates.length) {@@ -60,6 +67,23 @@ export function TracingSparkline({const withXScale = useCallback((scale: AnyScaleOptions): AnyScaleOptions => {+ if (durationMode) {+ // Duration buckets are categorical (1ms, 2ms, 5ms, ...) — the 1-2-5 series is+ // already log-spaced, so a plain category axis renders it evenly.+ return {+ ...scale,+ type: 'category',+ ticks: {+ display: true,+ maxRotation: 0,+ maxTicksLimit: 8,+ font: {+ size: 10,+ lineHeight: 1,+ },+ },+ } as AnyScaleOptions+ }return {...scale,type: 'timeseries',@@ -81,21 +105,43 @@ export function TracingSparkline({},} as AnyScaleOptions},- [timeUnit, tickFormat, displayTimezone]+ [durationMode, timeUnit, tickFormat, displayTimezone])const renderLabel = useCallback((label: string): string => {+ if (durationMode) {+ return label // bucket labels ("2ms") are already human-readable+ }const d = displayTimezone ? dayjs(label).tz(displayTimezone) : dayjs(label)const tz = displayTimezone === 'UTC' ? 'UTC' : (shortTimeZone(displayTimezone, d.toDate()) ?? 'Local')return `${d.format('D MMM YYYY HH:mm:ss')} ${tz}`},- [displayTimezone]+ [durationMode, displayTimezone])const sparklineLabels = useMemo(() => {+ if (durationHistogram) {+ return durationHistogram.labels+ }return sparklineData.dates.map((date: string) => dayjs(date).toISOString())- }, [sparklineData.dates])+ }, [durationHistogram, sparklineData.dates])++ // Map the visible rows' duration range onto histogram bucket indices: snap each edge onto+ // the same 1-2-5 series the backend bucketed with, then find those buckets on the axis.+ const durationHighlightedRange = useMemo(() => {+ if (!durationHistogram || !visibleRowDurationRange || durationHistogram.bucketsNs.length === 0) {+ return null+ }+ const { bucketsNs } = durationHistogram+ // An edge missing from the axis can only mean it's outside the rendered range (the axis+ // spans the data's min..max bucket), so clamp it to the nearest end.+ const startIndexRaw = bucketsNs.indexOf(snapDurationToBucket(visibleRowDurationRange.minNs))+ const endIndexRaw = bucketsNs.indexOf(snapDurationToBucket(visibleRowDurationRange.maxNs))+ const startIndex = startIndexRaw === -1 ? 0 : startIndexRaw+ const endIndex = endIndexRaw === -1 ? bucketsNs.length - 1 : endIndexRaw+ return startIndex <= endIndex ? { startIndex, endIndex } : null+ }, [visibleRowDurationRange, durationHistogram])// Map the visible-row date range onto bucket indices in `dates`. Buckets are anchored at// their start time; the date_to edge belongs to the bucket whose start is the last one@@ -157,23 +203,27 @@ export function TracingSparkline({aria-expanded={!collapsed}aria-controls="tracing-sparkline-content">- <span className="text-xs text-muted">Volume over time</span>+ <span className="text-xs text-muted">+ {durationMode ? 'Duration distribution' : 'Volume over time'}+ </span></LemonButton></div>{!collapsed && (<div id="tracing-sparkline-content" className="relative h-32">- {sparklineData.data.length > 0 ? (+ {(durationHistogram ? durationHistogram.data : sparklineData.data).length > 0 ? (<Sparklinelabels={sparklineLabels}- data={sparklineData.data}+ data={durationHistogram ? durationHistogram.data : sparklineData.data}className="w-full h-full"- onSelectionChange={compare ? undefined : onSelectionChange}+ // Drag-select sets the date range — meaningless on a duration axis, so+ // disabled in duration mode (a duration-range filter is a later idea).+ onSelectionChange={compare || durationMode ? undefined : onSelectionChange}withXScale={withXScale}renderLabel={renderLabel}tooltipRowCutoff={100}hideZerosInTooltipsortTooltipByCount- highlightedRange={highlightedRange}+ highlightedRange={durationMode ? durationHighlightedRange : highlightedRange}/>) : !sparklineLoading ? (<div className="h-full text-muted flex items-center justify-center">diff --git a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.tsindex 6d83b02d9057..aa82b6cb6d30 100644--- a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts+++ b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts@@ -5,10 +5,18 @@ import { initKeaTests } from '~/test/init'import { tracingIngestionLogic } from './tracingIngestionLogic'-jest.mock('lib/utils', () => ({- ...jest.requireActual('lib/utils'),- delay: () => Promise.resolve(),-}))+jest.mock('lib/utils', () => {+ const actual = jest.requireActual<typeof import('lib/utils')>('lib/utils')+ return {+ ...actual,+ // Run the real retry loop with no inter-attempt backoff. Otherwise the 1000ms + 1500ms+ // delays burn ~2.5s of real time per failing test and flake the 5s expectLogic timeout in CI.+ retryWithBackoff: (+ fn: Parameters<typeof actual.retryWithBackoff>[0],+ options: Parameters<typeof actual.retryWithBackoff>[1] = {}+ ) => actual.retryWithBackoff(fn, { ...options, initialDelayMs: 0 }),+ }+})describe('tracingIngestionLogic', () => {let logic: ReturnType<typeof tracingIngestionLogic.build>diff --git a/products/tracing/frontend/durationBuckets.test.ts b/products/tracing/frontend/durationBuckets.test.tsnew file mode 100644index 000000000000..612e8c24d63c--- /dev/null+++ b/products/tracing/frontend/durationBuckets.test.ts@@ -0,0 +1,73 @@+import {+ fillBucketSeries,+ formatBucketLabel,+ pivotDurationHistogram,+ snapDurationToBucket,+ visibleDurationRange,+} from './durationBuckets'++const MS = 1_000_000 // ns per ms++describe('durationBuckets', () => {+ it.each([+ [1_500_000, 1 * MS], // 1.5ms → 1ms+ [3_000_000, 2 * MS], // 3ms → 2ms+ [3_500_000, 2 * MS], // 3.5ms → 2ms+ [700 * MS, 500 * MS], // 700ms → 500ms+ [2 * MS, 2 * MS], // exact bucket value stays put+ [999, 500], // 999ns → 500ns+ [0, 1], // zero durations park in the 1ns bucket+ [5_000_000_000, 5_000_000_000], // exact 5s+ ])('snapDurationToBucket(%i) → %i', (ns, expected) => {+ expect(snapDurationToBucket(ns)).toBe(expected)+ })++ it('fillBucketSeries spans the 1-2-5 series inclusively', () => {+ expect(fillBucketSeries(1 * MS, 500 * MS)).toEqual(+ [1, 2, 5, 10, 20, 50, 100, 200, 500].map((bucketMs) => bucketMs * MS)+ )+ expect(fillBucketSeries(2 * MS, 2 * MS)).toEqual([2 * MS])+ })++ it.each([+ [500, '500ns'],+ [2_000, '2µs'],+ [2 * MS, '2ms'],+ [500 * MS, '500ms'],+ [5_000_000_000, '5s'],+ ])('formatBucketLabel(%i) → %s', (ns, expected) => {+ expect(formatBucketLabel(ns)).toBe(expected)+ })++ it('pivotDurationHistogram stacks services and fills axis gaps with zeros', () => {+ const rows = [+ { bucket_ns: 1 * MS, service: 'web', count: 1 },+ { bucket_ns: 2 * MS, service: 'web', count: 2 },+ // Nothing between 2ms and 500ms — the axis must still be continuous.+ { bucket_ns: 500 * MS, service: 'api', count: 1 },+ ]+ const result = pivotDurationHistogram(rows, ['c1', 'c2'])++ expect(result.bucketsNs).toEqual([1, 2, 5, 10, 20, 50, 100, 200, 500].map((bucketMs) => bucketMs * MS))+ expect(result.labels).toEqual(['1ms', '2ms', '5ms', '10ms', '20ms', '50ms', '100ms', '200ms', '500ms'])+ expect(result.data).toEqual([+ { name: 'api', values: [0, 0, 0, 0, 0, 0, 0, 0, 1], color: 'c1' },+ { name: 'web', values: [1, 2, 0, 0, 0, 0, 0, 0, 0], color: 'c2' },+ ])+ })++ it('pivotDurationHistogram returns empties for no rows', () => {+ expect(pivotDurationHistogram([], ['c1'])).toEqual({ data: [], bucketsNs: [], labels: [] })+ })++ it('visibleDurationRange orders min/max regardless of sort direction and clamps indices', () => {+ const durations = [900, 500, 100] // DESC-sorted list+ expect(visibleDurationRange({ startIndex: 0, stopIndex: 2 }, durations)).toEqual({ minNs: 100, maxNs: 900 })+ // ASC direction: boundary rows reversed, same range comes back ordered.+ expect(visibleDurationRange({ startIndex: 2, stopIndex: 0 }, durations)).toEqual({ minNs: 100, maxNs: 900 })+ // Indices past the end clamp to the last row.+ expect(visibleDurationRange({ startIndex: 1, stopIndex: 99 }, durations)).toEqual({ minNs: 100, maxNs: 500 })+ expect(visibleDurationRange(null, durations)).toBeNull()+ expect(visibleDurationRange({ startIndex: 0, stopIndex: 1 }, [])).toBeNull()+ })+})diff --git a/products/tracing/frontend/durationBuckets.ts b/products/tracing/frontend/durationBuckets.tsnew file mode 100644index 000000000000..461697189d95--- /dev/null+++ b/products/tracing/frontend/durationBuckets.ts@@ -0,0 +1,134 @@+// Pure helpers for the duration-histogram sparkline (JON-36). The list sorted by duration pairs+// with a histogram of trace counts per logarithmic duration bucket; everything here is pure so it+// can be unit-tested without the kea logic's import graph.++export interface DurationHistogramRow {+ bucket_ns: number+ service: string+ count: number+}++export interface TracingDurationHistogramData {+ data: { name: string; values: number[]; color: string }[]+ /** The 1-2-5 series bucket for each bar, in ns — the duration-space sibling of `dates`. */+ bucketsNs: number[]+ labels: string[]+}++export interface VisibleDurationRange {+ minNs: number+ maxNs: number+}++const BUCKET_MANTISSAS = [1, 2, 5]++/**+ * Snap a duration (ns) down onto the 1-2-5 log series the histogram buckets use (1ms, 2ms, 5ms, ...).+ *+ * Mirrors the SQL bucketing in `backend/duration_histogram_query_runner.py` — the backend buckets+ * authoritatively; the frontend only re-snaps to map the visible rows' durations (scroll position is+ * client-side) onto the rendered axis. Change the series in BOTH places or the highlight drifts.+ */+export function snapDurationToBucket(ns: number): number {+ const clamped = Math.max(ns, 1)+ const decade = Math.pow(10, Math.floor(Math.log10(clamped)))+ const mantissa = clamped / decade+ return Math.round(decade * (mantissa < 2 ? 1 : mantissa < 5 ? 2 : 5))+}++/** Every 1-2-5 series bucket from minBucket to maxBucket inclusive (both already snapped). */+export function fillBucketSeries(minBucket: number, maxBucket: number): number[] {+ const buckets: number[] = []+ let decade = Math.pow(10, Math.floor(Math.log10(Math.max(minBucket, 1))))+ for (;;) {+ for (const mantissa of BUCKET_MANTISSAS) {+ const bucket = Math.round(decade * mantissa)+ if (bucket > maxBucket) {+ return buckets+ }+ if (bucket >= minBucket) {+ buckets.push(bucket)+ }+ }+ decade *= 10+ }+}++/** Buckets are exact 1-2-5 values, so labels stay clean integers ("2ms", "500ms", "1s"). */+export function formatBucketLabel(ns: number): string {+ if (ns < 1_000) {+ return `${ns}ns`+ }+ if (ns < 1_000_000) {+ return `${ns / 1_000}µs`+ }+ if (ns < 1_000_000_000) {+ return `${ns / 1_000_000}ms`+ }+ return `${ns / 1_000_000_000}s`+}++/**+ * Pivot histogram rows into the Sparkline series shape, filling gaps along the 1-2-5 series+ * between the smallest and largest non-empty bucket so the log axis is continuous.+ */+export function pivotDurationHistogram(+ rows: DurationHistogramRow[],+ colors: readonly string[]+): TracingDurationHistogramData {+ if (!rows.length) {+ return { data: [], bucketsNs: [], labels: [] }+ }++ const minBucket = Math.min(...rows.map((row) => row.bucket_ns))+ const maxBucket = Math.max(...rows.map((row) => row.bucket_ns))+ const bucketsNs = fillBucketSeries(minBucket, maxBucket)+ const indexByBucket = new Map(bucketsNs.map((bucket, index) => [bucket, index]))++ const accumulated: Record<string, number[]> = {}+ for (const row of rows) {+ if (!row.service) {+ continue+ }+ const index = indexByBucket.get(row.bucket_ns)+ if (index === undefined) {+ continue+ }+ if (!accumulated[row.service]) {+ accumulated[row.service] = bucketsNs.map(() => 0)+ }+ accumulated[row.service][index] += row.count+ }++ const data = Object.entries(accumulated)+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([name, values], index) => ({+ name,+ values,+ color: colors[index % colors.length],+ }))+ .filter((series) => series.values.reduce((a, b) => a + b, 0) > 0)++ return { data, bucketsNs, labels: bucketsNs.map(formatBucketLabel) }+}++/**+ * Duration range spanned by the visible slice of a duration-sorted list, given the durations of+ * its rows in display order. Returns min/max regardless of ASC/DESC sort direction.+ */+export function visibleDurationRange(+ visibleRowRange: { startIndex: number; stopIndex: number } | null,+ durationsNs: number[]+): VisibleDurationRange | null {+ if (!visibleRowRange || durationsNs.length === 0) {+ return null+ }+ const startIndex = Math.max(0, Math.min(visibleRowRange.startIndex, durationsNs.length - 1))+ const stopIndex = Math.max(0, Math.min(visibleRowRange.stopIndex, durationsNs.length - 1))+ const a = durationsNs[startIndex]+ const b = durationsNs[stopIndex]+ if (a === undefined || b === undefined) {+ return null+ }+ return { minNs: Math.min(a, b), maxNs: Math.max(a, b) }+}diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex c1f71c0872b5..b1c96d51a510 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -135,11 +135,6 @@ export interface _TracingCountResponseApi {count: number}-export interface _HasSpansResponseApi {- /** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */- hasSpans: boolean-}-/*** * `timestamp` - timestamp* * `duration` - duration@@ -206,6 +201,11 @@ export interface _TracingQueryRequestApi {query: _TracingQueryBodyApi}+export interface _HasSpansResponseApi {+ /** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */+ hasSpans: boolean+}+export interface _TracingTraceRequestApi {/** Date range for the query. Defaults to last 24 hours. */dateRange?: _TracingDateRangeApidiff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 4bfbb7d6101f..13d16f9504aa 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -85,6 +85,23 @@ export const tracingSpansCountCreate = async (})}+export const getTracingSpansDurationHistogramCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tracing/spans/duration-histogram/`+}++export const tracingSpansDurationHistogramCreate = async (+ projectId: string,+ _tracingQueryRequestApi: _TracingQueryRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getTracingSpansDurationHistogramCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_tracingQueryRequestApi),+ })+}+export const getTracingSpansHasSpansRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/tracing/spans/has_spans/`}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 2c4743af7471..4cf655af70ee 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -170,6 +170,119 @@ export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({.describe('The span count query to execute.'),})+export const tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault = []+export const tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault = 100+export const tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin = 0++export const tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault = true+export const tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault = false++export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),+ })+ .optional()+ .describe('Date range for the query. Defaults to last hour.'),+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),+ statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),+ orderBy: zod+ .enum(['timestamp', 'duration'])+ .describe('\* `timestamp` - timestamp\n\* `duration` - duration')+ .optional()+ .describe(+ "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n\* `timestamp` - timestamp\n\* `duration` - duration"+ ),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .describe('\* `ASC` - ASC\n\* `DESC` - DESC')+ .optional()+ .describe(+ 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n\* `ASC` - ASC\n\* `DESC` - DESC'+ ),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'+ ),+ type: zod+ .enum(['span', 'span_attribute', 'span_resource_attribute'])+ .describe(+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ )+ .describe(+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'+ ),+ })+ )+ .default(tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault)+ .describe('Property filters for the query.'),+ traceId: zod.string().optional().describe('Filter to a specific trace ID (hex string).'),+ limit: zod+ .number()+ .default(tracingSpansDurationHistogramCreateBodyQueryOneLimitDefault)+ .describe('Max results (1-1000). Defaults to 100.'),+ after: zod+ .string()+ .optional()+ .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),+ offset: zod+ .number()+ .min(tracingSpansDurationHistogramCreateBodyQueryOneOffsetMin)+ .optional()+ .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),+ rootSpans: zod+ .boolean()+ .default(tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault)+ .describe('Filter to root spans only. Defaults to true.'),+ prefetchSpans: zod.number().optional().describe('Number of child spans to prefetch per trace (1-100).'),+ excludeAttributes: zod+ .boolean()+ .default(tracingSpansDurationHistogramCreateBodyQueryOneExcludeAttributesDefault)+ .describe('Omit the per-span attributes map from results to keep payloads compact. Defaults to false.'),+ })+ .describe('The tracing spans query to execute.'),+})+export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 96d01b09b0af..a9035ac4bb7b 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -12,8 +12,15 @@ import { humanFriendlyDetailedTime } from 'lib/utils'import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'import { PropertyGroupFilter } from '~/types'+import {+ type DurationHistogramRow,+ pivotDurationHistogram,+ type TracingDurationHistogramData,+ type VisibleDurationRange,+ visibleDurationRange,+} from './durationBuckets'import type { tracingDataLogicType } from './tracingDataLogicType'-import { type TracingOrderBy, tracingFiltersLogic } from './tracingFiltersLogic'+import { type TracingFilters, type TracingOrderBy, tracingFiltersLogic } from './tracingFiltersLogic'import type { Span } from './types'export interface SparklineRow {@@ -68,10 +75,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([clearSpans: true,cancelInProgressSpans: (controller: AbortController | null) => ({ controller }),cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),+ cancelInProgressDurationHistogram: (controller: AbortController | null) => ({ controller }),cancelInProgressAggregation: (controller: AbortController | null) => ({ controller }),cancelInProgressSpanTree: (controller: AbortController | null) => ({ controller }),setSpansAbortController: (controller: AbortController | null) => ({ controller }),setSparklineAbortController: (controller: AbortController | null) => ({ controller }),+ setDurationHistogramAbortController: (controller: AbortController | null) => ({ controller }),setAggregationAbortController: (controller: AbortController | null) => ({ controller }),setSpanTreeAbortController: (controller: AbortController | null) => ({ controller }),setHasMoreToLoad: (hasMore: boolean) => ({ hasMore }),@@ -100,6 +109,10 @@ export const tracingDataLogic = kea<tracingDataLogicType>([null as AbortController | null,{ setSparklineAbortController: (_, { controller }) => controller },],+ durationHistogramAbortController: [+ null as AbortController | null,+ { setDurationHistogramAbortController: (_, { controller }) => controller },+ ],aggregationAbortController: [null as AbortController | null,{ setAggregationAbortController: (_, { controller }) => controller },@@ -143,6 +156,14 @@ export const tracingDataLogic = kea<tracingDataLogicType>([fetchSparklineFailure: () => false,},],+ durationHistogramLoading: [+ false as boolean,+ {+ fetchDurationHistogram: () => true,+ fetchDurationHistogramSuccess: () => false,+ fetchDurationHistogramFailure: () => false,+ },+ ],aggregationLoading: [false as boolean,{@@ -381,6 +402,28 @@ export const tracingDataLogic = kea<tracingDataLogicType>([},},],+ rawDurationHistogram: [+ [] as DurationHistogramRow[],+ {+ fetchDurationHistogram: async () => {+ const controller = new AbortController()+ actions.cancelInProgressDurationHistogram(controller)++ const response = await api.tracing.durationHistogram(+ {+ dateRange: values.utcDateRange,+ serviceNames:+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,+ },+ controller.signal+ )++ actions.setDurationHistogramAbortController(null)+ return response.results+ },+ },+ ],})),selectors({@@ -439,18 +482,54 @@ export const tracingDataLogic = kea<tracingDataLogicType>([(s) => [s.rawSparklineData],(rows: SparklineRow[]): number => rows.reduce((sum, item) => sum + item.count, 0),],+ durationHistogramData: [+ (s) => [s.rawDurationHistogram],+ (rows: DurationHistogramRow[]): TracingDurationHistogramData => pivotDurationHistogram(rows, dataColorVars),+ ],rootSpans: [(s) => [s.spans],(spans: Span[]): Span[] => {return spans.filter((s) => s.is_root_span)},],+ // Memoized separately so visibleRowDurationRange (recomputed on every scroll tick) doesn't+ // re-allocate the durations array — this only changes when the loaded spans do.+ rootSpanDurations: [+ (s) => [s.rootSpans],+ (rootSpans: Span[]): number[] => rootSpans.map((span) => span.duration_nano),+ ],+ // Single owner of the "show the duration histogram?" rule — the fetch decision, the+ // highlight selector, and the scene's rendering all derive from this one place.+ // Compare mode replaces the span list with the aggregate table, so the histogram+ // (which mirrors the duration-sorted list) only applies outside it.+ isDurationMode: [+ (s) => [s.filters],+ (filters: TracingFilters): boolean => filters.orderBy === 'duration' && !filters.compareMode,+ ],++ // Duration range covered by the currently-visible rows — the duration-space sibling of+ // visibleRowDateRange below. When sorted by duration the visible rows are contiguous in+ // duration space, so the histogram can sweep a highlight across the distribution as the+ // user scrolls (the same interaction the time sparkline has under timestamp sort).+ visibleRowDurationRange: [+ (s) => [s.visibleRowRange, s.rootSpanDurations, s.isDurationMode],+ (+ visibleRowRange: VisibleRowRange | null,+ rootSpanDurations: number[],+ isDurationMode: boolean+ ): VisibleDurationRange | null => {+ if (!isDurationMode) {+ return null+ }+ return visibleDurationRange(visibleRowRange, rootSpanDurations)+ },+ ],// Date range covered by the currently-visible (scrolled-into-view) rows, so the sparkline can// highlight the window the list is showing (mirrors the logs viewer). Only meaningful when the// list is time-ordered — under duration (or any non-timestamp) sort, consecutive rows aren't- // contiguous in time, so the highlight would be meaningless. Suppress it then; a- // duration-appropriate overlay is a follow-up (JON-36).+ // contiguous in time, so the highlight would be meaningless. Suppress it then; the duration+ // histogram (visibleRowDurationRange above) covers the duration-sorted case.visibleRowDateRange: [(s) => [s.visibleRowRange, s.rootSpans, s.orderBy],(@@ -482,7 +561,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>([listeners(({ actions, values }) => ({runQuery: () => {actions.clearSpans()+ // The time sparkline is always fetched — it also feeds totalSpansMatchingFilters, and+ // keeps the chart warm when the user flips back to timestamp sort. Duration sort+ // additionally fetches the histogram that replaces it visually.actions.fetchSparkline()+ if (values.isDurationMode) {+ actions.fetchDurationHistogram()+ }if (values.filters.compareMode) {actions.fetchAggregation()} else {@@ -501,6 +586,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([}actions.setSparklineAbortController(controller)},+ cancelInProgressDurationHistogram: ({ controller }) => {+ if (values.durationHistogramAbortController !== null) {+ values.durationHistogramAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)+ }+ actions.setDurationHistogramAbortController(controller)+ },cancelInProgressAggregation: ({ controller }) => {if (values.aggregationAbortController !== null) {values.aggregationAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)@@ -525,11 +616,6 @@ export const tracingDataLogic = kea<tracingDataLogicType>([posthog.capture('tracing query failed', { query_type: 'spans', error_message: String(error) })}},- fetchSparklineFailure: ({ error }) => {- if (!isUserInitiatedError(error)) {- // Sparkline failures are non-critical, don't show toast- }- },fetchAggregationFailure: ({ error }) => {if (!isUserInitiatedError(error)) {lemonToast.error(`Failed to load span aggregation: ${error}`)@@ -550,6 +636,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([if (values.sparklineAbortController) {values.sparklineAbortController.abort('unmounting component')}+ if (values.durationHistogramAbortController) {+ values.durationHistogramAbortController.abort('unmounting component')+ }if (values.spanTreeAbortController) {values.spanTreeAbortController.abort('unmounting component')}diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex d665ad2fdd73..3bcc966296bc 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -43,6 +43,10 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['spanTree','spanTreeLoading','visibleRowDateRange',+ 'durationHistogramData',+ 'durationHistogramLoading',+ 'visibleRowDurationRange',+ 'isDurationMode',],tracingFiltersLogic(),['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs'],diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex 150535fb688a..a5b68ce3c7fe 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -157,6 +157,9 @@ tools:response:include:- results+ tracing-spans-duration-histogram-create:+ operation: tracing_spans_duration_histogram_create+ enabled: falsetracing-spans-has-spans-retrieve:operation: tracing_spans_has_spans_retrieveenabled: false