: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): metrics tab in the trace drawer (#91888)
Jimmy Zhu04d594fcff51
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 47eaee47f03e..a6d49f8027a4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -530,6 +530,7 @@ export const FEATURE_FLAGS = {TRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracingTRACING_LATENCY_HEATMAP: 'tracing-latency-heatmap', // owner: #team-apm — gates the latency-over-time heatmap chart in tracing+ TRACING_METRICS_TAB: 'tracing-metrics-tab', // owner: #team-apm — gates the Metrics tab (metrics correlated via exemplars) in the trace drawerTRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracingTRACING_SAVED_VIEWS: 'tracing-saved-views', // owner: #team-apm — gates saved views (saved filter sets) in tracingTRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsdiff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex b49397e2147b..be6759760f31 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -293,28 +293,32 @@ def list_metric_attribute_values(def list_metric_event_samples(*,team: Team,- metric_name: str,+ metric_name: str | None = None,date_from: dt.datetime,date_to: dt.datetime,trace_id: str | None = None,+ span_id: str | None = None,filters: Sequence[MetricFilter] = (),metric_type: MetricType | None = None,limit: int = 100,) -> list[MetricEventSample]:- """List individual metric emissions (the events model) for a metric,- newest first.+ """List individual metric emissions (the events model), newest first.Each sample carries its value, attributes, and trace linkage, so theSamples view can render raw rows and pivot to the trace behind any one.- Pass `trace_id` for the reverse pivot — every emission on a given trace.+ Pass `trace_id` for the reverse pivot — every emission on a given trace,+ across all metric names when `metric_name` is omitted (the tracing+ product's Metrics tab); `metric_name` or `trace_id` is required. Pass+ `span_id` (with `trace_id`) to narrow to one span's emissions, so the+ result stays exact even when the trace has more emissions than `limit`.`filters` and `metric_type` narrow the emissions to the same series a`run_metric_query` call with those arguments charts, so a filtered viewand its chart agree. Both are matched against the emission's series, soan emission whose series row hasn't been ingested yet drops out once- either is set.- Raises `ValueError` for an empty metric name, an inverted window, an- invalid regex filter, or an out-of-range limit; the presentation layer- surfaces these as 400s.+ either is set; both require `metric_name`.+ Raises `ValueError` for a missing metric name and trace id, an inverted+ window, an invalid regex filter, or an out-of-range limit; the+ presentation layer surfaces these as 400s."""runner = MetricEventSamplesQueryRunner(team=team,@@ -322,6 +326,7 @@ def list_metric_event_samples(date_from=date_from,date_to=date_to,trace_id=trace_id,+ span_id=span_id,filters=filters,metric_type=metric_type,limit=limit,diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.pyindex 4a5fe0c9abff..c6ca25dcdc8f 100644--- a/products/metrics/backend/metric_event_samples_query_runner.py+++ b/products/metrics/backend/metric_event_samples_query_runner.py@@ -62,26 +62,40 @@ class MetricEventSamplesQueryRunner:self,team: Team,*,- metric_name: str,+ metric_name: str | None = None,date_from: dt.datetime,date_to: dt.datetime,trace_id: str | None = None,+ span_id: str | None = None,filters: Sequence[MetricFilter] = (),metric_type: MetricType | None = None,limit: int = 100,) -> None:- if not metric_name:- raise ValueError("metric_name is required")+ # A trace-only query (the trace->metrics pivot) spans every metric name; it stays+ # bounded because trace_id carries a bloom-filter index (idx_trace_id_bf).+ if not metric_name and not trace_id:+ raise ValueError("metric_name or trace_id is required")+ if not metric_name and (filters or metric_type is not None):+ # Label filters and the type constraint scope series of ONE metric; without a+ # name there is no series set to scope, so honoring them would silently drop+ # every orphan emission across all metrics.+ raise ValueError("filters and metric_type require metric_name")if date_to <= date_from:raise ValueError("date_to must be after date_from")if limit <= 0 or limit > 1000:raise ValueError("limit must be in [1, 1000]")+ if span_id and not trace_id:+ # A span id is only unique within its trace, so an unanchored span filter+ # would silently mix emissions from unrelated traces.+ raise ValueError("span_id requires trace_id")+self.team = team- self.metric_name = metric_name+ self.metric_name = metric_name or ""self.date_from = date_fromself.date_to = date_toself.trace_id = _normalise_to_base64((trace_id or "").strip())+ self.span_id = _normalise_to_base64((span_id or "").strip())self.filters = tuple(filters)self.metric_type = metric_typeself.limit = limit@@ -124,9 +138,24 @@ class MetricEventSamplesQueryRunner:# trace is given, so the optional clause never has to be spliced into the# query string (which would collide with the HogQL placeholder braces) —# an empty {trace_id} matches every row. Samples are filtered + limited in- # the inner query, then left-joined to the deduped series for labels.+ # the CTE, then left-joined to the deduped series for labels. The series+ # side reads only the label sets of the matched samples: without that+ # bound, a query with no metric name (the trace pivot) would aggregate+ # every series in the project just to enrich at most {limit} rows.query = parse_select("""+ WITH matched_samples AS (+ SELECT team_id, metric_name, series_fingerprint, timestamp, value, count, trace_id, span_id+ FROM posthog.metric_samples+ WHERE ({metric_name} = '' OR metric_name = {metric_name})+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ AND ({trace_id} = '' OR trace_id = {trace_id})+ AND ({span_id} = '' OR span_id = {span_id})+ AND {series_scope}+ ORDER BY timestamp DESC+ LIMIT {limit}+ )SELECTs.timestamp,s.metric_name,@@ -141,17 +170,7 @@ class MetricEventSamplesQueryRunner:hex(tryBase64Decode(s.span_id)) AS span_id,ser.attributes,ser.resource_attributes- FROM (- SELECT team_id, metric_name, series_fingerprint, timestamp, value, count, trace_id, span_id- FROM posthog.metric_samples- WHERE metric_name = {metric_name}- AND timestamp >= {date_from}- AND timestamp < {date_to}- AND ({trace_id} = '' OR trace_id = {trace_id})- AND {series_scope}- ORDER BY timestamp DESC- LIMIT {limit}- ) AS s+ FROM matched_samples AS sLEFT JOIN (SELECTteam_id,@@ -165,7 +184,9 @@ class MetricEventSamplesQueryRunner:any(attributes) AS attributes,any(resource_attributes) AS resource_attributesFROM posthog.metric_series- WHERE metric_name = {metric_name}+ WHERE (metric_name, series_fingerprint) IN (+ SELECT metric_name, series_fingerprint FROM matched_samples+ )GROUP BY team_id, metric_name, series_fingerprint) AS serON s.team_id = ser.team_id@@ -178,6 +199,7 @@ class MetricEventSamplesQueryRunner:"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"trace_id": ast.Constant(value=self.trace_id),+ "span_id": ast.Constant(value=self.span_id),"series_scope": self._series_scope_expr(),"limit": ast.Constant(value=self.limit),},diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 4069eb6578a8..b1a740a9ff8b 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -532,8 +532,14 @@ class _MetricAttributeValuesResponseSerializer(serializers.Serializer):class _MetricSamplesBodySerializer(serializers.Serializer):metricName = serializers.CharField(+ required=False,+ allow_blank=True,max_length=255,- help_text="Exact metric name to list raw emissions for (e.g. 'http.server.duration').",+ help_text=(+ "Exact metric name to list raw emissions for (e.g. 'http.server.duration'). "+ "Omit to list emissions across all metric names — allowed only with traceId "+ "(the trace->metrics pivot)."+ ),)dateFrom = serializers.DateTimeField(help_text="Lower bound (inclusive) for the sample window. ISO 8601.",@@ -548,6 +554,12 @@ class _MetricSamplesBodySerializer(serializers.Serializer):max_length=255,help_text="Restrict to emissions on this trace (hex trace id, as the tracing product uses) — the reverse metric->trace pivot. Omit for all traces.",)+ spanId = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=255,+ help_text="Restrict to emissions recorded on this span (hex span id). Requires traceId, since a span id is only unique within its trace.",+ )metricType = serializers.ChoiceField(choices=[t.value for t in MetricType],required=False,@@ -568,6 +580,13 @@ class _MetricSamplesBodySerializer(serializers.Serializer):help_text="Max emissions to return, newest first. Defaults to 100, capped at 1000.",)+ def validate(self, attrs: dict) -> dict:+ if not attrs.get("metricName") and not attrs.get("traceId"):+ raise serializers.ValidationError("metricName or traceId is required.")+ if attrs.get("spanId") and not attrs.get("traceId"):+ raise serializers.ValidationError("spanId requires traceId.")+ return attrs+class _MetricSamplesRequestSerializer(serializers.Serializer):query = _MetricSamplesBodySerializer(help_text="The raw-emissions query to execute.")@@ -976,10 +995,11 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):try:samples = list_metric_event_samples(team=self.team,- metric_name=query_data["metricName"],+ metric_name=query_data.get("metricName") or None,date_from=query_data["dateFrom"],date_to=query_data.get("dateTo") or timezone.now(),trace_id=query_data.get("traceId") or None,+ span_id=query_data.get("spanId") or None,filters=filters,metric_type=MetricType(query_data["metricType"]) if query_data.get("metricType") else None,limit=query_data.get("limit") or 100,diff --git a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py b/products/metrics/backend/tests/test_metric_event_samples_query_runner.pyindex 668fc67e24a5..12dc2007cc94 100644--- a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py+++ b/products/metrics/backend/tests/test_metric_event_samples_query_runner.py@@ -105,6 +105,75 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):)self.assertEqual([s.trace_id for s in traced], [TRACE_A_HEX])+ def test_filters_by_span_id(self):+ # The span-scope toggle in the tracing drawer narrows server-side, so a span's+ # emissions stay exact even when the trace has more emissions than the limit.+ anchor = timezone.now().replace(microsecond=0)+ seed_metric_event(+ team_id=self.team.id, metric_name="m", points=[(anchor, 1.0)], trace_id=TRACE_A_B64, span_id=SPAN_A_B64+ )+ seed_metric_event(team_id=self.team.id, metric_name="n", points=[(anchor, 2.0)], trace_id=TRACE_A_B64)+ frm, to = anchor - dt.timedelta(hours=1), anchor + dt.timedelta(hours=1)++ spanned = list_metric_event_samples(+ team=self.team, date_from=frm, date_to=to, trace_id=TRACE_A_HEX, span_id=SPAN_A_HEX+ )+ self.assertEqual([(s.metric_name, s.span_id) for s in spanned], [("m", SPAN_A_HEX)])++ def test_span_id_requires_trace_id(self):+ now = timezone.now()+ with self.assertRaises(ValueError):+ MetricEventSamplesQueryRunner(+ team=self.team,+ metric_name="m",+ span_id=SPAN_A_HEX,+ date_from=now - dt.timedelta(hours=1),+ date_to=now,+ )++ @parameterized.expand(+ [+ ("filters", [MetricFilter(key="env", op=FilterOp.EQ, value="prod", scope=AttributeScope.ATTRIBUTE)], None),+ ("metric_type", [], MetricType.GAUGE),+ ]+ )+ def test_trace_only_query_rejects_series_constraints(self, _label, filters, metric_type):+ # Series constraints scope one metric's series; without a name there is no series+ # set to scope, so honoring them would silently drop every orphan emission.+ now = timezone.now()+ with self.assertRaises(ValueError):+ MetricEventSamplesQueryRunner(+ team=self.team,+ trace_id=TRACE_A_HEX,+ date_from=now - dt.timedelta(hours=1),+ date_to=now,+ filters=filters,+ metric_type=metric_type,+ )++ def test_trace_only_query_spans_metric_names(self):+ # The trace->metrics pivot (the tracing drawer's Metrics tab) lists every+ # emission on a trace without naming a metric — a regression back to a+ # required metric_name would blank that tab entirely.+ anchor = timezone.now().replace(microsecond=0)+ seed_metric_event(+ team_id=self.team.id, metric_name="http.duration", points=[(anchor, 1.0)], trace_id=TRACE_A_B64+ )+ seed_metric_event(team_id=self.team.id, metric_name="db.queries", points=[(anchor, 2.0)], trace_id=TRACE_A_B64)+ seed_metric_event(+ team_id=self.team.id, metric_name="http.duration", points=[(anchor, 3.0)], trace_id=TRACE_B_B64+ )++ samples = list_metric_event_samples(+ team=self.team,+ date_from=anchor - dt.timedelta(hours=1),+ date_to=anchor + dt.timedelta(hours=1),+ trace_id=TRACE_A_HEX,+ )++ self.assertEqual(sorted(s.metric_name for s in samples), ["db.queries", "http.duration"])+ self.assertEqual({s.trace_id for s in samples}, {TRACE_A_HEX})+def test_maps_fields_and_orders_newest_first(self):anchor = timezone.now().replace(microsecond=0)seed_metric_event(@@ -225,6 +294,28 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(results[0]["trace_id"], TRACE_A_HEX)self.assertEqual(results[0]["attributes"], {"region": "us"})+ def test_samples_api_trace_only_query(self):+ # Wiring guard for the trace->metrics pivot: metricName omitted, traceId given.+ anchor = timezone.now().replace(microsecond=0)+ seed_metric_event(+ team_id=self.team.id, metric_name="checkout.failed", points=[(anchor, 1.0)], trace_id=TRACE_A_B64+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/samples",+ data={+ "query": {+ "traceId": TRACE_A_HEX,+ "dateFrom": (anchor - dt.timedelta(hours=1)).isoformat(),+ "dateTo": (anchor + dt.timedelta(hours=1)).isoformat(),+ }+ },+ content_type="application/json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([r["metric_name"] for r in response.json()["results"]], ["checkout.failed"])+class TestMetricEventSampleFilters(ClickhouseTestMixin, APIBaseTest):CLASS_DATA_LEVEL_SETUP = Truediff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsxindex a60178099613..e826fe492321 100644--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx@@ -1,5 +1,4 @@import { useActions, useValues } from 'kea'-import { Fragment } from 'react'import { LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'@@ -10,30 +9,12 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { AccessControlLevel, AccessControlResourceType } from '~/types'-import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'import { traceUrl } from 'products/tracing/frontend/traceLinks'import { type MetricsAggregateRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { metricsViewerLogic } from './metricsViewerLogic'--function SampleAttributes({ sample }: { sample: _MetricEventSampleApi }): JSX.Element {- const entries = [...Object.entries(sample.attributes), ...Object.entries(sample.resource_attributes)]- if (!entries.length) {- return <div className="text-secondary text-xs p-2">No attributes on this emission.</div>- }- return (- <div className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 p-2 text-xs">- {/* Index-keyed: the same attribute key can appear in both the datapoint and resource maps. */}- {entries.map(([key, value], index) => (- <Fragment key={index}>- <span className="text-secondary font-mono">{key}</span>- <span className="font-mono break-all">{value}</span>- </Fragment>- ))}- </div>- )-}+import { SampleAttributes } from './SampleAttributes'function SamplesTab(): JSX.Element {const { samples, samplesLoading } = useValues(metricsSamplesLogic)diff --git a/products/metrics/frontend/components/SampleAttributes.tsx b/products/metrics/frontend/components/SampleAttributes.tsxnew file mode 100644index 000000000000..10d9124ca0e3--- /dev/null+++ b/products/metrics/frontend/components/SampleAttributes.tsx@@ -0,0 +1,23 @@+import { Fragment } from 'react'++import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'++// Expanded-row view of one emission's datapoint and resource attributes, shared by the+// metrics Samples panel and the tracing drawer's Metrics tab.+export function SampleAttributes({ sample }: { sample: _MetricEventSampleApi }): JSX.Element {+ const entries = [...Object.entries(sample.attributes), ...Object.entries(sample.resource_attributes)]+ if (!entries.length) {+ return <div className="text-secondary text-xs p-2">No attributes on this emission.</div>+ }+ return (+ <div className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 p-2 text-xs">+ {/* Index-keyed: the same attribute key can appear in both the datapoint and resource maps. */}+ {entries.map(([key, value], index) => (+ <Fragment key={index}>+ <span className="text-secondary font-mono">{key}</span>+ <span className="font-mono break-all">{value}</span>+ </Fragment>+ ))}+ </div>+ )+}diff --git a/products/metrics/frontend/components/TraceMetricSamples.tsx b/products/metrics/frontend/components/TraceMetricSamples.tsxnew file mode 100644index 000000000000..0715f1ad0c5e--- /dev/null+++ b/products/metrics/frontend/components/TraceMetricSamples.tsx@@ -0,0 +1,109 @@+import { useValues } from 'kea'++import { LemonBanner, LemonTable, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { metricUrl } from 'products/metrics/frontend/metricsLinks'++import { SampleAttributes } from './SampleAttributes'+import { traceMetricSamplesLogic } from './traceMetricSamplesLogic'++export interface TraceMetricSamplesProps {+ /** Hex trace id, as the tracing product uses. */+ traceId: string+ /** When set, only emissions recorded on this span (hex span id) are shown. */+ spanId?: string | null+ /** ISO window bounding the sample query, derived from the trace's timestamp. */+ dateFrom: string+ dateTo: string+}++// Metric emissions correlated with one trace (via OTel exemplars), each linking into the+// metrics viewer scoped to its metric — the reverse of the exemplar dots' metric->trace pivot.+export function TraceMetricSamples({ traceId, spanId, dateFrom, dateTo }: TraceMetricSamplesProps): JSX.Element {+ const { samples, samplesLoading, samplesError } = useValues(+ traceMetricSamplesLogic({ traceId, spanId, dateFrom, dateTo })+ )++ if (samplesError) {+ return (+ <LemonBanner type="error">+ Couldn't load the metrics for this trace. Close and reopen the trace to retry, and if it keeps happening+ contact support.+ </LemonBanner>+ )+ }++ return (+ <LemonTable+ dataSource={samples}+ loading={samplesLoading}+ size="small"+ rowKey={(sample, rowIndex) => `${rowIndex}-${sample.timestamp}-${sample.metric_name}`}+ emptyState={+ spanId+ ? 'No metrics were recorded on this span. Counters and histograms with exemplars link here automatically.'+ : 'No metrics were recorded on this trace. Counters and histograms with exemplars link here automatically.'+ }+ expandable={{+ expandedRowRender: (sample) => <SampleAttributes sample={sample} />,+ }}+ columns={[+ {+ title: 'Timestamp',+ key: 'timestamp',+ width: 0,+ render: (_, sample) => <TZLabel time={sample.timestamp} formatDate="MMM D" formatTime="HH:mm:ss" />,+ },+ {+ title: 'Metric',+ key: 'metric',+ render: (_, sample) => (+ <Tooltip title="Open this metric in the metrics viewer">+ <Link+ to={metricUrl({+ metricName: sample.metric_name,+ metricType: sample.metric_type || undefined,+ dateFrom,+ dateTo,+ })}+ className="font-mono"+ >+ {/* Link doesn't take data-attr; the span gives autocapture a named element. */}+ <span data-attr="tracing-metrics-open-metric">{sample.metric_name}</span>+ </Link>+ </Tooltip>+ ),+ },+ {+ title: 'Value',+ key: 'value',+ align: 'right',+ render: (_, sample) => (+ <Tooltip+ title={+ sample.count > 1+ ? `Distribution sum over ${sample.count} observations${sample.unit ? ` (${sample.unit})` : ''}`+ : sample.unit || undefined+ }+ >+ <span className="font-mono">{humanFriendlyNumber(sample.value, 2)}</span>+ </Tooltip>+ ),+ },+ {+ title: 'Service',+ key: 'service',+ render: (_, sample) =>+ sample.service_name ? (+ <span className="truncate max-w-40">{sample.service_name}</span>+ ) : (+ <span className="text-secondary">—</span>+ ),+ },+ ]}+ />+ )+}diff --git a/products/metrics/frontend/components/traceMetricSamplesLogic.test.ts b/products/metrics/frontend/components/traceMetricSamplesLogic.test.tsnew file mode 100644index 000000000000..0a71fe445ad4--- /dev/null+++ b/products/metrics/frontend/components/traceMetricSamplesLogic.test.ts@@ -0,0 +1,114 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'++import { traceMetricSamplesLogic } from './traceMetricSamplesLogic'++jest.mock('products/metrics/frontend/generated/api', () => ({+ ...jest.requireActual('products/metrics/frontend/generated/api'),+ metricsSamplesCreate: jest.fn(),+}))++const mockSamplesCreate = metricsSamplesCreate as jest.MockedFunction<typeof metricsSamplesCreate>++const TRACE_ID = '4EE9645D1C55A19919C83FDD657C88A4'++const SAMPLE = {+ timestamp: '2026-07-09T05:46:28.132600+00:00',+ metric_name: 'demo_checkout_duration_ms',+ metric_type: 'histogram',+ value: 970.97,+ count: 24,+ unit: 'ms',+ aggregation_temporality: 'cumulative',+ is_monotonic: false,+ service_name: 'checkout-demo',+ trace_id: TRACE_ID,+ span_id: 'F068A584A45A5EDA',+ attributes: { endpoint: '/api/checkout' },+ resource_attributes: { 'service.name': 'checkout-demo' },+}++const PROPS = {+ traceId: TRACE_ID,+ dateFrom: '2026-07-09T04:46:28.000Z',+ dateTo: '2026-07-09T06:46:28.000Z',+}++describe('traceMetricSamplesLogic', () => {+ let logic: ReturnType<typeof traceMetricSamplesLogic.build>++ const grantMetricsAccess = (level: AccessControlLevel | null): void => {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.Metrics]: level,+ },+ } as AppContext+ }++ beforeEach(() => {+ grantMetricsAccess(AccessControlLevel.Viewer)+ initKeaTests()+ mockSamplesCreate.mockReset()+ mockSamplesCreate.mockResolvedValue({ results: [SAMPLE] })+ })++ afterEach(() => {+ logic?.unmount()+ })++ // The trace->metrics pivot: the request names the trace and omits metricName, so the+ // response spans every metric the trace touched. A metricName sneaking in would+ // silently narrow the tab to one metric.+ it('loads emissions for the trace on mount, without a metric name', async () => {+ logic = traceMetricSamplesLogic(PROPS)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])++ expect(mockSamplesCreate).toHaveBeenCalledTimes(1)+ const [, request] = mockSamplesCreate.mock.calls[0]+ expect(request.query.traceId).toBe(TRACE_ID)+ expect(request.query).not.toHaveProperty('metricName')+ expect(request.query).not.toHaveProperty('spanId')+ expect(request.query.dateFrom).toBe(PROPS.dateFrom)+ expect(logic.values.samples).toEqual([SAMPLE])+ })++ // Span scope narrows server-side, so the result stays exact even when the trace has+ // more emissions than the request limit — a client-side filter over a capped response+ // would silently show "no metrics" for spans outside the newest page.+ it('passes the span id through to the request in span scope', async () => {+ logic = traceMetricSamplesLogic({ ...PROPS, spanId: SAMPLE.span_id })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])++ const [, request] = mockSamplesCreate.mock.calls[0]+ expect(request.query.spanId).toBe(SAMPLE.span_id)+ })++ it('skips the request without metrics view access', async () => {+ grantMetricsAccess(null)++ logic = traceMetricSamplesLogic(PROPS)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])++ expect(mockSamplesCreate).not.toHaveBeenCalled()+ expect(logic.values.samples).toEqual([])+ })++ it('flags the error state when the request fails', async () => {+ mockSamplesCreate.mockRejectedValue(new Error('boom'))++ logic = traceMetricSamplesLogic(PROPS)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSamplesFailure'])++ expect(logic.values.samplesError).toBe(true)+ })+})diff --git a/products/metrics/frontend/components/traceMetricSamplesLogic.ts b/products/metrics/frontend/components/traceMetricSamplesLogic.tsnew file mode 100644index 000000000000..d6deb1c5a5c1--- /dev/null+++ b/products/metrics/frontend/components/traceMetricSamplesLogic.ts@@ -0,0 +1,107 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'+import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'+import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'++const TRACE_SAMPLES_LIMIT = 100++export interface TraceMetricSamplesLogicProps {+ /** Hex trace id, as the tracing product uses. */+ traceId: string+ /** Narrow to emissions recorded on this span (hex span id), filtered server-side. */+ spanId?: string | null+ /** ISO lower bound for the sample window — the caller derives it from the trace's timestamp. */+ dateFrom: string+ /** ISO upper bound for the sample window. */+ dateTo: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceMetricSamplesLogicValues {+ currentTeamId: number | null // teamLogic+ samples: _MetricEventSampleApi[]+ samplesError: boolean+ samplesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceMetricSamplesLogicActions {+ loadSamples: () => any+ loadSamplesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSamplesSuccess: (+ samples: _MetricEventSampleApi[],+ payload?: any+ ) => {+ samples: _MetricEventSampleApi[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceMetricSamplesLogicMeta {+ key: string+}++export type traceMetricSamplesLogicType = MakeLogicType<+ traceMetricSamplesLogicValues,+ traceMetricSamplesLogicActions,+ TraceMetricSamplesLogicProps,+ traceMetricSamplesLogicMeta+>++// Metric emissions whose exemplar carries the given trace id — the trace->metrics pivot+// behind the tracing drawer's Metrics tab. Queried without a metric name, so it spans+// every metric the trace touched.+export const traceMetricSamplesLogic = kea<traceMetricSamplesLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'traceMetricSamplesLogic']),+ props({} as TraceMetricSamplesLogicProps),+ // Keyed by every query input: kea updates a mounted logic's props in place without+ // re-firing afterMount, so a scope or window change must mint a fresh instance to+ // refetch rather than silently serving the previous query's samples.+ key((props) => `${props.traceId}|${props.spanId ?? ''}|${props.dateFrom}|${props.dateTo}`),+ connect({ values: [teamLogic, ['currentTeamId']] }),+ loaders(({ values, props }) => ({+ samples: [+ [] as _MetricEventSampleApi[],+ {+ loadSamples: async (): Promise<_MetricEventSampleApi[]> => {+ if (!canViewMetrics()) {+ return []+ }+ const response = await metricsSamplesCreate(String(values.currentTeamId), {+ query: {+ traceId: props.traceId,+ ...(props.spanId ? { spanId: props.spanId } : {}),+ dateFrom: props.dateFrom,+ dateTo: props.dateTo,+ limit: TRACE_SAMPLES_LIMIT,+ },+ })+ return response.results+ },+ },+ ],+ })),+ reducers({+ samplesError: [+ false,+ {+ loadSamples: () => false,+ loadSamplesFailure: () => true,+ },+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadSamples()+ }),+])diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 5619f7b0d282..d9efaa176203 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -678,10 +678,10 @@ export interface _MetricQueryResponseApi {export interface _MetricSamplesBodyApi {/**- * Exact metric name to list raw emissions for (e.g. 'http.server.duration').+ * Exact metric name to list raw emissions for (e.g. 'http.server.duration'). Omit to list emissions across all metric names — allowed only with traceId (the trace->metrics pivot).* @maxLength 255*/- metricName: string+ metricName?: string/** Lower bound (inclusive) for the sample window. ISO 8601. */dateFrom: string/** Upper bound (exclusive) for the sample window. Defaults to now if omitted. */@@ -691,6 +691,11 @@ export interface _MetricSamplesBodyApi {* @maxLength 255*/traceId?: string+ /**+ * Restrict to emissions recorded on this span (hex span id). Requires traceId, since a span id is only unique within its trace.+ * @maxLength 255+ */+ spanId?: string/** Constrain the emissions to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, emissions of every type sharing the name are listed together. Pass the same value used for the chart so both describe the same series.** * `gauge` - gaugediff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.tsindex 444630691705..9ad64f679519 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -475,6 +475,8 @@ export const metricsSamplesCreateBodyQueryOneMetricNameMax = 255export const metricsSamplesCreateBodyQueryOneTraceIdMax = 255+export const metricsSamplesCreateBodyQueryOneSpanIdMax = 255+export const metricsSamplesCreateBodyQueryOneFiltersItemKeyMax = 255export const metricsSamplesCreateBodyQueryOneFiltersItemOpDefault = `eq`@@ -490,7 +492,10 @@ export const MetricsSamplesCreateBody = /* @__PURE__ */ zod.object({metricName: zod.string().max(metricsSamplesCreateBodyQueryOneMetricNameMax)- .describe("Exact metric name to list raw emissions for (e.g. 'http.server.duration')."),+ .optional()+ .describe(+ "Exact metric name to list raw emissions for (e.g. 'http.server.duration'). Omit to list emissions across all metric names — allowed only with traceId (the trace->metrics pivot)."+ ),dateFrom: zod.iso.datetime({ offset: true }).describe('Lower bound (inclusive) for the sample window. ISO 8601.'),@@ -505,6 +510,13 @@ export const MetricsSamplesCreateBody = /* @__PURE__ */ zod.object({.describe('Restrict to emissions on this trace (hex trace id, as the tracing product uses) — the reverse metric->trace pivot. Omit for all traces.'),+ spanId: zod+ .string()+ .max(metricsSamplesCreateBodyQueryOneSpanIdMax)+ .optional()+ .describe(+ 'Restrict to emissions recorded on this span (hex span id). Requires traceId, since a span id is only unique within its trace.'+ ),metricType: zod.union([zoddiff --git a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsxnew file mode 100644index 000000000000..aa27b2b646c8--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx@@ -0,0 +1,47 @@+import { fireEvent, render, screen } from '@testing-library/react'++import type { Span } from '../../types'+import { SpanMetricsTab } from './SpanMetricsTab'++// Capture the props the embedded TraceMetricSamples receives — the scope toggle's contract+// is which span filter (if any) reaches the samples component.+const capturedProps: { traceId: string; spanId?: string | null; dateFrom: string; dateTo: string }[] = []+jest.mock('products/metrics/frontend/components/TraceMetricSamples', () => ({+ TraceMetricSamples: (props: { traceId: string; spanId?: string | null; dateFrom: string; dateTo: string }) => {+ capturedProps.push(props)+ return null+ },+}))++const span = {+ trace_id: 'trace-abc',+ span_id: 'span-xyz',+ timestamp: '2026-06-11T08:00:00.000Z',+} as Span++describe('SpanMetricsTab', () => {+ beforeEach(() => {+ capturedProps.length = 0+ })++ it('defaults to whole-trace scope with a window around the span timestamp', () => {+ render(<SpanMetricsTab span={span} />)++ const props = capturedProps[capturedProps.length - 1]+ expect(props.traceId).toBe('trace-abc')+ expect(props.spanId).toBeNull()+ // ±1h around the span, same window the logs tab uses.+ expect(props.dateFrom).toBe('2026-06-11T07:00:00.000Z')+ expect(props.dateTo).toBe('2026-06-11T09:00:00.000Z')+ })++ it('narrows to the inspected span when the scope toggle flips', () => {+ render(<SpanMetricsTab span={span} />)++ // LemonSegmentedButton renders each option label more than once; any instance works.+ fireEvent.click(screen.getAllByText('This span')[0])++ const props = capturedProps[capturedProps.length - 1]+ expect(props.spanId).toBe('span-xyz')+ })+})diff --git a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsxnew file mode 100644index 000000000000..405ed4c77583--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx@@ -0,0 +1,50 @@+import { useState } from 'react'++import { LemonSegmentedButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { TraceMetricSamples } from 'products/metrics/frontend/components/TraceMetricSamples'++import { traceLookupDateRange } from '../../traceLinks'+import type { Span } from '../../types'++type TraceMetricScope = 'trace' | 'span'++// Metric emissions correlated to the whole trace (default) or the inspected span, via OTel+// exemplars. Trace scope is the default because a single span rarely carries an exemplar of+// its own; narrow to the span with the toggle when needed.+export function SpanMetricsTab({ span }: { span: Span }): JSX.Element {+ const [scope, setScope] = useState<TraceMetricScope>('trace')++ // The samples endpoint needs a concrete ISO window; ±1h around the trace covers any of+ // its emissions (same window cold trace loads use). Computed once per mount: the drawer+ // remounts this tab per trace, and pinning the window here keeps span selection from+ // shifting it a few milliseconds and refetching for nothing.+ const [dateRange] = useState(() =>+ traceLookupDateRange(dayjs(span.timestamp).isValid() ? span.timestamp : dayjs().toISOString())+ )++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <LemonSegmentedButton+ size="xsmall"+ value={scope}+ onChange={setScope}+ options={[+ { value: 'trace', label: 'Whole trace' },+ { value: 'span', label: 'This span' },+ ]}+ data-attr="tracing-metrics-scope"+ />+ </div>+ <TraceMetricSamples+ traceId={span.trace_id}+ spanId={scope === 'span' ? span.span_id : null}+ dateFrom={dateRange.date_from}+ dateTo={dateRange.date_to}+ />+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex bfa9805591c7..56ec930c1896 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -7,11 +7,15 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { JSONViewer } from 'lib/components/JSONViewer'import { Resizer } from 'lib/components/Resizer/Resizer'import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'+import { FEATURE_FLAGS } from 'lib/constants'import { IconLink } from 'lib/lemon-ui/icons'import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { cn } from 'lib/utils/css-classes'+import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'+import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'import { getQueryText } from '../../spanSummary'import { absoluteTraceUrl } from '../../traceLinks'@@ -19,9 +23,10 @@ import { buildServiceColorMap, formatDuration, TraceWaterfallView } from '../../import type { Span } from '../../types'import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'import { SpanLogsTab } from './SpanLogsTab'+import { SpanMetricsTab } from './SpanMetricsTab'import { SpanSummaryHeader } from './SpanSummaryHeader'-type InspectorTab = 'attributes' | 'query' | 'logs' | 'raw'+type InspectorTab = 'attributes' | 'query' | 'logs' | 'metrics' | 'raw'// Below this the inspector's content (the attribute KVP tables) stops being readable; clamp so a// drag can't crush it. The max is a flex `max-w` so a too-wide drag can't starve the waterfall.@@ -72,8 +77,14 @@ export function TraceDrawer({persistent: true,}const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))+ const { featureFlags } = useValues(featureFlagLogic)const [inspectorTab, setInspectorTab] = useState<InspectorTab>('attributes')+ // Metrics correlate to a trace via exemplars, so the tab only exists where the metrics+ // product does: its own flag, plus the metrics feature and view access.+ const showMetricsTab =+ !!featureFlags[FEATURE_FLAGS.TRACING_METRICS_TAB] && !!featureFlags[FEATURE_FLAGS.METRICS] && canViewMetrics()+// Resolve the inspected span outside render churn: a resize drag re-renders this component on// every mousemove, and these scans are O(spans) — memoize so they only run when data/selection change.const rootSpan = useMemo(() => spans.find((span) => span.is_root_span) ?? spans[0] ?? null, [spans])@@ -95,10 +106,14 @@ export function TraceDrawer({// Only DB spans carry a query; the Query tab appears only when one is present.const queryText = inspectedSpan ? getQueryText(inspectedSpan) : null- // The Query tab is conditional, so if it's the active tab and the user selects a span without a- // query, fall back to Attributes — otherwise activeKey would point at a tab LemonTabs has dropped- // and the inspector body would render blank. (Preference is preserved: a DB span re-shows Query.)- const activeInspectorTab: InspectorTab = inspectorTab === 'query' && !queryText ? 'attributes' : inspectorTab+ // The Query and Metrics tabs are conditional, so if the active tab disappears (a span without+ // a query, or the metrics gates turning off), fall back to Attributes — otherwise activeKey+ // would point at a tab LemonTabs has dropped and the inspector body would render blank.+ // (Preference is preserved: a DB span re-shows Query.)+ const activeInspectorTab: InspectorTab =+ (inspectorTab === 'query' && !queryText) || (inspectorTab === 'metrics' && !showMetricsTab)+ ? 'attributes'+ : inspectorTabreturn (<LemonDrawer@@ -195,6 +210,18 @@ export function TraceDrawer({// it) so we don't churn its logics or lose scroll.content: <SpanLogsTab key={inspectedSpan.trace_id} span={inspectedSpan} />,},+ // Conditional: needs the metrics product (flag + access) and its own flag.+ showMetricsTab+ ? {+ key: 'metrics',+ label: 'Metrics',+ // Keyed by trace like the Logs tab: a new trace remounts to reset+ // the scope toggle; selecting another span re-renders in place.+ content: (+ <SpanMetricsTab key={inspectedSpan.trace_id} span={inspectedSpan} />+ ),+ }+ : null,{key: 'raw',label: 'Raw',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8f29a6e6a51b..08cacb747f6c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -88884,10 +88884,10 @@ export namespace Schemas {export interface _MetricSamplesBody {/**- * Exact metric name to list raw emissions for (e.g. 'http.server.duration').+ * Exact metric name to list raw emissions for (e.g. 'http.server.duration'). Omit to list emissions across all metric names — allowed only with traceId (the trace->metrics pivot).* @maxLength 255*/- metricName: string;+ metricName?: string;/** Lower bound (inclusive) for the sample window. ISO 8601. */dateFrom: string;/** Upper bound (exclusive) for the sample window. Defaults to now if omitted. */@@ -88897,6 +88897,11 @@ export namespace Schemas {* @maxLength 255*/traceId?: string;+ /**+ * Restrict to emissions recorded on this span (hex span id). Requires traceId, since a span id is only unique within its trace.+ * @maxLength 255+ */+ spanId?: string;/** Constrain the emissions to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, emissions of every type sharing the name are listed together. Pass the same value used for the chart so both describe the same series.** * `gauge` - gauge