: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
fix(metrics): constrain queries to one metric type so same-named series don't blend (#69412)
Daniel Visca743043d36759
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9d92c8f2afb0..7e7e4e36248b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7755,9 +7755,9 @@ snapshots:utils-autocapture-preview-image--relative-image-no-properties--light:hash: v1.k794b7964.ac0b1b273673606c050f2456d4e4f89ed9b51f4ff81d19bd49c27012df7228b9.QqebZ5ofiSy7_l4SI8CY2r7Bmsct0UVC6p6a0jrlzyEutils-autocapture-preview-image--relative-image-with-current-url--dark:- hash: v1.k794b7964.c7acd105f6399d63776bfed3561242a2f2edb6c492aa4aaca9ff0c4ffc3dde61.MtawQTsrzaoXnXXtolm5QpozUgSON1UcrpYcyRbunok+ hash: v1.k794b7964.d753bca9fa2fef59a9263413065b9f5cb0b23634345e7e090d1f3a2e12d7c6bd.kA22l5SdPfyCTGR0DeLGoCLyWrekrLnvjq-hCUzQggAutils-autocapture-preview-image--relative-image-with-current-url--light:- hash: v1.k794b7964.65bee2b7efa6b972209d7d76b559b5499d6de41ffba62f41b44848e568f2b353.zu-E-JmCsic7u11XS1CTH0b7-1SpSLizRgQmaBJHlVE+ hash: v1.k794b7964.3ce877ae9bf3b58033dd24136d8f0c4117f9340321ff8847aa320f034b7112f2.zaD49tXfEgchVf0hlArZmvc39UmprasZh7BDL3NR7QQutils-autocapture-preview-image--tab-absolute-image-url--dark:hash: v1.k794b7964.756ee4ace843deb938f58fdfc6b75bf725775896532bd860be82ae13f45e4c7c.O31RlVZFnP3ys1B8VboOrdJs6usMKzuXbRJ6RWlyvLUutils-autocapture-preview-image--tab-absolute-image-url--light:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 74c8f08a184e..779f000017cb 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -555,6 +555,9 @@ SPECTACULAR_SETTINGS = {"HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],+ # The metrics query's OTel metric-type filter; without a pinned name it+ # collides with the experiments MetricTypeEnum (funnel/ratio/...).+ "OtelMetricTypeEnum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],# bulk_update_tags exposes an identical add/remove/set `action` ChoiceField on both# BulkUpdateTagsRequest and its UUID subclass, so the shared enum can't be component-prefixed# unambiguously and auto-resolves to a hash name. Pin it to a stable name.diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 84abf956f4f7..84270022975b 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -180,6 +180,7 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSgroup_by=clause.group_by,interval=request.interval,quantile=clause.quantile if runner_aggregation == "histogram_quantile" else None,+ metric_type=clause.metric_type.value if clause.metric_type is not None else None,)rows_by_clause[clause.name] = runner.run()diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex c1110fcc4930..4d39b2972903 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -22,7 +22,7 @@ from __future__ import annotationsimport datetime as dtfrom dataclasses import dataclass-from .enums import AttributeScope, FilterOp, MetricAggregation+from .enums import AttributeScope, FilterOp, MetricAggregation, MetricType# Each clause runs its own ClickHouse query on the shared logs cluster, so# the clause count per request is hard-capped.@@ -60,6 +60,8 @@ class MetricQueryClause:group_by: tuple[MetricGroupBy, ...] = ()# Required for QUANTILE / HISTOGRAM_QUANTILE; ignored otherwise.quantile: float | None = None+ # Constrains rows to one metric type; None keeps all types (legacy).+ metric_type: MetricType | None = Nonedef __post_init__(self) -> None:if self.aggregation.needs_quantile:diff --git a/products/metrics/backend/facade/enums.py b/products/metrics/backend/facade/enums.pyindex 8b48bee9e367..f74693a21411 100644--- a/products/metrics/backend/facade/enums.py+++ b/products/metrics/backend/facade/enums.py@@ -38,6 +38,19 @@ class FilterOp(StrEnum):NOT_REGEX = "not_regex"+class MetricType(StrEnum):+ """The OTel metric type a clause targets. Series identity includes the+ type — one name can exist as both a counter and a gauge — so queries+ constrain it to avoid blending distinct series. Values match what the+ ingest writes to `metric_type` (rust/capture-logs `flatten_metric`)."""++ GAUGE = "gauge"+ SUM = "sum"+ HISTOGRAM = "histogram"+ EXPONENTIAL_HISTOGRAM = "exponential_histogram"+ SUMMARY = "summary"++class MetricAggregation(StrEnum):"""How a clause collapses the values in each time bucket into one number.diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 716e66f3f73f..e6ae672d3181 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -24,7 +24,7 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.models import Teamfrom products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy-from products.metrics.backend.facade.enums import FilterOp+from products.metrics.backend.facade.enums import FilterOp, MetricTypeAttributeScope = Literal["resource", "attribute", "auto"]@@ -136,6 +136,10 @@ _ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"})+# Derived from the contract enum (whose values match what the ingest writes,+# rust/capture-logs `flatten_metric`) so the two can't silently diverge.+_ALLOWED_METRIC_TYPES: frozenset[str] = frozenset(t.value for t in MetricType)+def _histogram_quantile(quantile: float, bounds: list[float], counts: list[float]) -> float:"""Prometheus-style quantile from explicit-bounds bucket counts.@@ -245,9 +249,12 @@ class MetricQueryRunner:group_by: Sequence[MetricGroupBy] = (),interval: str | None = None,quantile: float | None = None,+ metric_type: str | None = None,) -> None:if aggregation not in _ALLOWED_AGGREGATIONS:raise ValueError(f"Unsupported aggregation: {aggregation!r}")+ if metric_type is not None and metric_type not in _ALLOWED_METRIC_TYPES:+ raise ValueError(f"Unknown metric_type: {metric_type!r}")if date_to <= date_from:raise ValueError("date_to must be after date_from")if date_to - date_from > MAX_QUERY_SPAN:@@ -274,6 +281,7 @@ class MetricQueryRunner:self.group_by = tuple(group_by)self.interval = interval or _pick_interval(date_from, date_to)self.quantile = quantile+ self.metric_type = metric_typedef run(self) -> list[dict[str, Any]]:"""Bucketed rows: `{"time", "value", "labels"}`. `labels` carries one@@ -366,6 +374,16 @@ class MetricQueryRunner:query.select.insert(1 + index, ast.Alias(alias=f"group_{index}", expr=label_expr))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)}+ )+def _build_simple_query(self) -> ast.SelectQuery:# `metrics` is only registered under the `posthog.` HogQL namespace# (see posthog/hogql/database/database.py).@@ -379,6 +397,7 @@ class MetricQueryRunner:AND timestamp >= {date_from}AND timestamp < {date_to}AND {filters}+ AND {type_filter}GROUP BY timeORDER BY time ASCLIMIT {row_limit}@@ -390,6 +409,7 @@ class MetricQueryRunner:"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"filters": _filters_expr(self.filters),+ "type_filter": self._type_filter_expr(),"row_limit": ast.Constant(value=_ROW_LIMIT),},)@@ -451,6 +471,7 @@ class MetricQueryRunner:AND timestamp >= {date_from}AND timestamp < {date_to}AND {filters}+ AND {type_filter}))GROUP BY time@@ -464,6 +485,7 @@ class MetricQueryRunner:"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"filters": _filters_expr(self.filters),+ "type_filter": self._type_filter_expr(),"row_limit": ast.Constant(value=_ROW_LIMIT),},)@@ -516,6 +538,7 @@ class MetricQueryRunner:AND timestamp < {date_to}AND notEmpty(histogram_counts)AND {filters}+ AND {type_filter}))GROUP BY time@@ -528,6 +551,7 @@ class MetricQueryRunner:"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"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.pyindex 2f253d3f3979..5508ae081717 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -38,7 +38,7 @@ from products.metrics.backend.facade.contracts import (MetricQueryClause,MetricQueryRequest,)-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType__all__ = ["MetricsViewSet"]@@ -86,6 +86,12 @@ class _MetricClauseSerializer(serializers.Serializer):max_length=255,help_text="Exact metric name this clause queries.",)+ metricType = serializers.ChoiceField(+ choices=[t.value for t in MetricType],+ required=False,+ allow_null=True,+ help_text="Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.",+ )aggregation = serializers.ChoiceField(choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],default="sum",@@ -118,6 +124,12 @@ class _MetricQueryBodySerializer(serializers.Serializer):required=False,help_text="Exact metric name to query (e.g. 'http.server.duration'). Single-clause shorthand — mutually exclusive with 'clauses'.",)+ metricType = serializers.ChoiceField(+ choices=[t.value for t in MetricType],+ required=False,+ allow_null=True,+ help_text="Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.",+ )aggregation = serializers.ChoiceField(choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],default="sum",@@ -176,6 +188,10 @@ class _MetricQueryBodySerializer(serializers.Serializer):raise serializers.ValidationError("Provide exactly one of 'metricName' or 'clauses'.")if attrs.get("formula") and not has_clauses:raise serializers.ValidationError("'formula' requires 'clauses'.")+ if has_clauses and attrs.get("metricType"):+ raise serializers.ValidationError(+ "'metricType' applies to the single-clause shorthand; set it per clause instead."+ )return attrs@@ -196,11 +212,13 @@ def _build_clause(data: dict, *, name: str) -> MetricQueryClause:else:aggregation = MetricAggregation(aggregation_raw)+ metric_type_raw = data.get("metricType")return MetricQueryClause(name=name,metric_name=data["metricName"],aggregation=aggregation,quantile=quantile,+ metric_type=MetricType(metric_type_raw) if metric_type_raw else None,filters=tuple(MetricFilter(key=f["key"], op=FilterOp(f["op"]), value=f["value"], scope=AttributeScope(f["scope"]))for f in data.get("filters") or []diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex bbe070b9eb13..685c9b7157aa 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -203,6 +203,20 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)+ def test_query_rejects_top_level_metric_type_with_clauses(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "clauses": [{"name": "a", "metricName": "m1", "aggregation": "sum"}],+ "metricType": "gauge",+ "dateFrom": "2026-01-01T00:00:00Z",+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_query_validates_required_fields(self):response = self.client.post(f"/api/projects/{self.team.id}/metrics/query",@@ -1166,6 +1180,99 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):+ """One metric name existing as several types (e.g. a counter and a gauge)+ must not blend into one aggregate — series identity includes the type."""++ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)+ # The same name recorded as a delta counter (5) and as a gauge (42).+ seed_metric(+ team_id=self.team.id,+ metric_name="m_collide",+ points=[(self.anchor, 5.0)],+ metric_type="sum",+ aggregation_temporality="delta",+ is_monotonic=True,+ )+ seed_metric(+ team_id=self.team.id,+ metric_name="m_collide",+ points=[(self.anchor, 42.0)],+ metric_type="gauge",+ )++ def _run(self, aggregation: str, metric_type: str | None, **kwargs: Any) -> list[dict[str, Any]]:+ return MetricQueryRunner(+ team=self.team,+ metric_name="m_collide",+ aggregation=aggregation,+ date_from=self.anchor - dt.timedelta(minutes=5),+ date_to=self.anchor + dt.timedelta(minutes=5),+ metric_type=metric_type,+ **kwargs,+ ).run()++ @parameterized.expand(+ [+ # Without isolation these blended: avg was (5 + 42) / 2 = 23.5.+ ("gauge_avg", "avg", "gauge", 42.0),+ ("counter_sum", "sum", "sum", 5.0),+ ("counter_increase", "increase", "sum", 5.0),+ ]+ )+ def test_type_filter_isolates_series(self, _name: str, aggregation: str, metric_type: str, expected: float):+ rows = self._run(aggregation, metric_type)+ assert [row["value"] for row in rows] == [expected]++ def test_without_type_filter_all_rows_still_match(self):+ # Back-compat: no metric_type keeps the pre-filter behavior.+ rows = self._run("count", None)+ assert [row["value"] for row in rows] == [2]++ def test_rejects_unknown_metric_type(self):+ with self.assertRaises(ValueError):+ self._run("avg", "flurble")++ def test_histogram_quantile_ignores_same_named_non_histogram_rows(self):+ seed_metric(+ team_id=self.team.id,+ metric_name="m_collide",+ points=[(self.anchor, 30.0)],+ metric_type="histogram",+ aggregation_temporality="delta",+ histogram_bounds=[10.0, 50.0, 100.0],+ histogram_counts=[0, 10, 0, 0],+ )+ # No explicit type needed: the histogram path must constrain itself.+ rows = self._run("histogram_quantile", None, quantile=0.5)+ assert len(rows) == 1+ # All 10 observations sit in the (10, 50] bucket; p50 interpolates to 30.+ assert abs(rows[0]["value"] - 30.0) < 1e-9++ def test_api_accepts_metric_type(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "m_collide",+ "aggregation": "avg",+ "metricType": "gauge",+ "dateFrom": (self.anchor - dt.timedelta(minutes=5)).isoformat(),+ "dateTo": (self.anchor + dt.timedelta(minutes=5)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ series = response.json()["results"][0]+ self.assertEqual([p["value"] for p in series["points"]], [42.0])++class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):"""ClickHouse float aggregates can overflow to inf (two 1e308 samples inone bucket). A Python `inf` leaking into the response is at best invaliddiff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 693116f9249b..d0e6337b3477 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -20,6 +20,7 @@ import { QueryBasedInsightModel } from '~/types'import { PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'import { metricsCharacterizeCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'+import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'import type {_MetricAnomalyReportApi,_MetricFilterApi,@@ -252,6 +253,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([query: {metricName: trimmedName,aggregation: values.aggregation,+ ...(values.selectedMetricType ? { metricType: values.selectedMetricType } : {}),dateFrom: dateFromISO,...(dateToISO ? { dateTo: dateToISO } : {}),...(values.groupByKeys.length@@ -327,6 +329,17 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([})),selectors({hasMetricName: [(s) => [s.metricName], (metricName) => metricName.trim().length > 0],+ // The picked metric's type (from the names list). Sent with the query so+ // a name that exists as several types (e.g. a counter and a gauge)+ // charts only the picked one instead of blending them.+ selectedMetricType: [+ (s) => [s.metricName, s.items],+ (metricName, items): OtelMetricTypeEnumApi | null => {+ const metricType = items.find((item) => item.name === metricName.trim())?.metric_type+ const known = Object.values(OtelMetricTypeEnumApi) as string[]+ return metricType && known.includes(metricType) ? (metricType as OtelMetricTypeEnumApi) : null+ },+ ],// The viewer state as a `MetricsQuery` schema node — what "Save as insight"// persists, so the saved tile re-runs exactly what the viewer shows.// The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 63218feaa652..9c61d3aa3d03 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -275,6 +275,23 @@ export interface _HasMetricsResponseApi {hasMetrics: boolean}+/**+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary+ */+export type OtelMetricTypeEnumApi = (typeof OtelMetricTypeEnumApi)[keyof typeof OtelMetricTypeEnumApi]++export const OtelMetricTypeEnumApi = {+ Gauge: 'gauge',+ Sum: 'sum',+ Histogram: 'histogram',+ ExponentialHistogram: 'exponential_histogram',+ Summary: 'summary',+} as const+export interface _MetricGroupByApi {/*** Attribute name to split series by (e.g. 'k8s.pod.name', 'env').@@ -323,6 +340,14 @@ export interface _MetricClauseApi {* @maxLength 255*/metricName: string+ /** Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.+ *+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary */+ metricType?: OtelMetricTypeEnumApi | null/** Aggregation applied per time bucket; same semantics as the top-level aggregation.** * `sum` - sum@@ -352,6 +377,14 @@ export interface _MetricQueryBodyApi {* @maxLength 255*/metricName?: string+ /** Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.+ *+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary */+ metricType?: OtelMetricTypeEnumApi | null/** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.** * `sum` - sumdiff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.tsindex bc8c9bee031d..eb08ba7fbbc5 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -158,6 +158,19 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({.describe("Exact metric name to query (e.g. 'http.server.duration'). Single-clause shorthand — mutually exclusive with 'clauses'."),+ 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 query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary"+ ),aggregation: zod.enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile']).describe(@@ -248,6 +261,19 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({.string().max(metricsQueryCreateBodyQueryOneClausesItemMetricNameMax).describe('Exact metric name this clause queries.'),+ 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 query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary"+ ),aggregation: zod.enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile']).describe(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0590c702a6a5..bb800dbc87b6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -32893,6 +32893,24 @@ export namespace Schemas {ImageBuilder: 'image_builder',} as const;+ /**+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary+ */+ export type OtelMetricTypeEnum = typeof OtelMetricTypeEnum[keyof typeof OtelMetricTypeEnum];+++ export const OtelMetricTypeEnum = {+ Gauge: 'gauge',+ Sum: 'sum',+ Histogram: 'histogram',+ ExponentialHistogram: 'exponential_histogram',+ Summary: 'summary',+ } as const;+/*** Initial goal and session outcome coming from LLM.*/@@ -58262,6 +58280,14 @@ export namespace Schemas {* @maxLength 255*/metricName: string;+ /** Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.+ *+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary */+ metricType?: OtelMetricTypeEnum | null;/** Aggregation applied per time bucket; same semantics as the top-level aggregation.** * `sum` - sum@@ -58342,6 +58368,14 @@ export namespace Schemas {* @maxLength 255*/metricName?: string;+ /** Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.+ *+ * * `gauge` - gauge+ * * `sum` - sum+ * * `histogram` - histogram+ * * `exponential_histogram` - exponential_histogram+ * * `summary` - summary */+ metricType?: OtelMetricTypeEnum | null;/** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.** * `sum` - sumdiff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.tsindex 378c4fc7b2d5..92e6c06165af 100644--- a/services/mcp/src/generated/metrics/api.ts+++ b/services/mcp/src/generated/metrics/api.ts@@ -173,6 +173,19 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({.describe("Exact metric name to query (e.g. 'http.server.duration'). Single-clause shorthand — mutually exclusive with 'clauses'."),+ 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 query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n* `gauge` - gauge\n* `sum` - sum\n* `histogram` - histogram\n* `exponential_histogram` - exponential_histogram\n* `summary` - summary"+ ),aggregation: zod.enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile']).describe(@@ -263,6 +276,19 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({.string().max(metricsQueryCreateBodyQueryOneClausesItemMetricNameMax).describe('Exact metric name this clause queries.'),+ 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 query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n* `gauge` - gauge\n* `sum` - sum\n* `histogram` - histogram\n* `exponential_histogram` - exponential_histogram\n* `summary` - summary"+ ),aggregation: zod.enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile']).describe(