Skip to content

: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.

feat(metrics): surface trace exemplars in investigations and on the viewer chart (#72116)

Daniel Visca95cd9442ea01
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index dd3131b502c9..50a9dee9ac64 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -44,6 +44,20 @@ export interface SparklineTimeSeries {
hoverColor?: string
}
+export interface SparklineMarker {
+ /**
+ * X position in the x-axis's own units: epoch ms (or a parseable date string) for a
+ * time scale, a label for a category scale.
+ */
+ xValue: number | string
+ /** Y position in data units. Omit to pin the marker to the bottom of the chart. */
+ yValue?: number
+ /** Color name from `vars.scss`. @default 'primary' */
+ color?: string
+ /** Makes the marker clickable (e.g. to open the trace behind an exemplar). */
+ onClick?: () => void
+}
+
export type AnyScaleOptions = ScaleOptions<'linear' | 'logarithmic' | 'time' | 'timeseries' | 'category'>
export interface SparklineProps {
@@ -79,6 +93,11 @@ export interface SparklineProps {
sortTooltipByCount?: boolean
/** Optional horizontal dashed reference lines (thresholds, goals, limits). */
referenceLines?: SparklineReferenceLine[]
+ /**
+ * Point markers drawn over the chart (e.g. trace exemplars). Hover shows the marker's
+ * label; a marker with `onClick` is clickable.
+ */
+ markers?: SparklineMarker[]
/** Format the per-series tooltip value. Defaults to `humanFriendlyNumber`. */
renderTooltipValue?: (value: number) => string
/**
@@ -157,6 +176,7 @@ export function Sparkline(props: SparklineProps): JSX.Element {
props.highlightedRange ||
props.incompleteBars?.indices?.length ||
props.referenceLines?.length ||
+ props.markers?.length ||
props.withXScale ||
props.withYScale
)
@@ -289,6 +309,7 @@ function LegacySparkline({
renderTooltipValue,
highlightedRange,
incompleteBars,
+ markers,
}: SparklineProps): JSX.Element {
const tooltipRef = useRef<HTMLDivElement | null>(null)
@@ -463,6 +484,39 @@ function LegacySparkline({
}
}
+ if (markers && markers.length > 0) {
+ markers.forEach((marker, i) => {
+ const markerColor = getColorVar(marker.color || 'primary')
+ annotations[`marker${i}`] = {
+ type: 'point',
+ xValue: marker.xValue,
+ // Markers don't participate in autoscaling, so an absent
+ // yValue pins to the bottom of whatever range the data set —
+ // exemplar-tick style, immune to out-of-range raw values.
+ yValue:
+ marker.yValue ?? ((ctx: { chart: Chart }) => ctx.chart.scales.y?.min ?? 0),
+ radius: 4,
+ backgroundColor: hexToRGBA(markerColor, 0.85),
+ borderColor: markerColor,
+ borderWidth: 1,
+ // enter/leave double as hover affordance for clickable markers.
+ enter: (ctx: { chart: Chart; element: { options: { radius: number } } }) => {
+ ctx.element.options.radius = 6
+ if (marker.onClick) {
+ ctx.chart.canvas.style.cursor = 'pointer'
+ }
+ return true
+ },
+ leave: (ctx: { chart: Chart; element: { options: { radius: number } } }) => {
+ ctx.element.options.radius = 4
+ ctx.chart.canvas.style.cursor = ''
+ return true
+ },
+ ...(marker.onClick ? { click: () => marker.onClick?.() } : {}),
+ }
+ })
+ }
+
return Object.keys(annotations).length > 0 ? { annotation: { annotations } } : {}
})(),
},
@@ -487,6 +541,7 @@ function LegacySparkline({
referenceLines,
highlightedRange,
incompleteBars,
+ markers,
],
})
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 10b7a60b551b..8b29acf67413 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -242,8 +242,8 @@ class InvestigationChartSpec:
@dataclass(frozen=True, slots=True)
class TraceExemplar:
"""A pointer from a metric sample into a concrete trace at the anomaly, for
- the metric->trace pivot. Populated by the trace-pivot primitive once the
- `metric_samples` table is live; empty until then.
+ the metric->trace pivot. Trace/span ids are hex, matching the tracing
+ product's contract, so they can be passed straight to a trace URL.
"""
trace_id: str
diff --git a/products/metrics/backend/investigation.py b/products/metrics/backend/investigation.py
index e5ff2d5462d8..5e7b7c54a908 100644
--- a/products/metrics/backend/investigation.py
+++ b/products/metrics/backend/investigation.py
@@ -1,14 +1,11 @@
"""Orchestrates a metric-symptom investigation into one structured result.
Composes the existing primitives — characterize the primary metric, check each
-companion metric over the same window, classify blast radius from the movers —
-into a single `InvestigationResult`. That result is the seam between investigate
-and display: the agent narrates it, the in-app explorer renders it, and the
-incident report serializes it, all from the same shape.
-
-The metric->trace pivot (`evidence.trace_exemplars`) is left empty until the
-`metric_samples` table lands; the seam is defined here so wiring it in later
-doesn't change the result shape.
+companion metric over the same window, classify blast radius from the movers,
+pull trace exemplars from the anomaly window — into a single
+`InvestigationResult`. That result is the seam between investigate and display:
+the agent narrates it, the in-app explorer renders it, and the incident report
+serializes it, all from the same shape.
"""
from __future__ import annotations
@@ -26,7 +23,9 @@ from products.metrics.backend.facade.contracts import (
InvestigationResult,
MetricAnomalyReport,
MetricFilter,
+ TraceExemplar,
)
+from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
# A companion counts as "moved with the symptom" once it changes by more than
# this fraction over the window (matches the eye test of "basically flat"
@@ -45,6 +44,14 @@ _DEFAULT_HISTOGRAM_QUANTILE = 0.95
# logs/traces pivot.
_SERVICE_KEYS = ("service_name", "service.name")
+# Enough exemplars to pivot from without bloating the serialized result the
+# agent and incident report carry around.
+_MAX_TRACE_EXEMPLARS = 5
+
+# Newest-first fetch size; only traced samples survive, so read more than the
+# cap to ride out untraced emissions interleaved in the window.
+_EXEMPLAR_SAMPLE_FETCH_LIMIT = 100
+
def investigate(
*,
@@ -98,7 +105,9 @@ def investigate(
service_name = _implicated_service(symptom)
evidence = InvestigationEvidence(
service_name=service_name,
- trace_exemplars=(), # filled by the trace-pivot primitive once samples land
+ trace_exemplars=_trace_exemplars(
+ team=team, metric_name=metric_name, anomaly_from=anomaly_from, anomaly_to=anomaly_to
+ ),
log_filter=_log_filter(service_name, symptom) if service_name else None,
)
chart_specs = _build_chart_specs(symptom, companion_verdicts, filters, quantile)
@@ -167,6 +176,40 @@ def _classify_blast_radius(symptom: MetricAnomalyReport) -> str:
return "shared"
+def _trace_exemplars(
+ *,
+ team: Team,
+ metric_name: str,
+ anomaly_from: dt.datetime,
+ anomaly_to: dt.datetime,
+) -> tuple[TraceExemplar, ...]:
+ """The newest traced emissions of the symptom metric inside the anomaly
+ window, capped — concrete traces to pivot into at the moment things broke.
+ Emissions without trace context are skipped; no samples means no pivot."""
+ rows = MetricEventSamplesQueryRunner(
+ team=team,
+ metric_name=metric_name,
+ date_from=anomaly_from,
+ date_to=anomaly_to,
+ limit=_EXEMPLAR_SAMPLE_FETCH_LIMIT,
+ ).run()
+ exemplars: list[TraceExemplar] = []
+ for row in rows:
+ if not row["trace_id"]:
+ continue
+ exemplars.append(
+ TraceExemplar(
+ trace_id=row["trace_id"],
+ span_id=row["span_id"],
+ timestamp=row["timestamp"],
+ value=row["value"],
+ )
+ )
+ if len(exemplars) == _MAX_TRACE_EXEMPLARS:
+ break
+ return tuple(exemplars)
+
+
def _implicated_service(symptom: MetricAnomalyReport) -> str | None:
for mover in symptom.top_movers:
if mover.key in _SERVICE_KEYS:
diff --git a/products/metrics/backend/tests/test_investigation.py b/products/metrics/backend/tests/test_investigation.py
index 5e475b88a141..974572a00a16 100644
--- a/products/metrics/backend/tests/test_investigation.py
+++ b/products/metrics/backend/tests/test_investigation.py
@@ -1,3 +1,4 @@
+import base64
import datetime as dt
from typing import Any
@@ -9,7 +10,15 @@ from posthog.clickhouse.client import sync_execute
from products.metrics.backend.facade.api import investigate, investigate_incident
from products.metrics.backend.facade.contracts import CompanionMetric, CompanionVerdict, IncidentContext
-from products.metrics.backend.tests._seeder import seed_metric
+from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event
+
+
+def _trace_hex(i: int) -> str:
+ return f"{i:032x}".upper()
+
+
+def _trace_b64(i: int) -> str:
+ return base64.b64encode(bytes.fromhex(_trace_hex(i))).decode()
class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
@@ -18,6 +27,8 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ sync_execute("TRUNCATE TABLE IF EXISTS metric_samples1")
+ sync_execute("TRUNCATE TABLE IF EXISTS metric_series1")
# 20-minute window: minutes 0-9 baseline, 10-19 anomaly (spike from 12).
self.start = (timezone.now() - dt.timedelta(hours=1)).replace(second=0, microsecond=0)
self.anomaly_from = self.start + dt.timedelta(minutes=10)
@@ -77,6 +88,8 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(self._verdict(result, "throughput").moved_with_symptom)
self.assertTrue(self._verdict(result, "error_rate").moved_with_symptom)
+ # No metric_samples rows exist -> the pivot stays empty rather than erroring.
+ self.assertEqual(result.evidence.trace_exemplars, ())
self.assertEqual(result.confidence, "high")
self.assertIn("logs-ingestion", result.narrative)
@@ -117,6 +130,57 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.blast_radius, "localized")
self.assertEqual(result.symptom.top_movers[0].label, "big")
+ def test_attaches_trace_exemplars_from_the_anomaly_window_only(self):
+ # If exemplar wiring regresses (window ignored, untraced samples included,
+ # or the cap dropped), an investigation would pivot into the wrong traces
+ # or bloat the result; nothing else exercises evidence.trace_exemplars.
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="ingestion_lag",
+ points=self._spike(10.0, 100.0),
+ service_name="logs-ingestion",
+ )
+ in_window = self.anomaly_from + dt.timedelta(minutes=2)
+ # Six traced samples inside the window (one more than the cap), each its
+ # own emission so each carries a distinct trace id.
+ for i in range(1, 7):
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="ingestion_lag",
+ points=[(in_window + dt.timedelta(seconds=i), 100.0 + i)],
+ trace_id=_trace_b64(i),
+ attributes={"pod": f"pod-{i}"},
+ )
+ # A traced sample before the window and an untraced one inside it must
+ # both be excluded.
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="ingestion_lag",
+ points=[(self.start + dt.timedelta(minutes=1), 10.0)],
+ trace_id=_trace_b64(99),
+ attributes={"pod": "baseline"},
+ )
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="ingestion_lag",
+ points=[(in_window, 100.0)],
+ attributes={"pod": "untraced"},
+ )
+
+ result = self._investigate()
+
+ self.assertEqual(len(result.evidence.trace_exemplars), 5)
+ # Newest first, so the cap keeps traces 6..2 and drops 1.
+ self.assertEqual(
+ [e.trace_id for e in result.evidence.trace_exemplars], [_trace_hex(i) for i in (6, 5, 4, 3, 2)]
+ )
+ newest = result.evidence.trace_exemplars[0]
+ self.assertEqual(newest.value, 106.0)
+ self.assertTrue(
+ newest.timestamp.startswith((in_window + dt.timedelta(seconds=6)).strftime("%Y-%m-%dT%H:%M:%S"))
+ )
+ self.assertNotIn(_trace_hex(99), [e.trace_id for e in result.evidence.trace_exemplars])
+
def test_flat_metric_yields_low_confidence(self):
seed_metric(
team_id=self.team.id, metric_name="ingestion_lag", points=self._flat(50.0), service_name="logs-ingestion"
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 1156d4a65666..34d1228277e4 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -1,4 +1,5 @@
import { useActions, useMountedLogic, useValues } from 'kea'
+import { router } from 'kea-router'
import { useCallback, useEffect, useMemo, useState } from 'react'
import {
@@ -15,7 +16,7 @@ import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboar
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { type MetricSummary } from 'lib/components/Metric/metricSummary'
-import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
+import { AnyScaleOptions, Sparkline, SparklineMarker } from 'lib/components/Sparkline'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
@@ -34,6 +35,8 @@ import {
UniversalFiltersGroupValue,
} from '~/types'
+import { traceUrl } from 'products/tracing/frontend/traceLinks'
+
import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'
import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
@@ -41,6 +44,7 @@ import { MetricsChartLegend } from './MetricsChartLegend'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import { MetricsSamplesPanel } from './MetricsSamplesPanel'
import { MetricStatPanel } from './MetricStatPanel'
+import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
import {
LIVE_REFRESH_MS,
METRIC_FILTER_OPERATOR_ALLOWLIST,
@@ -159,11 +163,41 @@ export const MetricsViewer = (): JSX.Element => {
closeAddToDashboardModal,
} = useActions(logic)
const { items: pickerItems } = useValues(pickerLogic)
+ const { traceExemplars } = useValues(metricsSamplesLogic)
+ const { exemplarDotClicked } = useActions(metricsUsageTrackingLogic)
const metricsViewerDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Metrics,
AccessControlLevel.Viewer
)
const insightEditorDisabledReason = getMetricsInsightEditorDisabledReason()
+ const tracingDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Tracing,
+ AccessControlLevel.Viewer
+ )
+
+ // Traced emissions as clickable dots along the bottom of the chart — the
+ // metric->trace pivot without opening the Samples tab. Skipped entirely when
+ // the user can't view traces, so a dot never leads to a dead end.
+ const exemplarMarkers: SparklineMarker[] = useMemo(
+ () =>
+ tracingDisabledReason
+ ? []
+ : traceExemplars.map((exemplar) => ({
+ xValue: dayjs(exemplar.timestamp).valueOf(),
+ color: 'primary',
+ onClick: () => {
+ exemplarDotClicked(!!exemplar.spanId)
+ router.actions.push(
+ traceUrl({
+ traceId: exemplar.traceId,
+ spanId: exemplar.spanId || null,
+ ts: exemplar.timestamp,
+ })
+ )
+ },
+ })),
+ [traceExemplars, tracingDisabledReason, exemplarDotClicked]
+ )
// Refetch the chart whenever any filter changes — the loader breakpoint debounces input.
useEffect(() => {
@@ -382,6 +416,7 @@ export const MetricsViewer = (): JSX.Element => {
className="w-full h-full"
withXScale={withXScale}
renderLabel={renderLabel}
+ markers={exemplarMarkers}
/>
) : !queryResultsLoading ? (
<div className="h-full flex items-center justify-center text-secondary text-sm">
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.test.ts b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
index c8be02aebb64..3ae4eaac946b 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.test.ts
+++ b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
@@ -31,6 +31,14 @@ const SAMPLE = {
resource_attributes: { 'service.name': 'checkout-demo' },
}
+const UNTRACED_SAMPLE = {
+ ...SAMPLE,
+ timestamp: '2026-07-09T05:47:28.132600+00:00',
+ value: 12.5,
+ trace_id: '',
+ span_id: '',
+}
+
describe('metricsSamplesLogic', () => {
let logic: ReturnType<typeof metricsSamplesLogic.build>
@@ -115,4 +123,39 @@ describe('metricsSamplesLogic', () => {
await expectLogic(logic).delay(10)
expect(mockSamplesCreate).toHaveBeenCalledTimes(2)
})
+
+ // Regression: exemplar dots on the chart silently vanish if untraced emissions
+ // leak into (or traced ones are dropped from) the derived exemplar list.
+ it('derives traceExemplars from traced samples only', async () => {
+ mockSamplesCreate.mockResolvedValue({ results: [SAMPLE, UNTRACED_SAMPLE] })
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+
+ logic.actions.setActiveTab('samples')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+
+ expect(logic.values.traceExemplars).toEqual([
+ {
+ timestamp: SAMPLE.timestamp,
+ value: SAMPLE.value,
+ traceId: SAMPLE.trace_id,
+ spanId: SAMPLE.span_id,
+ },
+ ])
+ })
+
+ // Regression: the chart's exemplar overlay starves (never fetches samples)
+ // unless the samples tab happens to be open — a chart redraw must refresh
+ // them in chart mode, and must not fire needless requests in stat mode.
+ it('refreshes samples on chart query success only in chart mode', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+
+ metricsViewerLogic.actions.fetchQueryResultsSuccess([])
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
+
+ metricsViewerLogic.actions.setViewMode('stat')
+ metricsViewerLogic.actions.fetchQueryResultsSuccess([])
+ await expectLogic(logic).delay(10)
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index b1d659dabbc6..470af55d867b 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -8,7 +8,7 @@ import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
import { formatSeriesName, seriesColor } from './metricsSeries'
-import { type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
+import { type MetricsViewMode, type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
// The side panel next to the chart: per-series aggregates, or the raw emissions
// behind the chart with their trace linkage (the metric->trace pivot).
@@ -24,21 +24,39 @@ export interface MetricsAggregateRow {
total: number
}
+// A traced emission rendered as a clickable exemplar dot on the viewer chart —
+// the metric->trace pivot straight from the time series.
+export interface MetricsTraceExemplar {
+ timestamp: string
+ value: number
+ traceId: string
+ spanId: string
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicValues {
dateFrom: string | null // metricsViewerLogic
dateTo: string | null // metricsViewerLogic
metricName: string // metricsViewerLogic
queryResults: MetricsViewerSeries[] // metricsViewerLogic
+ viewMode: MetricsViewMode // metricsViewerLogic
currentTeamId: number | null // teamLogic
activeTab: MetricsPanelTab
aggregateRows: MetricsAggregateRow[]
samples: _MetricEventSampleApi[]
samplesLoading: boolean
+ traceExemplars: MetricsTraceExemplar[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicActions {
+ fetchQueryResultsSuccess: (
+ queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],
+ payload?: any
+ ) => {
+ payload?: any
+ queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[]
+ } // metricsViewerLogic
setDateFrom: (dateFrom: string | null) => {
dateFrom: string | null
} // metricsViewerLogic
@@ -75,6 +93,7 @@ export interface metricsSamplesLogicMeta {
queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],
metricName: string
) => MetricsAggregateRow[]
+ traceExemplars: (samples: _MetricEventSampleApi[]) => MetricsTraceExemplar[]
}
}
@@ -92,9 +111,9 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
teamLogic,
['currentTeamId'],
metricsViewerLogic,
- ['metricName', 'dateFrom', 'dateTo', 'queryResults'],
+ ['metricName', 'dateFrom', 'dateTo', 'queryResults', 'viewMode'],
],
- actions: [metricsViewerLogic, ['setMetricName', 'setDateFrom', 'setDateTo']],
+ actions: [metricsViewerLogic, ['setMetricName', 'setDateFrom', 'setDateTo', 'fetchQueryResultsSuccess']],
})),
actions({
setActiveTab: (activeTab: MetricsPanelTab) => ({ activeTab }),
@@ -149,6 +168,19 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
}
}),
],
+ // Exemplar dots for the chart: only emissions that carry trace context.
+ traceExemplars: [
+ (s) => [s.samples],
+ (samples: _MetricEventSampleApi[]): MetricsTraceExemplar[] =>
+ samples
+ .filter((sample) => sample.trace_id)
+ .map((sample) => ({
+ timestamp: sample.timestamp,
+ value: sample.value,
+ traceId: sample.trace_id,
+ spanId: sample.span_id,
+ })),
+ ],
}),
listeners(({ actions, values }) => ({
setActiveTab: ({ activeTab }) => {
@@ -156,6 +188,13 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
actions.loadSamples({})
}
},
+ // The chart's exemplar overlay renders from these samples, so every chart
+ // redraw refreshes them; stat mode has no chart to dot, so skip it there.
+ fetchQueryResultsSuccess: () => {
+ if (values.viewMode === 'chart') {
+ actions.loadSamples({})
+ }
+ },
// The viewer's filters are the samples' filters: any change that redraws
// the chart refreshes the visible samples too, but only when they're shown.
setMetricName: () => {
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
index 8fa9336900cb..db219704cc69 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
@@ -92,6 +92,9 @@ export interface metricsUsageTrackingLogicActions {
viewMode: MetricsViewMode
} // metricsViewerLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
+ exemplarDotClicked: (hasSpanId: boolean) => {
+ hasSpanId: boolean
+ }
sampleRowExpanded: (sample: _MetricEventSampleApi) => {
sample: _MetricEventSampleApi
}
@@ -144,6 +147,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
// Component-only interactions with no source-logic action to listen to.
sampleRowExpanded: (sample: _MetricEventSampleApi) => ({ sample }),
tracePivotClicked: (sample: _MetricEventSampleApi) => ({ sample }),
+ exemplarDotClicked: (hasSpanId: boolean) => ({ hasSpanId }),
}),
listeners(({ actions, values, cache }) => ({
sceneTabChanged: ({ activeTab }) => {
@@ -254,5 +258,8 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
tracePivotClicked: ({ sample }) => {
posthog.capture('metrics trace pivot clicked', { has_span_id: !!sample.span_id })
},
+ exemplarDotClicked: ({ hasSpanId }) => {
+ posthog.capture('metrics exemplar dot clicked', { has_span_id: hasSpanId })
+ },
})),
])