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): samples side panel with metric-to-trace pivot (#69574)

Daniel Viscac5c378d4a593
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b8992d87770e..1304ddfb1bdb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3763,6 +3763,10 @@ importers:
react-window:
specifier: '*'
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
products/notebooks:
dependencies:
diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.py
index 0d9b8bec1dee..62f62189db3c 100644
--- a/products/metrics/backend/metric_event_samples_query_runner.py
+++ b/products/metrics/backend/metric_event_samples_query_runner.py
@@ -10,8 +10,13 @@ first, then enriched with their series' labels; the series side is grouped so a
ReplacingMergeTree duplicate never multiplies a sample. metric_name comes from
the sample row itself, so an emission whose series row hasn't landed yet still
renders with its name (series-side fields fall back to empty).
+
+Trace/span ids are stored base64-encoded (as capture-logs writes exemplars) but
+cross the API boundary as hex, matching the tracing product's contract — so a
+sample's trace_id can be passed straight to the trace endpoint / trace URL.
"""
+import base64
import datetime as dt
from typing import Any
@@ -23,6 +28,19 @@ from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
+def _normalise_to_base64(value: str) -> str:
+ """Hex trace/span ids (the API form) become the base64 the storage holds.
+
+ No-op for values that aren't valid hex, mirroring the tracing product's
+ filter normalisation so both pivot directions accept the same id string.
+ """
+ try:
+ int(value, 16)
+ return base64.b64encode(bytes.fromhex(value)).decode()
+ except ValueError:
+ return value
+
+
class MetricEventSamplesQueryRunner:
def __init__(
self,
@@ -45,7 +63,7 @@ class MetricEventSamplesQueryRunner:
self.metric_name = metric_name
self.date_from = date_from
self.date_to = date_to
- self.trace_id = (trace_id or "").strip()
+ self.trace_id = _normalise_to_base64((trace_id or "").strip())
self.limit = limit
def run(self) -> list[dict[str, Any]]:
@@ -66,8 +84,8 @@ class MetricEventSamplesQueryRunner:
ser.aggregation_temporality,
ser.is_monotonic,
ser.service_name,
- s.trace_id,
- s.span_id,
+ hex(tryBase64Decode(s.trace_id)) AS trace_id,
+ hex(tryBase64Decode(s.span_id)) AS span_id,
ser.attributes,
ser.resource_attributes
FROM (
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 96bea766d210..2f253d3f3979 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -473,7 +473,7 @@ class _MetricSamplesBodySerializer(serializers.Serializer):
required=False,
allow_blank=True,
max_length=255,
- help_text="Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.",
+ 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.",
)
limit = serializers.IntegerField(
required=False,
@@ -507,9 +507,9 @@ class _MetricEventSampleSerializer(serializers.Serializer):
is_monotonic = serializers.BooleanField(help_text="True for monotonically increasing counters.")
service_name = serializers.CharField(help_text="Service that emitted the metric.")
trace_id = serializers.CharField(
- help_text="Trace this emission belongs to; empty if none. Use it to pivot to the trace.",
+ help_text="Trace this emission belongs to (hex, same form the tracing product uses); empty if none. Use it to pivot to the trace.",
)
- span_id = serializers.CharField(help_text="Span this emission belongs to; empty if none.")
+ span_id = serializers.CharField(help_text="Span this emission belongs to (hex); empty if none.")
attributes = serializers.DictField(
child=serializers.CharField(),
help_text="Per-emission attributes (high-cardinality labels on the data point).",
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.py
index 399e5d7ff607..ed1b034b5f76 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
@@ -1,3 +1,4 @@
+import base64
import datetime as dt
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -14,6 +15,16 @@ from products.metrics.backend.facade.api import list_metric_event_samples
from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
from products.metrics.backend.tests._seeder import seed_metric_event
+# Trace context is stored base64-encoded (as capture-logs writes it) but crosses the
+# API boundary as hex, matching the tracing product's contract. hex() in ClickHouse
+# is uppercase, hence .upper() on the expectations.
+TRACE_A_HEX = "4ee9645d1c55a19919c83fdd657c88a4".upper()
+TRACE_A_B64 = base64.b64encode(bytes.fromhex(TRACE_A_HEX)).decode()
+TRACE_B_HEX = "d1799cba743417aaa74137af8c4c1aff".upper()
+TRACE_B_B64 = base64.b64encode(bytes.fromhex(TRACE_B_HEX)).decode()
+SPAN_A_HEX = "f068a584a45a5eda".upper()
+SPAN_A_B64 = base64.b64encode(bytes.fromhex(SPAN_A_HEX)).decode()
+
class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
@@ -72,17 +83,25 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(samples[0].attributes, {"region": "us"})
def test_filters_by_trace_id(self):
+ # The pivot contract: storage holds base64 ids, but callers (the tracing
+ # product, the Samples UI) speak hex. A hex filter must match, and the
+ # returned ids must be hex — if either side regresses to base64, the
+ # metric->trace pivot silently returns nothing.
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")
- seed_metric_event(team_id=self.team.id, metric_name="m", points=[(anchor, 2.0)], trace_id="trace-b")
+ seed_metric_event(
+ team_id=self.team.id, metric_name="m", points=[(anchor, 1.0)], trace_id=TRACE_A_B64, attributes={"k": "a"}
+ )
+ seed_metric_event(
+ team_id=self.team.id, metric_name="m", points=[(anchor, 2.0)], trace_id=TRACE_B_B64, attributes={"k": "b"}
+ )
frm, to = anchor - dt.timedelta(hours=1), anchor + dt.timedelta(hours=1)
self.assertEqual(len(list_metric_event_samples(team=self.team, metric_name="m", date_from=frm, date_to=to)), 2)
traced = list_metric_event_samples(
- team=self.team, metric_name="m", date_from=frm, date_to=to, trace_id="trace-a"
+ team=self.team, metric_name="m", date_from=frm, date_to=to, trace_id=TRACE_A_HEX
)
- self.assertEqual([s.trace_id for s in traced], ["trace-a"])
+ self.assertEqual([s.trace_id for s in traced], [TRACE_A_HEX])
def test_maps_fields_and_orders_newest_first(self):
anchor = timezone.now().replace(microsecond=0)
@@ -93,8 +112,8 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
metric_type="histogram",
unit="ms",
service_name="api",
- trace_id="t1",
- span_id="s1",
+ trace_id=TRACE_A_B64,
+ span_id=SPAN_A_B64,
attributes={"route": "/x"},
resource_attributes={"service.version": "1.2"},
count=40,
@@ -124,9 +143,14 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(oldest.aggregation_temporality, "cumulative")
self.assertTrue(oldest.is_monotonic)
self.assertEqual(oldest.service_name, "api")
- self.assertEqual(oldest.trace_id, "t1")
+ self.assertEqual(oldest.trace_id, TRACE_A_HEX)
+ self.assertEqual(oldest.span_id, SPAN_A_HEX)
self.assertEqual(oldest.attributes, {"route": "/x"})
self.assertEqual(oldest.resource_attributes, {"service.version": "1.2"})
+ # An emission with no trace context must surface empty ids, not garbage
+ # from decoding an empty string.
+ self.assertEqual(samples[0].trace_id, "")
+ self.assertEqual(samples[0].span_id, "")
def test_orphan_sample_keeps_metric_name(self):
# A sample can outrun its series row (series-MV lag, or the rollout
@@ -176,7 +200,7 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
team_id=self.team.id,
metric_name="checkout.failed",
points=[(anchor, 1.0)],
- trace_id="trace-z",
+ trace_id=TRACE_A_B64,
attributes={"region": "us"},
)
@@ -196,5 +220,5 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
results = response.json()["results"]
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["metric_name"], "checkout.failed")
- self.assertEqual(results[0]["trace_id"], "trace-z")
+ self.assertEqual(results[0]["trace_id"], TRACE_A_HEX)
self.assertEqual(results[0]["attributes"], {"region": "us"})
diff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
new file mode 100644
index 000000000000..f89cfe24b2f5
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
@@ -0,0 +1,166 @@
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
+
+import { LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { getColorVar } from 'lib/colors'
+import { TZLabel } from 'lib/components/TZLabel'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+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 { 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>
+ )
+}
+
+function SamplesTab(): JSX.Element {
+ const { samples, samplesLoading } = useValues(metricsSamplesLogic)
+ const { hasMetricName } = useValues(metricsViewerLogic)
+
+ return (
+ <LemonTable
+ dataSource={samples}
+ loading={samplesLoading}
+ size="small"
+ rowKey={(sample, rowIndex) => `${rowIndex}-${sample.timestamp}-${sample.trace_id}`}
+ emptyState={
+ hasMetricName
+ ? 'No emissions for this metric in the selected range.'
+ : 'Pick a metric to see its raw emissions.'
+ }
+ expandable={{
+ expandedRowRender: (sample) => <SampleAttributes sample={sample} />,
+ }}
+ columns={[
+ {
+ title: 'Timestamp',
+ key: 'timestamp',
+ render: (_, sample) => <TZLabel time={sample.timestamp} formatDate="MMM D" formatTime="HH:mm:ss" />,
+ },
+ {
+ 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: 'Trace',
+ key: 'trace',
+ render: (_, sample) =>
+ sample.trace_id ? (
+ <Tooltip title="Open the trace this emission was recorded in">
+ <Link
+ to={traceUrl({
+ traceId: sample.trace_id,
+ spanId: sample.span_id || null,
+ ts: sample.timestamp,
+ })}
+ className="font-mono"
+ >
+ {sample.trace_id.slice(0, 8).toLowerCase()}
+ </Link>
+ </Tooltip>
+ ) : (
+ <span className="text-secondary">—</span>
+ ),
+ },
+ ]}
+ />
+ )
+}
+
+function AggregatesTab(): JSX.Element {
+ const { aggregateRows } = useValues(metricsSamplesLogic)
+ const { queryResultsLoading, hasMetricName } = useValues(metricsViewerLogic)
+
+ return (
+ <LemonTable
+ dataSource={aggregateRows}
+ loading={queryResultsLoading}
+ size="small"
+ rowKey={(row: MetricsAggregateRow) => row.name}
+ emptyState={
+ hasMetricName ? 'No series in the selected range.' : 'Pick a metric to see per-series aggregates.'
+ }
+ columns={[
+ {
+ title: 'Series',
+ key: 'series',
+ render: (_, row) => (
+ <span className="flex items-center gap-1.5">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ // Dynamic per-series colour can't be a Tailwind class.
+ style={{ backgroundColor: getColorVar(row.color) }}
+ />
+ <span className="truncate max-w-40" title={row.name}>
+ {row.name}
+ </span>
+ </span>
+ ),
+ },
+ {
+ title: 'Latest',
+ key: 'latest',
+ align: 'right',
+ render: (_, row) => <span className="font-mono">{humanFriendlyNumber(row.latest, 2)}</span>,
+ },
+ {
+ title: 'Total',
+ key: 'total',
+ align: 'right',
+ render: (_, row) => <span className="font-mono">{humanFriendlyNumber(row.total, 2)}</span>,
+ },
+ ]}
+ />
+ )
+}
+
+/** Side panel next to the chart: per-series aggregates, or the raw emissions
+ * behind the chart with a link to the trace each one was recorded in. */
+export function MetricsSamplesPanel(): JSX.Element {
+ const { activeTab } = useValues(metricsSamplesLogic)
+ const { setActiveTab } = useActions(metricsSamplesLogic)
+
+ return (
+ <div className="border rounded p-2 overflow-y-auto">
+ <LemonTabs<MetricsPanelTab>
+ size="small"
+ activeKey={activeTab}
+ onChange={setActiveTab}
+ tabs={[
+ { key: 'aggregates', label: 'Aggregates', content: <AggregatesTab /> },
+ { key: 'samples', label: 'Samples', content: <SamplesTab /> },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index d07703765acd..7f4db299c29b 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -27,6 +27,8 @@ import { DateMappingOption, FilterLogicalOperator, UniversalFiltersGroup, Univer
import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import { MetricsChartLegend } from './MetricsChartLegend'
+import { metricsSamplesLogic } from './metricsSamplesLogic'
+import { MetricsSamplesPanel } from './MetricsSamplesPanel'
import { MetricStatPanel } from './MetricStatPanel'
import {
LIVE_REFRESH_MS,
@@ -98,6 +100,9 @@ export const MetricsViewer = (): JSX.Element => {
// Keep the picker logic mounted alongside the viewer so the chosen metric's
// metric_type stays available for the aggregation hint after the dropdown closes.
const pickerLogic = useMountedLogic(metricNamePickerLogic())
+ // The side panel's logic listens to this viewer's filter changes; mounting it
+ // here keeps samples in sync even while the panel itself is off-screen.
+ useMountedLogic(metricsSamplesLogic())
const {
metricName,
aggregation,
@@ -270,44 +275,53 @@ export const MetricsViewer = (): JSX.Element => {
bordered
/>
</div>
- <div className="relative h-[360px] border rounded p-3">
- {!hasMetricName ? (
- <div className="h-full flex items-center justify-center text-secondary text-sm">
- Pick a metric to see its time series.
+ <div className="flex flex-col xl:flex-row gap-3 items-stretch">
+ <div className="flex-1 min-w-0">
+ <div className="relative h-[360px] border rounded p-3">
+ {!hasMetricName ? (
+ <div className="h-full flex items-center justify-center text-secondary text-sm">
+ Pick a metric to see its time series.
+ </div>
+ ) : queryError ? (
+ <div className="h-full flex items-center justify-center">
+ <LemonBanner type="error" className="max-w-md">
+ {queryError}
+ </LemonBanner>
+ </div>
+ ) : hasResults && viewMode === 'stat' ? (
+ <MetricStatPanel
+ title={metricName}
+ summary={statSummary}
+ aggregation={aggregation}
+ total={statTotal}
+ values={sparklineValues}
+ labels={sparklineLabels.map(renderLabel)}
+ anomaly={anomalyBadge}
+ />
+ ) : hasResults ? (
+ <Sparkline
+ type="line"
+ data={chartSeries}
+ labels={sparklineLabels}
+ className="w-full h-full"
+ withXScale={withXScale}
+ renderLabel={renderLabel}
+ />
+ ) : !queryResultsLoading ? (
+ <div className="h-full flex items-center justify-center text-secondary text-sm">
+ No data for this metric in the selected range.
+ </div>
+ ) : null}
+ {queryResultsLoading && <SpinnerOverlay />}
</div>
- ) : queryError ? (
- <div className="h-full flex items-center justify-center">
- <LemonBanner type="error" className="max-w-md">
- {queryError}
- </LemonBanner>
- </div>
- ) : hasResults && viewMode === 'stat' ? (
- <MetricStatPanel
- title={metricName}
- summary={statSummary}
- aggregation={aggregation}
- total={statTotal}
- values={sparklineValues}
- labels={sparklineLabels.map(renderLabel)}
- anomaly={anomalyBadge}
- />
- ) : hasResults ? (
- <Sparkline
- type="line"
- data={chartSeries}
- labels={sparklineLabels}
- className="w-full h-full"
- withXScale={withXScale}
- renderLabel={renderLabel}
- />
- ) : !queryResultsLoading ? (
- <div className="h-full flex items-center justify-center text-secondary text-sm">
- No data for this metric in the selected range.
+ {viewMode === 'chart' && hasResults && <MetricsChartLegend series={chartSeries} />}
+ </div>
+ {viewMode === 'chart' && hasMetricName && (
+ <div className="xl:w-[26rem] shrink-0 xl:max-h-[360px] flex flex-col">
+ <MetricsSamplesPanel />
</div>
- ) : null}
- {queryResultsLoading && <SpinnerOverlay />}
+ )}
</div>
- {viewMode === 'chart' && hasResults && <MetricsChartLegend series={chartSeries} />}
</div>
)
}
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.test.ts b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
new file mode 100644
index 000000000000..62c84ac46968
--- /dev/null
+++ b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
@@ -0,0 +1,93 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
+
+import { metricsSamplesLogic } from './metricsSamplesLogic'
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+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 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: '4EE9645D1C55A19919C83FDD657C88A4',
+ span_id: 'F068A584A45A5EDA',
+ attributes: { endpoint: '/api/checkout' },
+ resource_attributes: { 'service.name': 'checkout-demo' },
+}
+
+describe('metricsSamplesLogic', () => {
+ let logic: ReturnType<typeof metricsSamplesLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ mockSamplesCreate.mockReset()
+ mockSamplesCreate.mockResolvedValue({ results: [SAMPLE] })
+ metricsViewerLogic.mount()
+ logic = metricsSamplesLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ metricsViewerLogic.unmount()
+ })
+
+ // Regression: relative date strings ('-1h') sent to the API raw are a 400 —
+ // the loader must resolve them to ISO timestamps before the request.
+ it('activating the samples tab fetches emissions with resolved ISO dates', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+
+ logic.actions.setActiveTab('samples')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
+ const [, request] = mockSamplesCreate.mock.calls[0]
+ expect(request.query.metricName).toBe('demo_checkout_duration_ms')
+ expect(request.query.dateFrom).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ expect(logic.values.samples).toEqual([SAMPLE])
+ })
+
+ // Regression: firing the request with an empty metric name spams 400s on the
+ // empty state before a metric is picked.
+ it('does not call the API without a metric selected', async () => {
+ logic.actions.setActiveTab('samples')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+
+ expect(mockSamplesCreate).not.toHaveBeenCalled()
+ expect(logic.values.samples).toEqual([])
+ })
+
+ // Regression: samples going stale when the selected metric changes while the
+ // tab is open — and conversely, needless requests while the tab is hidden.
+ it('refetches on metric change only while the samples tab is active', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+ logic.actions.setActiveTab('samples')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
+
+ metricsViewerLogic.actions.setMetricName('demo_checkout_requests_total')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(2)
+ expect(mockSamplesCreate.mock.calls[1][1].query.metricName).toBe('demo_checkout_requests_total')
+
+ logic.actions.setActiveTab('aggregates')
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+ await expectLogic(logic).delay(10)
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
new file mode 100644
index 000000000000..f110e917d4c7
--- /dev/null
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -0,0 +1,113 @@
+import { actions, connect, kea, listeners, path, reducers, selectors } 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 type { metricsSamplesLogicType } from './metricsSamplesLogicType'
+import { formatSeriesName, seriesColor } from './metricsSeries'
+import { 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).
+export type MetricsPanelTab = 'aggregates' | 'samples'
+
+export const SAMPLES_LIMIT = 50
+
+// One row of the Aggregates tab: a series with its headline numbers.
+export interface MetricsAggregateRow {
+ name: string
+ color: string
+ latest: number
+ total: number
+}
+
+export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
+ path(['products', 'metrics', 'frontend', 'components', 'metricsSamplesLogic']),
+ connect(() => ({
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ metricsViewerLogic,
+ ['metricName', 'dateFrom', 'dateTo', 'queryResults'],
+ ],
+ actions: [metricsViewerLogic, ['setMetricName', 'setDateFrom', 'setDateTo']],
+ })),
+ actions({
+ setActiveTab: (activeTab: MetricsPanelTab) => ({ activeTab }),
+ }),
+ reducers({
+ activeTab: ['aggregates' as MetricsPanelTab, { setActiveTab: (_, { activeTab }) => activeTab }],
+ }),
+ loaders(({ values }) => ({
+ samples: [
+ [] as _MetricEventSampleApi[],
+ {
+ loadSamples: async (_, breakpoint) => {
+ const metricName = values.metricName.trim()
+ const dateFrom = resolveDate(values.dateFrom)
+ if (!metricName || !dateFrom) {
+ return []
+ }
+ await breakpoint(300)
+ const dateTo = resolveDate(values.dateTo) ?? undefined
+ const response = await metricsSamplesCreate(String(values.currentTeamId), {
+ query: {
+ metricName,
+ dateFrom,
+ ...(dateTo ? { dateTo } : {}),
+ limit: SAMPLES_LIMIT,
+ },
+ })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ })),
+ selectors({
+ // Rows for the Aggregates tab, derived from the chart's series so both
+ // views always describe the same query (colors match the chart legend).
+ aggregateRows: [
+ (s) => [s.queryResults, s.metricName],
+ (queryResults: MetricsViewerSeries[], metricName: string): MetricsAggregateRow[] =>
+ queryResults.map((series, index) => {
+ // Null points are gaps (unrepresentable buckets) — skip them
+ // rather than counting them as zero.
+ const values = series.points.map((point) => point.value).filter((value) => value !== null)
+ return {
+ name: formatSeriesName(series, metricName),
+ color: seriesColor(index),
+ latest: values.length ? values[values.length - 1] : 0,
+ total: values.reduce((sum, value) => sum + value, 0),
+ }
+ }),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setActiveTab: ({ activeTab }) => {
+ if (activeTab === 'samples') {
+ 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: () => {
+ if (values.activeTab === 'samples') {
+ actions.loadSamples({})
+ }
+ },
+ setDateFrom: () => {
+ if (values.activeTab === 'samples') {
+ actions.loadSamples({})
+ }
+ },
+ setDateTo: () => {
+ if (values.activeTab === 'samples') {
+ actions.loadSamples({})
+ }
+ },
+ })),
+])
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 64d6a4715013..286530e38760 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -122,7 +122,7 @@ const propertyFilterToMetricFilter = (filter: UniversalFilterValue): _MetricFilt
const flattenFilterValues = (group: UniversalFiltersGroup): UniversalFilterValue[] =>
group.values.flatMap((value) => (isUniversalGroupFilterLike(value) ? flattenFilterValues(value) : [value]))
-const resolveDate = (value: string | null | undefined): string | null => {
+export const resolveDate = (value: string | null | undefined): string | null => {
if (!value) {
return null
}
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 275057867dcf..63218feaa652 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -419,7 +419,7 @@ export interface _MetricSamplesBodyApi {
/** Upper bound (exclusive) for the sample window. Defaults to now if omitted. */
dateTo?: string
/**
- * Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.
+ * Restrict to emissions on this trace (hex trace id, as the tracing product uses) — the reverse metric->trace pivot. Omit for all traces.
* @maxLength 255
*/
traceId?: string
@@ -465,9 +465,9 @@ export interface _MetricEventSampleApi {
is_monotonic: boolean
/** Service that emitted the metric. */
service_name: string
- /** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */
+ /** Trace this emission belongs to (hex, same form the tracing product uses); empty if none. Use it to pivot to the trace. */
trace_id: string
- /** Span this emission belongs to; empty if none. */
+ /** Span this emission belongs to (hex); empty if none. */
span_id: string
/** Per-emission attributes (high-cardinality labels on the data point). */
attributes: _MetricEventSampleApiAttributes
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 835056c5879c..bc8c9bee031d 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -372,7 +372,7 @@ export const MetricsSamplesCreateBody = /* @__PURE__ */ zod.object({
.max(metricsSamplesCreateBodyQueryOneTraceIdMax)
.optional()
.describe(
- 'Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.'
+ 'Restrict to emissions on this trace (hex trace id, as the tracing product uses) — the reverse metric->trace pivot. Omit for all traces.'
),
limit: zod
.number()
diff --git a/products/metrics/package.json b/products/metrics/package.json
index 3cbb3af159c5..6cadda681e72 100644
--- a/products/metrics/package.json
+++ b/products/metrics/package.json
@@ -11,6 +11,9 @@
"kea-router": "catalog:",
"posthog-js": "catalog:"
},
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
"peerDependencies": {
"@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 23acd4ffeabe..b8f1e10b3ccf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58119,9 +58119,9 @@ export namespace Schemas {
is_monotonic: boolean;
/** Service that emitted the metric. */
service_name: string;
- /** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */
+ /** Trace this emission belongs to (hex, same form the tracing product uses); empty if none. Use it to pivot to the trace. */
trace_id: string;
- /** Span this emission belongs to; empty if none. */
+ /** Span this emission belongs to (hex); empty if none. */
span_id: string;
/** Per-emission attributes (high-cardinality labels on the data point). */
attributes: _MetricEventSampleAttributes;
@@ -58214,7 +58214,7 @@ export namespace Schemas {
/** Upper bound (exclusive) for the sample window. Defaults to now if omitted. */
dateTo?: string;
/**
- * Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.
+ * Restrict to emissions on this trace (hex trace id, as the tracing product uses) — the reverse metric->trace pivot. Omit for all traces.
* @maxLength 255
*/
traceId?: string;