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.

fix(metrics): scope the samples tab to the viewer's filters (#85598)

Frank Hamand8fe670e55f7a
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 84270022975b..654e38b076ea 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -7,6 +7,7 @@ so import-linter's strict-mode contract holds.
import math
import datetime as dt
+from collections.abc import Sequence
from typing import Any
from posthog.models import Team
@@ -24,7 +25,7 @@ from products.metrics.backend.facade.contracts import (
MetricQueryRequest,
MetricSeries,
)
-from products.metrics.backend.facade.enums import FilterOp, MetricAggregation
+from products.metrics.backend.facade.enums import FilterOp, MetricAggregation, MetricType
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
from products.metrics.backend.investigation import investigate as _investigate
@@ -275,6 +276,8 @@ def list_metric_event_samples(
date_from: dt.datetime,
date_to: dt.datetime,
trace_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,
@@ -283,8 +286,14 @@ def list_metric_event_samples(
Each sample carries its value, attributes, and trace linkage, so the
Samples 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.
- Raises `ValueError` for an empty metric name, an inverted window, or an
- out-of-range limit; the presentation layer surfaces these as 400s.
+ `filters` and `metric_type` narrow the emissions to the same series a
+ `run_metric_query` call with those arguments charts, so a filtered view
+ and its chart agree. Both are matched against the emission's series, so
+ an 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.
"""
runner = MetricEventSamplesQueryRunner(
team=team,
@@ -292,6 +301,8 @@ def list_metric_event_samples(
date_from=date_from,
date_to=date_to,
trace_id=trace_id,
+ filters=filters,
+ metric_type=metric_type,
limit=limit,
)
return [MetricEventSample(**row) for row in runner.run()]
diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.py
index 62f62189db3c..4a5fe0c9abff 100644
--- a/products/metrics/backend/metric_event_samples_query_runner.py
+++ b/products/metrics/backend/metric_event_samples_query_runner.py
@@ -18,15 +18,31 @@ sample's trace_id can be passed straight to the trace endpoint / trace URL.
import base64
import datetime as dt
+from collections.abc import Sequence
from typing import Any
from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
+from products.metrics.backend.facade.contracts import MetricFilter
+from products.metrics.backend.facade.enums import MetricType
+from products.metrics.backend.metric_query_runner import filters_expr, type_filter_expr
+
+# This runs on the ClickHouse cluster shared with the live logs/traces
+# products, so cap how much one request may read. Same budget the chart
+# queries get, and the same throw-on-overflow: a truncated sample list would
+# read as "these are the emissions" while silently hiding most of them.
+_QUERY_SETTINGS = HogQLGlobalSettings(
+ max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,
+ read_overflow_mode="throw",
+)
+
def _normalise_to_base64(value: str) -> str:
"""Hex trace/span ids (the API form) become the base64 the storage holds.
@@ -50,6 +66,8 @@ class MetricEventSamplesQueryRunner:
date_from: dt.datetime,
date_to: dt.datetime,
trace_id: str | None = None,
+ filters: Sequence[MetricFilter] = (),
+ metric_type: MetricType | None = None,
limit: int = 100,
) -> None:
if not metric_name:
@@ -64,8 +82,43 @@ class MetricEventSamplesQueryRunner:
self.date_from = date_from
self.date_to = date_to
self.trace_id = _normalise_to_base64((trace_id or "").strip())
+ self.filters = tuple(filters)
+ self.metric_type = metric_type
self.limit = limit
+ def _series_scope_expr(self) -> ast.Expr:
+ """Restrict the emissions to the series the caller's label filters select.
+
+ Labels live only on `metric_series`, so the predicate has to be an IN
+ over fingerprints, and it has to sit inside the sample subquery before
+ its LIMIT. Filtering after the LIMIT would take the newest `limit`
+ emissions across every series and then discard most of them, so a
+ filtered view would look almost empty while the chart shows plenty.
+
+ TRUE when nothing is pinned, which keeps the orphan case working: a
+ sample whose series row hasn't landed yet still renders. Once a filter
+ or a metric type is pinned there is no way to tell whether an orphan
+ belongs to the selection, so it drops out.
+ """
+ if not self.filters and self.metric_type is None:
+ return ast.Constant(value=True)
+ return parse_expr(
+ """
+ series_fingerprint IN (
+ SELECT series_fingerprint
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ AND {type_filter}
+ AND {filters}
+ )
+ """,
+ placeholders={
+ "metric_name": ast.Constant(value=self.metric_name),
+ "type_filter": type_filter_expr(self.metric_type.value if self.metric_type else None),
+ "filters": filters_expr(self.filters),
+ },
+ )
+
def run(self) -> list[dict[str, Any]]:
# The trace filter is an always-present predicate that is a no-op when no
# trace is given, so the optional clause never has to be spliced into the
@@ -95,6 +148,7 @@ class MetricEventSamplesQueryRunner:
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
@@ -124,6 +178,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),
+ "series_scope": self._series_scope_expr(),
"limit": ast.Constant(value=self.limit),
},
)
@@ -134,6 +189,7 @@ class MetricEventSamplesQueryRunner:
query=query,
team=self.team,
workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ settings=_QUERY_SETTINGS,
)
return [
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index e6ae672d3181..e4ab981a9744 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -227,7 +227,7 @@ def _filter_condition(filter: MetricFilter) -> ast.Expr:
raise ValueError(f"Unsupported filter op: {filter.op!r}")
-def _filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr:
+def filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr:
"""AND of all filter conditions; TRUE when there are none."""
if not filters:
return ast.Constant(value=True)
@@ -237,6 +237,18 @@ def _filters_expr(filters: Sequence[MetricFilter]) -> ast.Expr:
return ast.And(exprs=conditions)
+def type_filter_expr(metric_type: str | None) -> ast.Expr:
+ """Constrains rows to one metric type. A name can exist as several
+ types (a counter and a gauge); their series are distinct and must not
+ blend into one aggregate. TRUE when no type was requested.
+
+ Both `metrics` and `metric_series` name the column `metric_type`, so the
+ same expression works against either table."""
+ if metric_type is None:
+ return ast.Constant(value=True)
+ return parse_expr("metric_type = {metric_type}", placeholders={"metric_type": ast.Constant(value=metric_type)})
+
+
class MetricQueryRunner:
def __init__(
self,
@@ -375,14 +387,7 @@ class MetricQueryRunner:
query.group_by.append(ast.Field(chain=[f"group_{index}"]))
def _type_filter_expr(self) -> ast.Expr:
- """Constrains rows to one metric type. A name can exist as several
- types (a counter and a gauge); their series are distinct and must not
- blend into one aggregate. TRUE when no type was requested."""
- if self.metric_type is None:
- return ast.Constant(value=True)
- return parse_expr(
- "metric_type = {metric_type}", placeholders={"metric_type": ast.Constant(value=self.metric_type)}
- )
+ return type_filter_expr(self.metric_type)
def _build_simple_query(self) -> ast.SelectQuery:
# `metrics` is only registered under the `posthog.` HogQL namespace
@@ -408,7 +413,7 @@ class MetricQueryRunner:
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
- "filters": _filters_expr(self.filters),
+ "filters": filters_expr(self.filters),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
@@ -484,7 +489,7 @@ class MetricQueryRunner:
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
- "filters": _filters_expr(self.filters),
+ "filters": filters_expr(self.filters),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
@@ -550,7 +555,7 @@ class MetricQueryRunner:
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
- "filters": _filters_expr(self.filters),
+ "filters": filters_expr(self.filters),
"type_filter": self._type_filter_expr(),
"row_limit": ast.Constant(value=_ROW_LIMIT),
},
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 95958333627b..679735ea836b 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -495,6 +495,18 @@ 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.",
)
+ metricType = serializers.ChoiceField(
+ choices=[t.value for t in MetricType],
+ required=False,
+ allow_null=True,
+ help_text="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.",
+ )
+ filters = _MetricFilterSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Label predicates ANDed together, matched against each emission's series. Pass the same filters used for the chart so the emissions listed are the ones behind it.",
+ )
limit = serializers.IntegerField(
required=False,
default=100,
@@ -721,6 +733,10 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
body.is_valid(raise_exception=True)
query_data = body.validated_data["query"]
+ filters = tuple(
+ MetricFilter(key=f["key"], op=FilterOp(f["op"]), value=f["value"], scope=AttributeScope(f["scope"]))
+ for f in query_data.get("filters") or []
+ )
try:
samples = list_metric_event_samples(
team=self.team,
@@ -728,6 +744,8 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
date_from=query_data["dateFrom"],
date_to=query_data.get("dateTo") or timezone.now(),
trace_id=query_data.get("traceId") or None,
+ filters=filters,
+ metric_type=MetricType(query_data["metricType"]) if query_data.get("metricType") else None,
limit=query_data.get("limit") or 100,
)
except ValueError as exc:
@@ -736,7 +754,11 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
report_user_action(
request.user,
"metrics samples listed",
- {"sample_count": len(samples), "has_trace_filter": bool(query_data.get("traceId"))},
+ {
+ "sample_count": len(samples),
+ "has_trace_filter": bool(query_data.get("traceId")),
+ "filter_count": len(filters),
+ },
team=self.team,
request=request,
)
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 ed1b034b5f76..668fc67e24a5 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
@@ -12,6 +12,8 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from products.metrics.backend.facade.api import list_metric_event_samples
+from products.metrics.backend.facade.contracts import MetricFilter
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricType
from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
from products.metrics.backend.tests._seeder import seed_metric_event
@@ -222,3 +224,129 @@ class TestMetricEventSamplesQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["metric_name"], "checkout.failed")
self.assertEqual(results[0]["trace_id"], TRACE_A_HEX)
self.assertEqual(results[0]["attributes"], {"region": "us"})
+
+
+class TestMetricEventSampleFilters(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metric_samples1")
+ sync_execute("TRUNCATE TABLE IF EXISTS metric_series1")
+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)
+ self.anchor = timezone.now().replace(microsecond=0)
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=5), 1.0)],
+ service_name="api",
+ attributes={"env": "prod", "path": "/api"},
+ resource_attributes={"k8s.pod.name": "web-1"},
+ )
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=5), 10.0)],
+ service_name="web",
+ attributes={"env": "dev", "path": "/web"},
+ )
+
+ def _values(
+ self,
+ filters: tuple[MetricFilter, ...] = (),
+ metric_type: MetricType | None = None,
+ limit: int = 100,
+ ) -> list[float]:
+ return [
+ sample.value
+ for sample in list_metric_event_samples(
+ team=self.team,
+ metric_name="req",
+ date_from=self.anchor - dt.timedelta(hours=1),
+ date_to=self.anchor + dt.timedelta(hours=1),
+ filters=filters,
+ metric_type=metric_type,
+ limit=limit,
+ )
+ ]
+
+ @parameterized.expand(
+ [
+ ("eq_attribute", MetricFilter(key="env", op=FilterOp.EQ, value="prod"), [1.0]),
+ (
+ "eq_resource_scope",
+ MetricFilter(key="k8s.pod.name", op=FilterOp.EQ, value="web-1", scope=AttributeScope.RESOURCE),
+ [1.0],
+ ),
+ ("eq_service_name_column", MetricFilter(key="service.name", op=FilterOp.EQ, value="web"), [10.0]),
+ (
+ "neq_matches_series_lacking_key",
+ MetricFilter(key="k8s.pod.name", op=FilterOp.NEQ, value="web-1"),
+ [10.0],
+ ),
+ ]
+ )
+ def test_single_filter(self, _label, filter, expected_values):
+ # The chart reads labels off `metrics1`, where `attributes` is an ALIAS that
+ # strips the type tag; here they come off `metric_series`, where the map is
+ # real and `service_name` is its own column. Same filter expressions, two
+ # storage shapes, so both need covering.
+ self.assertEqual(self._values((filter,)), expected_values)
+
+ def test_filter_applies_before_the_limit(self):
+ # Newer emissions from the series the filter excludes. Filtering after the
+ # LIMIT would take these three, drop them all, and return nothing.
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=minutes), 100.0) for minutes in (1, 2, 3)],
+ service_name="web",
+ attributes={"env": "dev", "path": "/web"},
+ )
+
+ self.assertEqual(self._values((MetricFilter(key="env", op=FilterOp.EQ, value="prod"),), limit=1), [1.0])
+
+ def test_filter_excludes_a_sample_whose_series_is_missing(self):
+ # A sample can outrun its series row, and there is then no label set to
+ # match, so it drops out of a filtered result. The predicate below matches
+ # both real series, which pins the exclusion on the missing series rather
+ # than on the filter itself.
+ sync_execute(
+ "INSERT INTO metric_samples1 (team_id, metric_name, series_fingerprint, timestamp, value) "
+ "VALUES (%(team_id)s, 'req', 42, %(ts)s, 7.0)",
+ {"team_id": self.team.id, "ts": self.anchor.strftime("%Y-%m-%d %H:%M:%S.%f")},
+ )
+
+ self.assertIn(7.0, self._values())
+ self.assertNotIn(7.0, self._values((MetricFilter(key="env", op=FilterOp.NEQ, value="absent"),)))
+
+ def test_metric_type_isolates_same_named_series(self):
+ seed_metric_event(
+ team_id=self.team.id,
+ metric_name="req",
+ points=[(self.anchor - dt.timedelta(minutes=5), 99.0)],
+ metric_type="gauge",
+ service_name="gauge-source",
+ attributes={"env": "prod", "path": "/api"},
+ )
+
+ self.assertEqual(self._values(metric_type=MetricType.GAUGE), [99.0])
+ self.assertEqual(sorted(self._values(metric_type=MetricType.SUM)), [1.0, 10.0])
+
+ def test_filters_and_metric_type_via_api(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/samples",
+ data={
+ "query": {
+ "metricName": "req",
+ "dateFrom": (self.anchor - dt.timedelta(hours=1)).isoformat(),
+ "dateTo": (self.anchor + dt.timedelta(hours=1)).isoformat(),
+ "metricType": "sum",
+ "filters": [{"key": "k8s.pod.name", "op": "eq", "value": "web-1", "scope": "resource"}],
+ }
+ },
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual([result["value"] for result in response.json()["results"]], [1.0])
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.test.ts b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
index 3ae4eaac946b..df841e62ac35 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.test.ts
+++ b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
@@ -1,7 +1,16 @@
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
+import {
+ AccessControlLevel,
+ AccessControlResourceType,
+ AppContext,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+ UniversalFiltersGroupValue,
+} from '~/types'
import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
@@ -31,6 +40,18 @@ const SAMPLE = {
resource_attributes: { 'service.name': 'checkout-demo' },
}
+const filterGroupWith = (filters: Record<string, any>[]): UniversalFiltersGroup => ({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: filters.map(
+ (filter) => ({ type: PropertyFilterType.MetricAttribute, ...filter }) as UniversalFiltersGroupValue
+ ),
+ },
+ ],
+})
+
const UNTRACED_SAMPLE = {
...SAMPLE,
timestamp: '2026-07-09T05:47:28.132600+00:00',
@@ -124,6 +145,46 @@ describe('metricsSamplesLogic', () => {
expect(mockSamplesCreate).toHaveBeenCalledTimes(2)
})
+ // Regression: the panel listing emissions the chart above it excludes, because
+ // the request went out with only the metric name and date range.
+ it('scopes the request to the viewer filter bar and the picked metric type', async () => {
+ metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
+ metricsViewerLogic.actions.setSelectedMetricType('histogram')
+ metricsViewerLogic.actions.setFilterGroup(
+ filterGroupWith([{ key: 'env', operator: PropertyOperator.Exact, value: ['prod'] }])
+ )
+
+ logic.actions.setActiveTab('samples')
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+
+ const [, request] = mockSamplesCreate.mock.calls[0]
+ expect(request.query.filters).toEqual([{ key: 'env', op: 'eq', value: 'prod' }])
+ expect(request.query.metricType).toBe('histogram')
+ })
+
+ // Regression: samples going stale when a filter changes while the tab is open,
+ // and conversely needless requests while the tab is hidden.
+ it('refetches on filter 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.setFilterGroup(
+ filterGroupWith([{ key: 'env', operator: PropertyOperator.Exact, value: ['prod'] }])
+ )
+ await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
+ expect(mockSamplesCreate).toHaveBeenCalledTimes(2)
+ expect(mockSamplesCreate.mock.calls[1][1].query.filters).toEqual([{ key: 'env', op: 'eq', value: 'prod' }])
+
+ logic.actions.setActiveTab('aggregates')
+ metricsViewerLogic.actions.setFilterGroup(
+ filterGroupWith([{ key: 'env', operator: PropertyOperator.Exact, value: ['dev'] }])
+ )
+ 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 () => {
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index 470af55d867b..6309f52190d8 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -3,8 +3,14 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
+import { UniversalFiltersGroup } from '~/types'
+
import { metricsSamplesCreate } from 'products/metrics/frontend/generated/api'
-import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'
+import type {
+ _MetricEventSampleApi,
+ _MetricFilterApi,
+ OtelMetricTypeEnumApi,
+} from 'products/metrics/frontend/generated/api.schemas'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
import { formatSeriesName, seriesColor } from './metricsSeries'
@@ -38,7 +44,9 @@ export interface metricsSamplesLogicValues {
dateFrom: string | null // metricsViewerLogic
dateTo: string | null // metricsViewerLogic
metricName: string // metricsViewerLogic
+ queryFilters: _MetricFilterApi[] // metricsViewerLogic
queryResults: MetricsViewerSeries[] // metricsViewerLogic
+ selectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogic
viewMode: MetricsViewMode // metricsViewerLogic
currentTeamId: number | null // teamLogic
activeTab: MetricsPanelTab
@@ -63,9 +71,15 @@ export interface metricsSamplesLogicActions {
setDateTo: (dateTo: string | null) => {
dateTo: string | null
} // metricsViewerLogic
+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
+ filterGroup: UniversalFiltersGroup
+ } // metricsViewerLogic
setMetricName: (metricName: string) => {
metricName: string
} // metricsViewerLogic
+ setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
+ metricType: OtelMetricTypeEnumApi | null
+ } // metricsViewerLogic
loadSamples: (_: any) => any
loadSamplesFailure: (
error: string,
@@ -111,9 +125,19 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
teamLogic,
['currentTeamId'],
metricsViewerLogic,
- ['metricName', 'dateFrom', 'dateTo', 'queryResults', 'viewMode'],
+ ['metricName', 'dateFrom', 'dateTo', 'queryFilters', 'selectedMetricType', 'queryResults', 'viewMode'],
+ ],
+ actions: [
+ metricsViewerLogic,
+ [
+ 'setMetricName',
+ 'setDateFrom',
+ 'setDateTo',
+ 'setFilterGroup',
+ 'setSelectedMetricType',
+ 'fetchQueryResultsSuccess',
+ ],
],
- actions: [metricsViewerLogic, ['setMetricName', 'setDateFrom', 'setDateTo', 'fetchQueryResultsSuccess']],
})),
actions({
setActiveTab: (activeTab: MetricsPanelTab) => ({ activeTab }),
@@ -141,6 +165,8 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
metricName,
dateFrom,
...(dateTo ? { dateTo } : {}),
+ ...(values.selectedMetricType ? { metricType: values.selectedMetricType } : {}),
+ ...(values.queryFilters.length ? { filters: values.queryFilters } : {}),
limit: SAMPLES_LIMIT,
},
})
@@ -182,35 +208,34 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
})),
],
}),
- listeners(({ actions, values }) => ({
- setActiveTab: ({ activeTab }) => {
- if (activeTab === 'samples') {
- 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({})
- }
- },
+ listeners(({ actions, values }) => {
// 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: () => {
+ const reloadWhenShown = (): void => {
if (values.activeTab === 'samples') {
actions.loadSamples({})
}
- },
- setDateFrom: () => {
- if (values.activeTab === 'samples') {
- actions.loadSamples({})
- }
- },
- setDateTo: () => {
- if (values.activeTab === 'samples') {
- actions.loadSamples({})
- }
- },
- })),
+ }
+ return {
+ setActiveTab: ({ activeTab }) => {
+ if (activeTab === 'samples') {
+ 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({})
+ }
+ },
+ setMetricName: reloadWhenShown,
+ setDateFrom: reloadWhenShown,
+ setDateTo: reloadWhenShown,
+ setFilterGroup: reloadWhenShown,
+ // The viewer pins the type in its own setMetricName listener, so without
+ // this a metric switch can load samples pinned to the previous type.
+ setSelectedMetricType: reloadWhenShown,
+ }
+ }),
])
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 9c61d3aa3d03..cecff4c65249 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -456,6 +456,16 @@ export interface _MetricSamplesBodyApi {
* @maxLength 255
*/
traceId?: 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
+ * * `sum` - sum
+ * * `histogram` - histogram
+ * * `exponential_histogram` - exponential_histogram
+ * * `summary` - summary */
+ metricType?: OtelMetricTypeEnumApi | null
+ /** Label predicates ANDed together, matched against each emission's series. Pass the same filters used for the chart so the emissions listed are the ones behind it. */
+ filters?: _MetricFilterApi[]
/**
* Max emissions to return, newest first. Defaults to 100, capped at 1000.
* @minimum 1
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index eb08ba7fbbc5..e1ec2507a61b 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -376,6 +376,12 @@ export const metricsSamplesCreateBodyQueryOneMetricNameMax = 255
export const metricsSamplesCreateBodyQueryOneTraceIdMax = 255
+export const metricsSamplesCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsSamplesCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsSamplesCreateBodyQueryOneFiltersItemValueMax = 1024
+
+export const metricsSamplesCreateBodyQueryOneFiltersItemScopeDefault = `auto`
export const metricsSamplesCreateBodyQueryOneLimitDefault = 100
export const metricsSamplesCreateBodyQueryOneLimitMax = 1000
@@ -400,6 +406,52 @@ 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.'
),
+ metricType: zod
+ .union([
+ zod
+ .enum(['gauge', 'sum', 'histogram', 'exponential_histogram', 'summary'])
+ .describe(
+ '\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ '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.\n\n\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary'
+ ),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsSamplesCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex')
+ .default(metricsSamplesCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'\/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .max(metricsSamplesCreateBodyQueryOneFiltersItemValueMax)
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto')
+ .default(metricsSamplesCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe(
+ "Label predicates ANDed together, matched against each emission's series. Pass the same filters used for the chart so the emissions listed are the ones behind it."
+ ),
limit: zod
.number()
.min(1)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4ad01ffc6e6e..8f4415a0b881 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -83237,6 +83237,16 @@ export namespace Schemas {
* @maxLength 255
*/
traceId?: 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
+ * * `sum` - sum
+ * * `histogram` - histogram
+ * * `exponential_histogram` - exponential_histogram
+ * * `summary` - summary */
+ metricType?: OtelMetricTypeEnum | null;
+ /** Label predicates ANDed together, matched against each emission's series. Pass the same filters used for the chart so the emissions listed are the ones behind it. */
+ filters?: _MetricFilter[];
/**
* Max emissions to return, newest first. Defaults to 100, capped at 1000.
* @minimum 1