: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): add operation detail scene with latency histogram and trace samples (#67757)
Jon McCallum89e37ec7a19d
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 7c04bf46a879..9d30047adef3 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -3016,6 +3016,9 @@ const api = {serviceNames?: string[]statusCodes?: number[]filterGroup?: PropertyGroupFilter+ // true (default) buckets root spans only (a distribution of traces); false buckets+ // every matching span — pair with a span name filter for operation-scoped pages.+ rootSpans?: boolean},signal?: AbortSignal): Promise<{diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 8b74c7cdc213..d06dad4c007a 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -154,6 +154,7 @@ export const productScenes: Record<string, () => Promise<any>> = {Skill: () => import('../../products/skills/frontend/LLMSkillScene'),SlackTaskContext: () => import('../../products/tasks/frontend/SlackTaskContextScene'),Tracing: () => import('../../products/tracing/frontend/TracingScene'),+ TracingOperation: () => import('../../products/tracing/frontend/TracingOperationScene'),UserInterviews: () => import('../../products/user_interviews/frontend/UserInterviews'),UserInterview: () => import('../../products/user_interviews/frontend/UserInterview'),UserInterviewResponse: () => import('../../products/user_interviews/frontend/UserInterviewResponse'),@@ -304,6 +305,7 @@ export const productRoutes: Record<string, [string, string]> = {'/skills/:name': ['Skill', 'skill'],'/slack-task-context': ['SlackTaskContext', 'slackTaskContext'],'/tracing': ['Tracing', 'tracing'],+ '/tracing/operation': ['TracingOperation', 'tracingOperation'],'/user_research': ['UserInterviews', 'userInterviews'],'/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],'/user_research/:id': ['UserInterview', 'userInterview'],@@ -866,6 +868,14 @@ export const productConfiguration: Record<string, any> = {description: 'Monitor and analyze distributed traces to understand service performance and debug issues.',iconType: 'tracing',},+ TracingOperation: {+ name: 'Operation',+ projectBased: true,+ layout: 'app-container',+ activityScope: 'Tracing',+ description: 'Latency distribution and sample traces for a single operation.',+ iconType: 'tracing',+ },UserInterviews: {name: 'User research',projectBased: true,@@ -1307,6 +1317,8 @@ export const productUrls = {slackTaskContext: (): string => '/slack-task-context',toolbarLaunch: (): string => '/toolbar',tracing: (): string => '/tracing',+ tracingOperation: (serviceName: string, spanName: string): string =>+ combineUrl('/tracing/operation', { service: serviceName, name: spanName }).url,userInterviews: (): string => '/user_research',userInterview: (id: string): string => `/user_research/${id}`,userInterviewResponse: (topicId: string, responseId: string): string =>@@ -2230,7 +2242,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [flag: FEATURE_FLAGS.TRACING,tags: ['alpha'],sceneKey: 'Tracing',- sceneKeys: ['Tracing'],+ sceneKeys: ['Tracing', 'TracingOperation'],},{path: 'User research',diff --git a/products/tracing/backend/duration_histogram_query_runner.py b/products/tracing/backend/duration_histogram_query_runner.pyindex bc8cbb161f35..3dbe3d55c9d3 100644--- a/products/tracing/backend/duration_histogram_query_runner.py+++ b/products/tracing/backend/duration_histogram_query_runner.py@@ -9,7 +9,7 @@ from posthog.schema import ()from 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@@ -29,8 +29,10 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):bucket (the root is the row the list displays), grouped by service. Only non-empty bucketsare 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+ Root scoping is the default — a distribution of *traces* for the trace list, where counting+ child spans would mix units. When `query.rootSpans` is explicitly False (the operation detail+ page, which scopes by span name), every matching span is counted instead: same-named spans+ are the same unit, so a span-level distribution is sound there. The 1-2-5 bucketing below ismirrored in `frontend/durationBuckets.ts` (snapDurationToBucket), which re-snaps client-sideonly to place the scroll highlight — change the series in BOTH places."""@@ -80,7 +82,7 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):count() AS countFROM posthog.trace_spansWHERE {where}- AND is_root_span = 1+ AND {root_scope}AND timestamp >= {date_from} AND timestamp < {date_to}GROUP BY bucket_ns, serviceORDER BY bucket_ns ASC, count DESC@@ -90,6 +92,9 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):placeholders={**self.query_date_range.to_placeholders(),"where": self.where(),+ "root_scope": parse_expr("is_root_span = 1")+ if self.query.rootSpans is not False+ else ast.Constant(value=True),},)assert isinstance(query, ast.SelectQuery)@@ -103,6 +108,7 @@ def run_duration_histogram_query(service_names: list[str] | None = None,status_codes: list[int] | None = None,filter_group: PropertyGroupFilter | None = None,+ root_spans: bool = True,) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:"""Facade-friendly entry point for running a duration histogram query."""query = TraceSpansQuery(@@ -110,6 +116,7 @@ def run_duration_histogram_query(serviceNames=service_names,statusCodes=status_codes,filterGroup=filter_group,+ rootSpans=root_spans,)runner = TraceSpansDurationHistogramQueryRunner(query, team)response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.pyindex 9bba56e275e7..c74160e49316 100644--- a/products/tracing/backend/facade/api.py+++ b/products/tracing/backend/facade/api.py@@ -119,14 +119,20 @@ def run_duration_histogram_query(service_names: list[str] | None = None,status_codes: list[int] | None = None,filter_group: PropertyGroupFilter | None = None,+ root_spans: bool = True,) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:- """Run the per-bucket trace-duration histogram (root spans, stacked by service)."""+ """Run the per-bucket duration histogram, stacked by service.++ Root spans by default (a distribution of traces); `root_spans=False` buckets every+ matching span — pair with a span name filter for operation-scoped distributions.+ """return _run_duration_histogram_query(team=team,date_range=date_range,service_names=service_names,status_codes=status_codes,filter_group=filter_group,+ root_spans=root_spans,)diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 0549dc221551..6beee48e831c 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -214,6 +214,22 @@ class _TracingTimeseriesRequestSerializer(serializers.Serializer):query = _TracingTimeseriesQueryBodySerializer(help_text="The sparkline / duration-histogram query to execute.")+class _TracingDurationHistogramQueryBodySerializer(_TracingTimeseriesQueryBodySerializer):+ rootSpans = serializers.BooleanField(+ required=False,+ default=True,+ help_text=(+ "When true (default), bucket root-span durations only — a distribution of traces. "+ "When false, bucket every matching span — used with a span name filter for "+ "operation-scoped distributions."+ ),+ )+++class _TracingDurationHistogramRequestSerializer(serializers.Serializer):+ query = _TracingDurationHistogramQueryBodySerializer(help_text="The duration-histogram query to execute.")++class _TracingSparklineQueryBodySerializer(_TracingTimeseriesQueryBodySerializer):rootSpans = serializers.BooleanField(required=False,@@ -878,7 +894,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)return Response({"results": response.results}, status=status.HTTP_200_OK)- @extend_schema(request=_TracingTimeseriesRequestSerializer)+ @extend_schema(request=_TracingDurationHistogramRequestSerializer)@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)@@ -900,6 +916,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)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),)return Response({"results": response.results}, status=status.HTTP_200_OK)diff --git a/products/tracing/backend/tests/test_duration_histogram.py b/products/tracing/backend/tests/test_duration_histogram.pyindex 2ac862326be2..e2ca8e15a196 100644--- a/products/tracing/backend/tests/test_duration_histogram.py+++ b/products/tracing/backend/tests/test_duration_histogram.py@@ -47,8 +47,8 @@ class TestTraceSpansDurationHistogram(_TraceSpansTestBase):"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}}+ def _histogram(self, *, service_names: list[str] | None = None, **extra_query: object) -> list[dict]:+ query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}, **extra_query}if service_names is not None:query["serviceNames"] = service_namesresponse = self.client.post(@@ -75,3 +75,23 @@ class TestTraceSpansDurationHistogram(_TraceSpansTestBase):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})++ 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.+ rows = {+ (row["bucket_ns"], row["service"]): row["count"]+ for row in self._histogram(+ rootSpans=False,+ filterGroup={+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [{"type": "span", "key": "name", "operator": "exact", "value": ["db query"]}],+ }+ ],+ },+ )+ }+ self.assertEqual(rows, {(5_000 * MS, "web"): 1})diff --git a/products/tracing/frontend/OperationHistogram.tsx b/products/tracing/frontend/OperationHistogram.tsxnew file mode 100644index 000000000000..fe026d8b8eb1--- /dev/null+++ b/products/tracing/frontend/OperationHistogram.tsx@@ -0,0 +1,114 @@+import { useCallback, useMemo } from 'react'++import { LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'++import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'++import {+ formatBucketLabel,+ selectionToDurationRange,+ snapDurationToBucket,+ type TracingDurationHistogramData,+} from './durationBuckets'+import type { DurationRange } from './operationFilters'++interface OperationHistogramProps {+ data: TracingDurationHistogramData+ loading: boolean+ selection: DurationRange | null+ onSelect: (selection: DurationRange) => void+ onClear: () => void+}++// Duration buckets are categorical (1ms, 2ms, 5ms, ...) — the 1-2-5 series is already+// log-spaced, so a plain category axis renders it evenly (mirrors TracingSparkline).+function withCategoryXScale(scale: AnyScaleOptions): AnyScaleOptions {+ return {+ ...scale,+ type: 'category',+ ticks: {+ display: true,+ maxRotation: 0,+ maxTicksLimit: 8,+ font: {+ size: 10,+ lineHeight: 1,+ },+ },+ } as AnyScaleOptions+}++export function OperationHistogram({+ data,+ loading,+ selection,+ onSelect,+ onClear,+}: OperationHistogramProps): JSX.Element {+ const onSelectionChange = useCallback(+ ({ startIndex, endIndex }: { startIndex: number; endIndex: number }): void => {+ const range = selectionToDurationRange(data.bucketsNs, startIndex, endIndex)+ if (range) {+ onSelect(range)+ }+ },+ [data.bucketsNs, onSelect]+ )++ // Map the persisted selection back onto bucket indices: snap each edge onto the same+ // 1-2-5 series the backend bucketed with, then find those buckets on the axis.+ const highlightedRange = useMemo(() => {+ if (!selection || data.bucketsNs.length === 0) {+ return null+ }+ const { bucketsNs, labels } = data+ const startIndexRaw = bucketsNs.indexOf(snapDurationToBucket(selection.minNs))+ // maxNs is the exclusive upper edge — the highlight ends at the bar before it.+ const endIndexRaw = bucketsNs.indexOf(snapDurationToBucket(selection.maxNs))+ const startIndex = startIndexRaw === -1 ? 0 : startIndexRaw+ const endIndex = endIndexRaw === -1 ? bucketsNs.length : endIndexRaw+ if (startIndex >= endIndex) {+ return null+ }+ return { xMin: labels[startIndex], xMax: labels[endIndex] ?? labels[labels.length - 1] }+ }, [selection, data])++ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2 min-h-6">+ <span className="text-xs text-muted">Latency distribution</span>+ {selection ? (+ <>+ <span className="text-xs font-mono">+ {formatBucketLabel(selection.minNs)} – {formatBucketLabel(selection.maxNs)}+ </span>+ <LemonButton size="xsmall" type="tertiary" onClick={onClear}>+ Clear+ </LemonButton>+ </>+ ) : (+ <span className="text-xs text-muted italic">Drag to select a duration range</span>+ )}+ </div>+ <div className="relative h-32">+ {data.data.length > 0 ? (+ <Sparkline+ labels={data.labels}+ data={data.data}+ className="w-full h-full"+ onSelectionChange={onSelectionChange}+ withXScale={withCategoryXScale}+ renderLabel={(label) => label}+ tooltipRowCutoff={100}+ hideZerosInTooltip+ sortTooltipByCount+ highlightedRange={highlightedRange}+ />+ ) : !loading ? (+ <div className="h-full text-muted flex items-center justify-center">No spans in this range</div>+ ) : null}+ {loading && <SpinnerOverlay />}+ </div>+ </div>+ )+}diff --git a/products/tracing/frontend/TracingOperationScene.tsx b/products/tracing/frontend/TracingOperationScene.tsxnew file mode 100644index 000000000000..cbaf504e922e--- /dev/null+++ b/products/tracing/frontend/TracingOperationScene.tsx@@ -0,0 +1,178 @@+import { useActions, useValues } from 'kea'++import { IconChevronLeft, IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneDivider } from '~/layout/scenes/components/SceneDivider'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'++import { OperationHistogram } from './OperationHistogram'+import { formatDuration, TraceWaterfallView } from './TraceWaterfallView'+import { tracingOperationSceneLogic, type TracingOperationSceneLogicProps } from './tracingOperationSceneLogic'++export const scene: SceneExport<TracingOperationSceneLogicProps> = {+ component: TracingOperationScene,+ logic: tracingOperationSceneLogic,+ paramsToProps: ({ searchParams: { service, name } }) => ({+ serviceName: String(service ?? ''),+ spanName: String(name ?? ''),+ }),+ productKey: ProductKey.TRACING,+}++function StatBlock({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <div className="flex flex-col">+ <span className="text-xs text-muted">{label}</span>+ <span className="font-mono text-sm">{value}</span>+ </div>+ )+}++export function TracingOperationScene(): JSX.Element {+ const {+ serviceName,+ spanName,+ dateRange,+ histogramData,+ rawHistogramLoading,+ durationSelection,+ samples,+ samplesLoading,+ samplesHaveMore,+ sampleIndex,+ currentSample,+ sampleTraceSpans,+ sampleTraceSpansLoading,+ selectedSpanId,+ operationStats,+ } = useValues(tracingOperationSceneLogic)+ const { setDateRange, setDurationSelection, setSampleIndex, selectSpan } = useActions(tracingOperationSceneLogic)++ if (!spanName) {+ return (+ <SceneContent>+ <div className="flex flex-col items-center gap-1 py-16">+ <span>This link is missing an operation name.</span>+ <Link to={urls.tracing()}>Back to tracing</Link>+ </div>+ </SceneContent>+ )+ }++ const errorRate = operationStats && operationStats.count > 0 ? operationStats.error_count / operationStats.count : 0++ return (+ <SceneContent>+ <SceneTitleSection+ name={spanName}+ description={serviceName}+ resourceType={{+ type: 'tracing',+ }}+ forceBackTo={{+ key: 'tracing',+ name: 'Tracing',+ path: urls.tracing(),+ }}+ actions={+ <DateFilter+ dateFrom={dateRange.date_from}+ dateTo={dateRange.date_to}+ onChange={(date_from, date_to) => setDateRange({ date_from, date_to })}+ />+ }+ />+ {operationStats && (+ <div className="flex gap-8">+ <StatBlock label="Requests" value={humanFriendlyNumber(operationStats.count)} />+ <StatBlock+ label="Error rate"+ value={`${(errorRate * 100).toFixed(errorRate > 0 && errorRate < 0.01 ? 2 : 1)}%`}+ />+ <StatBlock label="p50" value={formatDuration(operationStats.p50_duration_nano)} />+ <StatBlock label="p95" value={formatDuration(operationStats.p95_duration_nano)} />+ <StatBlock label="p99" value={formatDuration(operationStats.p99_duration_nano)} />+ </div>+ )}+ <OperationHistogram+ data={histogramData}+ loading={rawHistogramLoading}+ selection={durationSelection}+ onSelect={setDurationSelection}+ onClear={() => setDurationSelection(null)}+ />+ <SceneDivider />+ {samples.length === 0 && samplesLoading ? (+ <div className="relative min-h-32">+ <SpinnerOverlay />+ </div>+ ) : samples.length > 0 ? (+ <>+ <div className="flex items-center gap-2">+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconChevronLeft />}+ onClick={() => setSampleIndex(sampleIndex - 1)}+ disabledReason={+ samplesLoading ? 'Loading samples…' : sampleIndex <= 0 ? 'First sample' : undefined+ }+ />+ <span className="text-sm whitespace-nowrap">+ {samples.length > 0 ? sampleIndex + 1 : 0} of {samples.length}+ {samplesHaveMore ? '+' : ''}+ </span>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconChevronRight />}+ onClick={() => setSampleIndex(sampleIndex + 1)}+ disabledReason={+ samplesLoading+ ? 'Loading samples…'+ : sampleIndex >= samples.length - 1+ ? 'Last sample'+ : undefined+ }+ />+ {currentSample && (+ <div className="flex items-center gap-2 ml-2 text-sm text-muted">+ <span>{humanFriendlyDetailedTime(currentSample.timestamp)}</span>+ <span className="font-mono">{formatDuration(currentSample.duration_nano)}</span>+ {currentSample.status_code === 2 && <LemonTag type="danger">Error</LemonTag>}+ </div>+ )}+ </div>+ <div className="relative min-h-96 flex-1">+ <TraceWaterfallView+ spans={sampleTraceSpans}+ selectedSpanId={selectedSpanId}+ onSpanSelect={selectSpan}+ />+ {sampleTraceSpansLoading && <SpinnerOverlay />}+ </div>+ </>+ ) : (+ <div className="flex flex-col items-center gap-1 py-8 text-muted">+ <span>No sampled traces in this range</span>+ {durationSelection && (+ <LemonButton size="small" type="secondary" onClick={() => setDurationSelection(null)}>+ Clear selection+ </LemonButton>+ )}+ </div>+ )}+ </SceneContent>+ )+}++export default TracingOperationScenediff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 05e0e56af931..2bcf676cca5f 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { router } from 'kea-router'import posthog from 'posthog-js'import { LemonBanner, LemonButton, LemonModal, LemonTabs, Link } from '@posthog/lemon-ui'@@ -10,6 +11,7 @@ import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'import { SceneExport } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneDivider } from '~/layout/scenes/components/SceneDivider'@@ -194,6 +196,7 @@ function TracingSceneContents(): JSX.Element {rows={aggregation.current}loading={aggregationLoading}windowMs={operationsWindowMs}+ onRowClick={(row) => router.actions.push(urls.tracingOperation(row.service_name, row.name))}/>) : (<>diff --git a/products/tracing/frontend/durationBuckets.test.ts b/products/tracing/frontend/durationBuckets.test.tsindex 612e8c24d63c..786a229b7fc4 100644--- a/products/tracing/frontend/durationBuckets.test.ts+++ b/products/tracing/frontend/durationBuckets.test.ts@@ -1,7 +1,9 @@import {+ bucketUpperBound,fillBucketSeries,formatBucketLabel,pivotDurationHistogram,+ selectionToDurationRange,snapDurationToBucket,visibleDurationRange,} from './durationBuckets'@@ -60,6 +62,32 @@ describe('durationBuckets', () => {expect(pivotDurationHistogram([], ['c1'])).toEqual({ data: [], bucketsNs: [], labels: [] })})+ it.each([+ [1, 2],+ [2, 5],+ [5, 10],+ [500 * MS, 1_000 * MS], // 500ms → 1s+ [1_000 * MS, 2_000 * MS],+ ])('bucketUpperBound(%i) → %i', (bucket, expected) => {+ expect(bucketUpperBound(bucket)).toBe(expected)+ })++ // Bucket b covers [b, nextBucket(b)) — an off-by-one here silently shifts which spans a+ // histogram drag-selection matches (the 5ms bar must mean [5ms, 10ms)).+ it.each<[number, number, { minNs: number; maxNs: number } | null]>([+ [0, 1, { minNs: 1 * MS, maxNs: 5 * MS }], // interior selection: max is the bucket after the last bar+ [2, 2, { minNs: 5 * MS, maxNs: 10 * MS }], // single bar+ [2, 3, { minNs: 5 * MS, maxNs: 20 * MS }], // ends on the last bar: upper edge extrapolated on the series+ [3, 99, { minNs: 10 * MS, maxNs: 20 * MS }], // out-of-range end clamps to the last bar+ ])('selectionToDurationRange over [1,2,5,10]ms maps [%i, %i] → %o', (startIndex, endIndex, expected) => {+ const bucketsNs = [1, 2, 5, 10].map((bucketMs) => bucketMs * MS)+ expect(selectionToDurationRange(bucketsNs, startIndex, endIndex)).toEqual(expected)+ })++ it('selectionToDurationRange returns null for an empty axis', () => {+ expect(selectionToDurationRange([], 0, 0)).toBeNull()+ })+it('visibleDurationRange orders min/max regardless of sort direction and clamps indices', () => {const durations = [900, 500, 100] // DESC-sorted listexpect(visibleDurationRange({ startIndex: 0, stopIndex: 2 }, durations)).toEqual({ minNs: 100, maxNs: 900 })diff --git a/products/tracing/frontend/durationBuckets.ts b/products/tracing/frontend/durationBuckets.tsindex 461697189d95..48c55300f358 100644--- a/products/tracing/frontend/durationBuckets.ts+++ b/products/tracing/frontend/durationBuckets.ts@@ -112,6 +112,33 @@ export function pivotDurationHistogram(return { data, bucketsNs, labels: bucketsNs.map(formatBucketLabel) }}+/** Exclusive upper edge of a 1-2-5 bucket — the next bucket on the series (1→2, 2→5, 5→10). */+export function bucketUpperBound(bucketNs: number): number {+ const decade = Math.pow(10, Math.floor(Math.log10(Math.max(bucketNs, 1))))+ const mantissa = bucketNs / decade+ return Math.round(mantissa < 2 ? 2 * decade : mantissa < 5 ? 5 * decade : 10 * decade)+}++/**+ * Duration range covered by an inclusive bar-index selection on the histogram axis.+ * Bucket b covers [b, nextBucket(b)), so the range's max is the bucket after the last selected+ * bar (extrapolated on the 1-2-5 series when the selection ends on the last bar).+ */+export function selectionToDurationRange(+ bucketsNs: number[],+ startIndex: number,+ endIndex: number+): { minNs: number; maxNs: number } | null {+ if (bucketsNs.length === 0) {+ return null+ }+ const start = Math.max(0, Math.min(startIndex, bucketsNs.length - 1))+ const end = Math.max(start, Math.min(endIndex, bucketsNs.length - 1))+ const minNs = bucketsNs[start]+ const maxNs = bucketsNs[end + 1] ?? bucketUpperBound(bucketsNs[end])+ return { minNs, maxNs }+}+/*** 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.diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex 5db5e6ddf019..5fa581da3ffd 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -223,7 +223,7 @@ export interface _TracingCountResponseApi {traceCount: number}-export interface _TracingTimeseriesQueryBodyApi {+export interface _TracingDurationHistogramQueryBodyApi {/** Date range for the query. Defaults to last hour. */dateRange?: _TracingDateRangeApi/** Filter by service names. */@@ -232,11 +232,13 @@ export interface _TracingTimeseriesQueryBodyApi {statusCodes?: number[]/** Property filters for the query. */filterGroup?: _SpanPropertyFilterApi[]+ /** When true (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions. */+ rootSpans?: boolean}-export interface _TracingTimeseriesRequestApi {- /** The sparkline / duration-histogram query to execute. */- query: _TracingTimeseriesQueryBodyApi+export interface _TracingDurationHistogramRequestApi {+ /** The duration-histogram query to execute. */+ query: _TracingDurationHistogramQueryBodyApi}export interface _HasSpansResponseApi {diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex f931c762b5e9..22b1ccafd67b 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -24,9 +24,9 @@ import type {_TracingAttributesResponseApi,_TracingCountRequestApi,_TracingCountResponseApi,+ _TracingDurationHistogramRequestApi,_TracingQueryRequestApi,_TracingSparklineRequestApi,- _TracingTimeseriesRequestApi,_TracingTraceRequestApi,_TracingTreeRequestApi,} from './api.schemas'@@ -135,14 +135,14 @@ export const getTracingSpansDurationHistogramCreateUrl = (projectId: string) =>export const tracingSpansDurationHistogramCreate = async (projectId: string,- _tracingTimeseriesRequestApi: _TracingTimeseriesRequestApi,+ _tracingDurationHistogramRequestApi: _TracingDurationHistogramRequestApi,options?: RequestInit): Promise<void> => {return apiMutator<void>(getTracingSpansDurationHistogramCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(_tracingTimeseriesRequestApi),+ body: JSON.stringify(_tracingDurationHistogramRequestApi),})}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 93555d8e32b8..558f70cddfbb 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -286,6 +286,7 @@ export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({})export const tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault = []+export const tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault = trueexport const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -357,8 +358,14 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec).default(tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),+ rootSpans: zod+ .boolean()+ .default(tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault)+ .describe(+ 'When true (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions.'+ ),})- .describe('The sparkline \/ duration-histogram query to execute.'),+ .describe('The duration-histogram query to execute.'),})export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []diff --git a/products/tracing/frontend/operationFilters.ts b/products/tracing/frontend/operationFilters.tsnew file mode 100644index 000000000000..b7557414c06f--- /dev/null+++ b/products/tracing/frontend/operationFilters.ts@@ -0,0 +1,43 @@+import {+ FilterLogicalOperator,+ PropertyFilterType,+ PropertyGroupFilter,+ PropertyOperator,+ SpanPropertyFilter,+} from '~/types'++export interface DurationRange {+ minNs: number+ maxNs: number+}++const NS_PER_MS = 1_000_000++/**+ * Filter group scoping a spans query to one operation, optionally to a duration range.+ * The span `duration` property filter's value unit is milliseconds — the backend translates+ * it to `duration_nano` (see translate_span_filter in backend/logic.py).+ */+export function operationFilterGroup(spanName: string, durationRange: DurationRange | null): PropertyGroupFilter {+ const values: SpanPropertyFilter[] = [+ { type: PropertyFilterType.Span, key: 'name', operator: PropertyOperator.Exact, value: [spanName] },+ ]+ if (durationRange) {+ values.push({+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.GreaterThanOrEqual,+ value: durationRange.minNs / NS_PER_MS,+ })+ values.push({+ type: PropertyFilterType.Span,+ key: 'duration',+ operator: PropertyOperator.LessThan,+ value: durationRange.maxNs / NS_PER_MS,+ })+ }+ return {+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values }],+ }+}diff --git a/products/tracing/frontend/tracingOperationSceneLogic.test.ts b/products/tracing/frontend/tracingOperationSceneLogic.test.tsnew file mode 100644index 000000000000..3e80f14ea5dd--- /dev/null+++ b/products/tracing/frontend/tracingOperationSceneLogic.test.ts@@ -0,0 +1,102 @@+import { router } from 'kea-router'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import { tracingOperationSceneLogic } from './tracingOperationSceneLogic'+import type { Span } from './types'++const createMockSample = (n: number): Span => ({+ uuid: `uuid-${n}`,+ trace_id: `trace-${n}`,+ span_id: `span-${n}`,+ parent_span_id: 'parent',+ name: 'db query',+ kind: 3,+ service_name: 'web',+ status_code: 1,+ timestamp: `2024-01-01T0${n}:00:00Z`,+ end_time: `2024-01-01T0${n}:00:01Z`,+ duration_nano: 1_000_000_000,+ is_root_span: false,+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+})++describe('tracingOperationSceneLogic', () => {+ let logic: ReturnType<typeof tracingOperationSceneLogic.build>+ let listSpansSpy: jest.SpyInstance+ let getTraceSpy: jest.SpyInstance++ beforeEach(async () => {+ initKeaTests()+ jest.spyOn(api.tracing, 'durationHistogram').mockResolvedValue({ results: [] })+ jest.spyOn(api.tracing, 'aggregate').mockResolvedValue({ results: [] })+ listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })+ getTraceSpy = jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({ results: [], hasMore: false })+ logic = tracingOperationSceneLogic({ serviceName: 'web', spanName: 'db query' })+ logic.mount()+ // Settle the mount-time fetches (these calls supersede them via the loader breakpoint),+ // so their empty results can't land mid-test and clobber seeded samples.+ await Promise.all([+ logic.asyncActions.fetchHistogram(),+ logic.asyncActions.fetchStats(),+ logic.asyncActions.fetchSamples(),+ ])+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('drag-selecting a duration range refetches samples scoped to the range and resets the pager', async () => {+ logic.actions.fetchSamplesSuccess([1, 2, 3, 4].map(createMockSample))+ logic.actions.setSampleIndex(3)++ logic.actions.setDurationSelection({ minNs: 5_000_000, maxNs: 10_000_000 })+ // The listener wiring dispatches the refetch synchronously, and the pager resets with it.+ expect(logic.values.samplesLoading).toBe(true)+ expect(logic.values.sampleIndex).toBe(0)++ await logic.asyncActions.fetchSamples()+ expect(listSpansSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({+ flatSpans: true,+ serviceNames: ['web'],+ filterGroup: {+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [+ { type: 'span', key: 'name', operator: 'exact', value: ['db query'] },+ // The span duration filter's unit is ms; the range above is 5–10ms in ns.+ { type: 'span', key: 'duration', operator: 'gte', value: 5 },+ { type: 'span', key: 'duration', operator: 'lt', value: 10 },+ ],+ },+ ],+ },+ })+ )+ })++ it('paging to another sample fetches its containing trace and anchors the waterfall on the sample span', async () => {+ logic.actions.fetchSamplesSuccess([1, 2].map(createMockSample))++ logic.actions.setSampleIndex(1)+ expect(logic.values.sampleTraceSpansLoading).toBe(true)++ await logic.asyncActions.fetchSampleTrace({ sample: logic.values.currentSample! })+ expect(getTraceSpy).toHaveBeenLastCalledWith('trace-2', expect.anything())+ expect(logic.values.selectedSpanId).toBe('span-2')+ })++ it('ignores a negative sample index restored from the URL', () => {+ router.actions.push('/tracing/operation', { sample: '-1' })+ expect(logic.values.sampleIndex).toBe(0)+ })+})diff --git a/products/tracing/frontend/tracingOperationSceneLogic.ts b/products/tracing/frontend/tracingOperationSceneLogic.tsnew file mode 100644index 000000000000..3b3799d3791a--- /dev/null+++ b/products/tracing/frontend/tracingOperationSceneLogic.ts@@ -0,0 +1,231 @@+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { dataColorVars } from 'lib/colors'++import { AggregatedSpanRow, DateRange } from '~/queries/schema/schema-general'++import { type DurationHistogramRow, pivotDurationHistogram, type TracingDurationHistogramData } from './durationBuckets'+import { type DurationRange, operationFilterGroup } from './operationFilters'+import { traceLookupDateRange } from './traceLinks'+import { DEFAULT_DATE_RANGE } from './tracingFiltersLogic'+import type { tracingOperationSceneLogicType } from './tracingOperationSceneLogicType'+import type { Span } from './types'++export interface TracingOperationSceneLogicProps {+ serviceName: string+ spanName: string+}++const SAMPLE_LIMIT = 100++export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([+ props({} as TracingOperationSceneLogicProps),+ key(({ serviceName, spanName }) => `${serviceName}//${spanName}`),+ path((key) => ['products', 'tracing', 'frontend', 'tracingOperationSceneLogic', key]),++ actions({+ setDateRange: (dateRange: DateRange) => ({ dateRange }),+ setDurationSelection: (selection: DurationRange | null) => ({ selection }),+ setSampleIndex: (index: number) => ({ index }),+ selectSpan: (spanId: string | null) => ({ spanId }),+ setSamplesHaveMore: (hasMore: boolean) => ({ hasMore }),+ }),++ loaders(({ props, values, actions }) => ({+ rawHistogram: [+ [] as DurationHistogramRow[],+ {+ fetchHistogram: async (_: void, breakpoint) => {+ await breakpoint(100)+ const response = await api.tracing.durationHistogram({+ dateRange: values.dateRange,+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, null),+ // Span-level: operations are often child spans, and the samples query+ // below is span-level too — both must count the same population.+ rootSpans: false,+ })+ breakpoint()+ return response.results+ },+ },+ ],+ samples: [+ [] as Span[],+ {+ fetchSamples: async (_: void, breakpoint) => {+ await breakpoint(100)+ const response = await api.tracing.listSpans({+ dateRange: values.dateRange,+ orderBy: 'timestamp',+ orderDirection: 'DESC',+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, values.durationSelection),+ flatSpans: true,+ limit: SAMPLE_LIMIT,+ })+ breakpoint()+ actions.setSamplesHaveMore(!!response.hasMore)+ return response.results as Span[]+ },+ },+ ],+ operationStats: [+ null as AggregatedSpanRow | null,+ {+ fetchStats: async (_: void, breakpoint) => {+ await breakpoint(100)+ const response = await api.tracing.aggregate({+ dateRange: values.dateRange,+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, null),+ })+ breakpoint()+ return response.results.find((row) => row.name === props.spanName) ?? null+ },+ },+ ],+ sampleTraceSpans: [+ [] as Span[],+ {+ fetchSampleTrace: async ({ sample }: { sample: Span }, breakpoint) => {+ await breakpoint(100)+ const response = await api.tracing.getTrace(sample.trace_id, {+ dateRange: traceLookupDateRange(sample.timestamp),+ })+ breakpoint()+ return response.results as Span[]+ },+ },+ ],+ })),++ reducers({+ dateRange: [DEFAULT_DATE_RANGE as DateRange, { setDateRange: (_, { dateRange }) => dateRange }],+ durationSelection: [null as DurationRange | null, { setDurationSelection: (_, { selection }) => selection }],+ sampleIndex: [+ 0,+ {+ setSampleIndex: (_, { index }) => index,+ setDurationSelection: () => 0,+ setDateRange: () => 0,+ },+ ],+ selectedSpanId: [null as string | null, { selectSpan: (_, { spanId }) => spanId }],+ samplesHaveMore: [false, { setSamplesHaveMore: (_, { hasMore }) => hasMore }],+ // A stale waterfall must not linger under a new (or empty) sample set.+ sampleTraceSpans: { fetchSamples: () => [] },+ }),++ selectors({+ serviceName: [() => [(_, props) => props.serviceName], (serviceName: string): string => serviceName],+ spanName: [() => [(_, props) => props.spanName], (spanName: string): string => spanName],+ histogramData: [+ (s) => [s.rawHistogram],+ (rows: DurationHistogramRow[]): TracingDurationHistogramData => pivotDurationHistogram(rows, dataColorVars),+ ],+ currentSample: [+ (s) => [s.samples, s.sampleIndex],+ (samples: Span[], sampleIndex: number): Span | null => samples[sampleIndex] ?? null,+ ],+ }),++ listeners(({ actions, values }) => ({+ setDurationSelection: () => {+ actions.fetchSamples()+ },+ setDateRange: () => {+ actions.fetchHistogram()+ actions.fetchSamples()+ actions.fetchStats()+ },+ fetchSamplesSuccess: ({ samples }) => {+ if (samples.length === 0) {+ actions.selectSpan(null)+ return+ }+ if (values.sampleIndex >= samples.length) {+ // A deep-linked or stale index past the new result set would render a blank sample.+ actions.setSampleIndex(0)+ return+ }+ if (values.currentSample) {+ actions.fetchSampleTrace({ sample: values.currentSample })+ }+ },+ setSampleIndex: () => {+ if (values.currentSample) {+ actions.fetchSampleTrace({ sample: values.currentSample })+ }+ },+ fetchSampleTraceSuccess: () => {+ // Anchor the waterfall on the operation's own span — for child operations the+ // sample sits deep in a larger trace and would otherwise open unfocused at the root.+ actions.selectSpan(values.currentSample?.span_id ?? null)+ },+ fetchHistogramFailure: ({ error }) => {+ lemonToast.error(`Failed to load latency distribution: ${error}`)+ },+ fetchSamplesFailure: ({ error }) => {+ lemonToast.error(`Failed to load sample traces: ${error}`)+ },+ fetchStatsFailure: ({ error }) => {+ lemonToast.error(`Failed to load operation stats: ${error}`)+ },+ fetchSampleTraceFailure: ({ error }) => {+ lemonToast.error(`Failed to load trace: ${error}`)+ },+ })),++ actionToUrl(({ values }) => {+ const withSelectionParams = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {+ const { min, max, sample, ...rest } = router.values.searchParams+ const params: Record<string, any> = { ...rest }+ if (values.durationSelection) {+ params.min = values.durationSelection.minNs+ params.max = values.durationSelection.maxNs+ }+ if (values.sampleIndex > 0) {+ params.sample = values.sampleIndex+ }+ return [router.values.location.pathname, params, router.values.hashParams, { replace: true }]+ }+ return {+ setDurationSelection: withSelectionParams,+ setSampleIndex: withSelectionParams,+ }+ }),++ urlToAction(({ actions, values }) => ({+ '/tracing/operation': (_, searchParams, __, { method }) => {+ if (method === 'REPLACE') {+ return // our own actionToUrl writes+ }+ const minNs = parseInt(String(searchParams.min), 10)+ const maxNs = parseInt(String(searchParams.max), 10)+ const selection = !isNaN(minNs) && !isNaN(maxNs) ? { minNs, maxNs } : null+ if (JSON.stringify(selection) !== JSON.stringify(values.durationSelection)) {+ actions.setDurationSelection(selection)+ }+ const sample = parseInt(String(searchParams.sample), 10)+ if (!isNaN(sample) && sample >= 0 && sample !== values.sampleIndex) {+ actions.setSampleIndex(sample)+ }+ },+ })),++ afterMount(({ actions, values }) => {+ actions.fetchHistogram()+ actions.fetchStats()+ // A deep link restores the selection via urlToAction, whose listener already fetches+ // samples — only fetch directly when mounting without one.+ if (!values.durationSelection) {+ actions.fetchSamples()+ }+ }),+])diff --git a/products/tracing/manifest.tsx b/products/tracing/manifest.tsxindex ee9e2d75109a..51da05964d94 100644--- a/products/tracing/manifest.tsx+++ b/products/tracing/manifest.tsx@@ -1,3 +1,5 @@+import { combineUrl } from 'kea-router'+import { FEATURE_FLAGS } from 'lib/constants'import { urls } from 'scenes/urls'@@ -16,13 +18,27 @@ export const manifest: ProductManifest = {description: 'Monitor and analyze distributed traces to understand service performance and debug issues.',iconType: 'tracing',},+ TracingOperation: {+ name: 'Operation',+ import: () => import('./frontend/TracingOperationScene'),+ projectBased: true,+ layout: 'app-container',+ activityScope: 'Tracing',+ description: 'Latency distribution and sample traces for a single operation.',+ iconType: 'tracing',+ },},routes: {'/tracing': ['Tracing', 'tracing'],+ '/tracing/operation': ['TracingOperation', 'tracingOperation'],},redirects: {},urls: {tracing: (): string => '/tracing',+ // Query params rather than path segments: span names ("GET /api/stats") contain slashes+ // and arbitrary characters that break path routing.+ tracingOperation: (serviceName: string, spanName: string): string =>+ combineUrl('/tracing/operation', { service: serviceName, name: spanName }).url,},fileSystemTypes: {},treeItemsNew: [],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 61f51b502823..682d267d96d9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55582,6 +55582,24 @@ export namespace Schemas {traceCount: number;}+ export interface _TracingDurationHistogramQueryBody {+ /** 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 (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions. */+ rootSpans?: boolean;+ }++ export interface _TracingDurationHistogramRequest {+ /** The duration-histogram query to execute. */+ query: _TracingDurationHistogramQueryBody;+ }+/*** * `timestamp` - timestamp* * `duration` - duration@@ -55657,22 +55675,6 @@ export namespace Schemas {query: _TracingSparklineQueryBody;}- export interface _TracingTimeseriesQueryBody {- /** 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[];- }-- export interface _TracingTimeseriesRequest {- /** The sparkline / duration-histogram query to execute. */- query: _TracingTimeseriesQueryBody;- }-export interface _TracingTraceRequest {/** Date range for the query. Defaults to last 24 hours. */dateRange?: _TracingDateRange;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 18099b9f5b19..761fa8376cc0 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -356,6 +356,7 @@ export const TracingSpansDurationHistogramCreateParams = /* @__PURE__ */ zod.obj})export const tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault = []+export const tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault = trueexport const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -427,8 +428,14 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec).default(tracingSpansDurationHistogramCreateBodyQueryOneFilterGroupDefault).describe('Property filters for the query.'),+ rootSpans: zod+ .boolean()+ .default(tracingSpansDurationHistogramCreateBodyQueryOneRootSpansDefault)+ .describe(+ 'When true (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions.'+ ),})- .describe('The sparkline / duration-histogram query to execute.'),+ .describe('The duration-histogram query to execute.'),})export const TracingSpansQueryCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.jsonindex 0ead90f92166..1f60e0a25dfd 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-duration-histogram.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 duration-histogram query to execute.","properties": {"dateRange": {"description": "Date range for the query. Defaults to last hour.",@@ -71,6 +71,11 @@},"type": "array"},+ "rootSpans": {+ "default": true,+ "description": "When true (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions.",+ "type": "boolean"+ },"serviceNames": {"description": "Filter by service names.","items": {