: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(metrics): add metric_events Samples endpoint (#66196)
Daniel Visca01bb8a2fbf0a
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 6a33ea4c3be3..2dad1314a2be 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -13,6 +13,7 @@ from posthog.models import Teamfrom products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomalyfrom products.metrics.backend.facade.contracts import (MetricAnomalyReport,+ MetricEventSample,MetricFilter,MetricPoint,MetricQueryClause,@@ -22,6 +23,7 @@ from products.metrics.backend.facade.contracts import (from products.metrics.backend.facade.enums import MetricAggregationfrom products.metrics.backend.formula import evaluate, parse_formulafrom products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics+from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunnerfrom products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunnerfrom products.metrics.backend.metric_query_runner import MetricQueryRunner@@ -197,6 +199,35 @@ def list_metric_names(return runner.run()+def list_metric_event_samples(+ *,+ team: Team,+ metric_name: str,+ date_from: dt.datetime,+ date_to: dt.datetime,+ trace_id: str | None = None,+ limit: int = 100,+) -> list[MetricEventSample]:+ """List individual metric emissions (the events model) for a metric,+ newest first.++ 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.+ """+ runner = MetricEventSamplesQueryRunner(+ team=team,+ metric_name=metric_name,+ date_from=date_from,+ date_to=date_to,+ trace_id=trace_id,+ limit=limit,+ )+ return [MetricEventSample(**row) for row in runner.run()]++def characterize_metric_anomaly(*,team: Team,diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex 0ad915b63e80..5e094a1f6ad4 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -157,3 +157,22 @@ class MetricAnomalyReport:onset_time: str | Nonetop_movers: tuple[MetricAnomalyDimension, ...]series: MetricSeries+++@dataclass(frozen=True, slots=True)+class MetricEventSample:+ """A single raw metric emission: one `metric_samples` row enriched with its+ `metric_series` labels. Backs the Samples view and the metric->trace pivot.+ Distinct from `MetricSeries`, which is aggregated at query time.+ """++ timestamp: str # ISO 8601+ metric_name: str+ metric_type: str # OTel type: gauge | sum | histogram | summary | exponential_histogram+ value: float+ unit: str+ service_name: str+ trace_id: str+ span_id: str+ attributes: dict[str, str]+ resource_attributes: dict[str, str]diff --git a/products/metrics/backend/metric_event_samples_query_runner.py b/products/metrics/backend/metric_event_samples_query_runner.pynew file mode 100644index 000000000000..dbf953e36170--- /dev/null+++ b/products/metrics/backend/metric_event_samples_query_runner.py@@ -0,0 +1,128 @@+"""Raw metric emissions for a metric, from the metric_samples/metric_series split.++Unlike `MetricQueryRunner` (which aggregates `metrics1` into a time series), this+returns individual emissions — value, attributes, and the trace linkage — newest+first. It backs the Samples view and the metric->trace pivot.++Joins `posthog.metric_samples` (the tiny hot rows) to `posthog.metric_series`+(the deduped label set) on `series_fingerprint`. Samples are filtered + limited+first, then enriched with their series' labels; the series side is grouped so a+ReplacingMergeTree duplicate never multiplies a sample.+"""++import datetime as dt+from typing import Any++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.models import Team+++class MetricEventSamplesQueryRunner:+ def __init__(+ self,+ team: Team,+ *,+ metric_name: str,+ date_from: dt.datetime,+ date_to: dt.datetime,+ trace_id: str | None = None,+ limit: int = 100,+ ) -> None:+ if not metric_name:+ raise ValueError("metric_name is required")+ 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]")++ self.team = team+ self.metric_name = metric_name+ self.date_from = date_from+ self.date_to = date_to+ self.trace_id = (trace_id or "").strip()+ self.limit = limit++ 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+ # 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.+ query = parse_select(+ """+ SELECT+ s.timestamp,+ ser.metric_name,+ ser.metric_type,+ s.value,+ ser.unit,+ ser.service_name,+ s.trace_id,+ s.span_id,+ ser.attributes,+ ser.resource_attributes+ FROM (+ SELECT team_id, metric_name, series_fingerprint, timestamp, value, 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})+ ORDER BY timestamp DESC+ LIMIT {limit}+ ) AS s+ LEFT JOIN (+ SELECT+ team_id,+ metric_name,+ series_fingerprint,+ any(metric_type) AS metric_type,+ any(unit) AS unit,+ any(service_name) AS service_name,+ any(attributes) AS attributes,+ any(resource_attributes) AS resource_attributes+ FROM posthog.metric_series+ WHERE metric_name = {metric_name}+ GROUP BY team_id, metric_name, series_fingerprint+ ) AS ser+ ON s.team_id = ser.team_id+ AND s.metric_name = ser.metric_name+ AND s.series_fingerprint = ser.series_fingerprint+ ORDER BY s.timestamp DESC+ """,+ placeholders={+ "metric_name": ast.Constant(value=self.metric_name),+ "date_from": ast.Constant(value=self.date_from),+ "date_to": ast.Constant(value=self.date_to),+ "trace_id": ast.Constant(value=self.trace_id),+ "limit": ast.Constant(value=self.limit),+ },+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricEventSamplesQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ )++ return [+ {+ "timestamp": row[0].isoformat() if hasattr(row[0], "isoformat") else str(row[0]),+ "metric_name": row[1],+ "metric_type": row[2],+ "value": row[3],+ "unit": row[4],+ "service_name": row[5],+ "trace_id": row[6],+ "span_id": row[7],+ "attributes": dict(row[8]) if row[8] else {},+ "resource_attributes": dict(row[9]) if row[9] else {},+ }+ for row in response.results+ ]diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex a74177e12880..0e9381732b74 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -25,6 +25,7 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRfrom products.metrics.backend.facade.api import (characterize_metric_anomaly,+ list_metric_event_samples,list_metric_names,run_metric_query,team_has_metrics,@@ -343,6 +344,67 @@ class _MetricNamesResponseSerializer(serializers.Serializer):results = _MetricNameSerializer(many=True, help_text="Distinct metric names ordered by recent activity.")+class _MetricSamplesBodySerializer(serializers.Serializer):+ metricName = serializers.CharField(+ max_length=255,+ help_text="Exact metric name to list raw emissions for (e.g. 'http.server.duration').",+ )+ dateFrom = serializers.DateTimeField(+ help_text="Lower bound (inclusive) for the sample window. ISO 8601.",+ )+ dateTo = serializers.DateTimeField(+ required=False,+ help_text="Upper bound (exclusive) for the sample window. Defaults to now if omitted.",+ )+ traceId = serializers.CharField(+ 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.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=100,+ min_value=1,+ max_value=1000,+ help_text="Max emissions to return, newest first. Defaults to 100, capped at 1000.",+ )+++class _MetricSamplesRequestSerializer(serializers.Serializer):+ query = _MetricSamplesBodySerializer(help_text="The raw-emissions query to execute.")+++class _MetricEventSampleSerializer(serializers.Serializer):+ timestamp = serializers.CharField(help_text="When the metric was emitted, ISO 8601.")+ metric_name = serializers.CharField(help_text="Metric this emission belongs to.")+ metric_type = serializers.CharField(+ help_text="OTel metric type: gauge, sum, histogram, summary, or exponential_histogram."+ )+ value = serializers.FloatField(help_text="The emitted value.")+ unit = serializers.CharField(help_text="Unit of the value, if any.")+ 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.",+ )+ span_id = serializers.CharField(help_text="Span this emission belongs to; empty if none.")+ attributes = serializers.DictField(+ child=serializers.CharField(),+ help_text="Per-emission attributes (high-cardinality labels on the data point).",+ )+ resource_attributes = serializers.DictField(+ child=serializers.CharField(),+ help_text="Attributes of the resource (host, pod, service version) that emitted the metric.",+ )+++class _MetricSamplesResponseSerializer(serializers.Serializer):+ results = _MetricEventSampleSerializer(+ many=True,+ help_text="Raw emissions ordered by timestamp descending.",+ )++@extend_schema(tags=["metrics"])class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "metrics"@@ -452,6 +514,39 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response({"results": [asdict(s) for s in series]}, status=status.HTTP_200_OK)+ @extend_schema(request=_MetricSamplesRequestSerializer, responses={200: _MetricSamplesResponseSerializer})+ @action(detail=False, methods=["POST"], required_scopes=["metrics:read"])+ def samples(self, request: Request, *args, **kwargs) -> Response:+ """Raw individual emissions for a metric (the events model), newest+ first — backs the Samples view and the metric->trace pivot."""+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)++ body = _MetricSamplesRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ query_data = body.validated_data["query"]++ try:+ samples = list_metric_event_samples(+ team=self.team,+ metric_name=query_data["metricName"],+ date_from=query_data["dateFrom"],+ date_to=query_data.get("dateTo") or timezone.now(),+ trace_id=query_data.get("traceId") or None,+ limit=query_data.get("limit") or 100,+ )+ except ValueError as exc:+ raise ParseError(str(exc))++ report_user_action(+ request.user,+ "metrics samples listed",+ {"sample_count": len(samples), "has_trace_filter": bool(query_data.get("traceId"))},+ team=self.team,+ request=request,+ )++ return Response({"results": [asdict(s) for s in samples]}, status=status.HTTP_200_OK)+@extend_schema(request=_MetricAnomalyRequestSerializer, responses={200: _MetricAnomalyReportSerializer})@action(detail=False,diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.pyindex 18bc2a33d479..00a2c5287fdf 100644--- a/products/metrics/backend/tests/_seeder.py+++ b/products/metrics/backend/tests/_seeder.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport jsonimport uuid+import hashlibimport datetime as dtfrom collections.abc import Iterable, Mappingfrom typing import Any@@ -19,6 +20,19 @@ from typing import Anyfrom posthog.clickhouse.client import sync_execute+def _series_fingerprint(+ metric_name: str, service_name: str, resource_attributes: Mapping[str, str], attributes: Mapping[str, str]+) -> int:+ """A deterministic UInt64 fingerprint for the (metric, label-set) tuple.++ The seeder owns both the series and its samples, so this only has to be+ stable per label-set (distinct sets -> distinct fingerprints) — it does NOT+ have to equal ClickHouse's `cityHash64`, which the real ingest MV computes.+ """+ key = repr((metric_name, service_name, sorted(resource_attributes.items()), sorted(attributes.items())))+ return int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8).digest(), "big")++def _attribute_map_str_with_type_tags(labels: Mapping[str, str]) -> dict[str, str]:"""`attributes_map_str` stores keys with a trailing 5-char type tag (e.g.`container__str`), matching the Kafka MV's `concat(k, '__str')`. The@@ -89,3 +103,59 @@ def seed_metric(payload = "\n".join(json.dumps(row) for row in rows)sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {payload}")+++def seed_metric_event(+ *,+ team_id: int,+ metric_name: str,+ points: Iterable[tuple[dt.datetime, float]],+ metric_type: str = "sum",+ unit: str = "",+ service_name: str = "test-service",+ trace_id: str = "",+ span_id: str = "",+ attributes: Mapping[str, str] | None = None,+ resource_attributes: Mapping[str, str] | None = None,+) -> None:+ """Insert one `metric_samples` row per `(timestamp, value)` point plus the+ matching `metric_series` row, the way the ingest MVs split a metric.++ All points here share one label-set, so they share one `series_fingerprint`+ and one series row that the samples reference.+ """+ attributes = dict(attributes or {})+ resource_attributes = dict(resource_attributes or {})+ points = list(points)+ if not points:+ return++ fingerprint = _series_fingerprint(metric_name, service_name, resource_attributes, attributes)++ sample_rows: list[dict[str, Any]] = [+ {+ "team_id": team_id,+ "metric_name": metric_name,+ "series_fingerprint": fingerprint,+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "value": value,+ "trace_id": trace_id,+ "span_id": span_id,+ "trace_flags": 0,+ }+ for timestamp, value in points+ ]+ series_row = {+ "team_id": team_id,+ "metric_name": metric_name,+ "series_fingerprint": fingerprint,+ "metric_type": metric_type,+ "unit": unit,+ "service_name": service_name,+ "resource_attributes": resource_attributes,+ "attributes": attributes,+ "last_seen": max(ts for ts, _ in points).strftime("%Y-%m-%d %H:%M:%S.%f"),+ }++ sync_execute("INSERT INTO metric_samples1 FORMAT JSONEachRow " + "\n".join(json.dumps(r) for r in sample_rows))+ sync_execute("INSERT INTO metric_series1 FORMAT JSONEachRow " + json.dumps(series_row))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.pynew file mode 100644index 000000000000..1b0d7fae914f--- /dev/null+++ b/products/metrics/backend/tests/test_metric_event_samples_query_runner.py@@ -0,0 +1,169 @@+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++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.metric_event_samples_query_runner import MetricEventSamplesQueryRunner+from products.metrics.backend.tests._seeder import seed_metric_event+++class TestMetricEventSamplesQueryRunner(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)++ @parameterized.expand(+ [+ ("empty_metric_name", "", -1, 0, 100),+ ("inverted_window", "m", 0, -1, 100),+ ("zero_limit", "m", -1, 0, 0),+ ("oversized_limit", "m", -1, 0, 1001),+ ]+ )+ def test_runner_rejects_bad_input(self, _label, metric_name, from_h, to_h, limit):+ now = timezone.now()+ with self.assertRaises(ValueError):+ MetricEventSamplesQueryRunner(+ team=self.team,+ metric_name=metric_name,+ date_from=now + dt.timedelta(hours=from_h),+ date_to=now + dt.timedelta(hours=to_h),+ limit=limit,+ )++ def test_returns_empty_for_no_data(self):+ now = timezone.now()+ samples = list_metric_event_samples(+ team=self.team,+ metric_name="absent",+ date_from=now - dt.timedelta(hours=1),+ date_to=now + dt.timedelta(hours=1),+ )+ self.assertEqual(samples, [])++ def test_scopes_to_team(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric_event(+ team_id=self.team.id, metric_name="checkout.failed", points=[(anchor, 1.0)], attributes={"region": "us"}+ )+ # Another team's emission for the same metric must never surface.+ seed_metric_event(team_id=self.team.id + 1, metric_name="checkout.failed", points=[(anchor, 9.0)])++ samples = list_metric_event_samples(+ team=self.team,+ metric_name="checkout.failed",+ date_from=anchor - dt.timedelta(hours=1),+ date_to=anchor + dt.timedelta(hours=1),+ )+ self.assertEqual(len(samples), 1)+ self.assertEqual(samples[0].value, 1.0)+ self.assertEqual(samples[0].attributes, {"region": "us"})++ def test_filters_by_trace_id(self):+ 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")+ 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"+ )+ self.assertEqual([s.trace_id for s in traced], ["trace-a"])++ def test_maps_fields_and_orders_newest_first(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric_event(+ team_id=self.team.id,+ metric_name="latency",+ points=[(anchor - dt.timedelta(minutes=5), 10.0)],+ metric_type="histogram",+ unit="ms",+ service_name="api",+ trace_id="t1",+ span_id="s1",+ attributes={"route": "/x"},+ resource_attributes={"service.version": "1.2"},+ )+ seed_metric_event(+ team_id=self.team.id,+ metric_name="latency",+ points=[(anchor, 20.0)],+ metric_type="histogram",+ service_name="api",+ )++ samples = list_metric_event_samples(+ team=self.team,+ metric_name="latency",+ date_from=anchor - dt.timedelta(hours=1),+ date_to=anchor + dt.timedelta(hours=1),+ )++ self.assertEqual([s.value for s in samples], [20.0, 10.0]) # newest first+ oldest = samples[1]+ self.assertEqual(oldest.metric_type, "histogram")+ self.assertEqual(oldest.unit, "ms")+ self.assertEqual(oldest.service_name, "api")+ self.assertEqual(oldest.trace_id, "t1")+ self.assertEqual(oldest.attributes, {"route": "/x"})+ self.assertEqual(oldest.resource_attributes, {"service.version": "1.2"})++ def test_samples_api_requires_authentication(self):+ self.client.logout()+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/samples",+ data={"query": {"metricName": "m", "dateFrom": "2026-01-01T00:00:00Z"}},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_samples_api_validates_required_fields(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/samples",+ data={"query": {"dateFrom": "2026-01-01T00:00:00Z"}},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_samples_api_returns_emissions(self):+ 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-z",+ attributes={"region": "us"},+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/samples",+ data={+ "query": {+ "metricName": "checkout.failed",+ "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)+ 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]["attributes"], {"region": "us"})diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 4e8bc562a231..f6103cb8f0e1 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -374,6 +374,72 @@ export interface _MetricQueryResponseApi {results: _MetricSeriesApi[]}+export interface _MetricSamplesBodyApi {+ /**+ * Exact metric name to list raw emissions for (e.g. 'http.server.duration').+ * @maxLength 255+ */+ 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. */+ dateTo?: string+ /**+ * Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.+ * @maxLength 255+ */+ traceId?: string+ /**+ * Max emissions to return, newest first. Defaults to 100, capped at 1000.+ * @minimum 1+ * @maximum 1000+ */+ limit?: number+}++export interface _MetricSamplesRequestApi {+ /** The raw-emissions query to execute. */+ query: _MetricSamplesBodyApi+}++/**+ * Per-emission attributes (high-cardinality labels on the data point).+ */+export type _MetricEventSampleApiAttributes = { [key: string]: string }++/**+ * Attributes of the resource (host, pod, service version) that emitted the metric.+ */+export type _MetricEventSampleApiResourceAttributes = { [key: string]: string }++export interface _MetricEventSampleApi {+ /** When the metric was emitted, ISO 8601. */+ timestamp: string+ /** Metric this emission belongs to. */+ metric_name: string+ /** OTel metric type: gauge, sum, histogram, summary, or exponential_histogram. */+ metric_type: string+ /** The emitted value. */+ value: number+ /** Unit of the value, if any. */+ unit: string+ /** Service that emitted the metric. */+ service_name: string+ /** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */+ trace_id: string+ /** Span this emission belongs to; empty if none. */+ span_id: string+ /** Per-emission attributes (high-cardinality labels on the data point). */+ attributes: _MetricEventSampleApiAttributes+ /** Attributes of the resource (host, pod, service version) that emitted the metric. */+ resource_attributes: _MetricEventSampleApiResourceAttributes+}++export interface _MetricSamplesResponseApi {+ /** Raw emissions ordered by timestamp descending. */+ results: _MetricEventSampleApi[]+}+export interface _MetricNameApi {/** Metric name as it appears in the team's data. */name: stringdiff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex 86148679ab5b..f40ec42b3370 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -18,6 +18,8 @@ import type {_MetricNamesResponseApi,_MetricQueryRequestApi,_MetricQueryResponseApi,+ _MetricSamplesRequestApi,+ _MetricSamplesResponseApi,} from './api.schemas'export const getEventFilterMetricsRetrieveUrl = (projectId: string) => {@@ -114,6 +116,27 @@ export const metricsQueryCreate = async (})}+export const getMetricsSamplesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/metrics/samples/`+}++/**+ * Raw individual emissions for a metric (the events model), newest+ * first — backs the Samples view and the metric->trace pivot.+ */+export const metricsSamplesCreate = async (+ projectId: string,+ _metricSamplesRequestApi: _MetricSamplesRequestApi,+ options?: RequestInit+): Promise<_MetricSamplesResponseApi> => {+ return apiMutator<_MetricSamplesResponseApi>(getMetricsSamplesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_metricSamplesRequestApi),+ })+}+export const getMetricsValuesRetrieveUrl = (projectId: string, params?: MetricsValuesRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.tsindex 146d81fb717f..835056c5879c 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -341,3 +341,45 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({}).describe('The metric query to execute.'),})++/**+ * Raw individual emissions for a metric (the events model), newest+ * first — backs the Samples view and the metric->trace pivot.+ */+export const metricsSamplesCreateBodyQueryOneMetricNameMax = 255++export const metricsSamplesCreateBodyQueryOneTraceIdMax = 255++export const metricsSamplesCreateBodyQueryOneLimitDefault = 100+export const metricsSamplesCreateBodyQueryOneLimitMax = 1000++export const MetricsSamplesCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ metricName: zod+ .string()+ .max(metricsSamplesCreateBodyQueryOneMetricNameMax)+ .describe("Exact metric name to list raw emissions for (e.g. 'http.server.duration')."),+ dateFrom: zod.iso+ .datetime({ offset: true })+ .describe('Lower bound (inclusive) for the sample window. ISO 8601.'),+ dateTo: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Upper bound (exclusive) for the sample window. Defaults to now if omitted.'),+ traceId: zod+ .string()+ .max(metricsSamplesCreateBodyQueryOneTraceIdMax)+ .optional()+ .describe(+ 'Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.'+ ),+ limit: zod+ .number()+ .min(1)+ .max(metricsSamplesCreateBodyQueryOneLimitMax)+ .default(metricsSamplesCreateBodyQueryOneLimitDefault)+ .describe('Max emissions to return, newest first. Defaults to 100, capped at 1000.'),+ })+ .describe('The raw-emissions query to execute.'),+})diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yamlindex 323fcf2c5948..bd9627caee4f 100644--- a/products/metrics/mcp/tools.yaml+++ b/products/metrics/mcp/tools.yaml@@ -41,6 +41,9 @@ tools:metrics-has-metrics-retrieve:operation: metrics_has_metrics_retrieveenabled: false+ metrics-samples-create:+ operation: metrics_samples_create+ enabled: falsequery-metrics:operation: metrics_query_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f106f8e4d82c..f13b06b9d7f9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54122,6 +54122,39 @@ export namespace Schemas {groupBy?: _MetricGroupBy[];}+ /**+ * Per-emission attributes (high-cardinality labels on the data point).+ */+ export type _MetricEventSampleAttributes = {[key: string]: string};++ /**+ * Attributes of the resource (host, pod, service version) that emitted the metric.+ */+ export type _MetricEventSampleResourceAttributes = {[key: string]: string};++ export interface _MetricEventSample {+ /** When the metric was emitted, ISO 8601. */+ timestamp: string;+ /** Metric this emission belongs to. */+ metric_name: string;+ /** OTel metric type: gauge, sum, histogram, summary, or exponential_histogram. */+ metric_type: string;+ /** The emitted value. */+ value: number;+ /** Unit of the value, if any. */+ unit: string;+ /** Service that emitted the metric. */+ service_name: string;+ /** Trace this emission belongs to; empty if none. Use it to pivot to the trace. */+ trace_id: string;+ /** Span this emission belongs to; empty if none. */+ span_id: string;+ /** Per-emission attributes (high-cardinality labels on the data point). */+ attributes: _MetricEventSampleAttributes;+ /** Attributes of the resource (host, pod, service version) that emitted the metric. */+ resource_attributes: _MetricEventSampleResourceAttributes;+ }+export interface _MetricName {/** Metric name as it appears in the team's data. */name: string;@@ -54196,6 +54229,39 @@ export namespace Schemas {results: _MetricSeries[];}+ export interface _MetricSamplesBody {+ /**+ * Exact metric name to list raw emissions for (e.g. 'http.server.duration').+ * @maxLength 255+ */+ 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. */+ dateTo?: string;+ /**+ * Restrict to emissions on this trace — the reverse metric->trace pivot. Omit for all traces.+ * @maxLength 255+ */+ traceId?: string;+ /**+ * Max emissions to return, newest first. Defaults to 100, capped at 1000.+ * @minimum 1+ * @maximum 1000+ */+ limit?: number;+ }++ export interface _MetricSamplesRequest {+ /** The raw-emissions query to execute. */+ query: _MetricSamplesBody;+ }++ export interface _MetricSamplesResponse {+ /** Raw emissions ordered by timestamp descending. */+ results: _MetricEventSample[];+ }+/*** * `span` - span* * `span_attribute` - span_attribute