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): aggregate across series instead of raw samples (#86381)

Frank Hamand777d55398c59
diff --git a/products/metrics/backend/facade/enums.py b/products/metrics/backend/facade/enums.py
index f74693a21411..e94775f6ac66 100644
--- a/products/metrics/backend/facade/enums.py
+++ b/products/metrics/backend/facade/enums.py
@@ -54,8 +54,16 @@ class MetricType(StrEnum):
class MetricAggregation(StrEnum):
"""How a clause collapses the values in each time bucket into one number.
- Instant aggregations operate on the values that fell in the bucket:
- SUM, AVG, COUNT, MIN, MAX, QUANTILE.
+ Every aggregation resolves per series first, then combines across series,
+ so a result never depends on how often a series was scraped.
+
+ Instant aggregations take each series' last sample in the bucket and
+ combine those: SUM is the total across series, AVG and QUANTILE are
+ computed over series, COUNT is how many series reported, and MIN and MAX
+ are the smallest and largest last sample across series. MIN and MAX still
+ need the per-series step once they are implemented, because taken over raw
+ samples they would report a stale within-bucket extreme rather than the
+ current cross-series one.
Counter functions operate on the change across the bucket (cumulative
counters get reset-corrected; deltas are summed): RATE, INCREASE.
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index e4ab981a9744..6d7561e4887d 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -6,6 +6,11 @@ range, with a choice of aggregation. Modelled after the logs
`AnalyticsQueryRunner[LogsQueryResponse]` infrastructure since this product
isn't going through HogQL `DataNode` caching, schema-gen or the data-viz
pipeline yet.
+
+Every aggregation resolves per physical series (`_series_key_exprs`) before
+combining across series: instant aggregations reduce each series to its last
+sample in the bucket, counter functions diff within a series. Aggregating raw
+samples instead would weight a series by how often it was scraped.
"""
import re
@@ -51,6 +56,10 @@ _QUERY_SETTINGS = HogQLGlobalSettings(
# to it so filters/group-bys match real ingested rows.
_SERVICE_NAME_KEYS: frozenset[str] = frozenset({"service_name", "service.name"})
+# Synthetic per-data-point attribute ingest stamps on a point whose timestamp it
+# had to override. Never part of a series' identity — see `_series_key_exprs`.
+_ORIGINAL_TIMESTAMP_KEY = "$originalTimestamp"
+
def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
"""Build the HogQL AST node that accesses a metric attribute by name.
@@ -102,23 +111,64 @@ def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:
)
-def _aggregation_expr(name: str) -> ast.Expr:
- """Build the HogQL AST for the supported aggregations.
+def _series_key_exprs() -> list[ast.Expr]:
+ """Identifies the physical series a row belongs to.
+
+ Every aggregation resolves per series before combining across series, so
+ all three query builders share this definition rather than restating it.
+
+ `metric_type` belongs to the identity, not just to filtering: one name can
+ be ingested as both a counter and a gauge, and `metric_type` is optional on
+ the query, so an unconstrained query sees both sets of rows at once.
+
+ `$originalTimestamp` is dropped back out of `attributes`. Ingest adds it to
+ the map for a point whose timestamp is more than a day off, carrying a
+ per-sample value, and deliberately fingerprints the series before adding it
+ (`compute_series_fingerprint` in `rust/capture-logs/src/metric_record.rs`).
+ Keeping it would shatter a skewed exporter's series into one series per
+ sample, which is the exact weighting these keys exist to prevent.
+
+ `resource_attributes` appears here rather than its `resource_fingerprint`
+ digest so that the key stays exact — a hash collision would merge two
+ targets into one series.
+
+ These are grouping and partitioning keys only; a query that also needs the
+ attributes themselves reads them off `posthog.metrics` in the same scope,
+ because a column aliased `attributes` in a scope that already resolves the
+ `attributes` map collides with it.
+ """
+ return [
+ ast.Field(chain=["service_name"]),
+ ast.Field(chain=["resource_attributes"]),
+ parse_expr(
+ "mapFilter((k, v) -> k != {synthetic}, attributes)",
+ placeholders={"synthetic": ast.Constant(value=_ORIGINAL_TIMESTAMP_KEY)},
+ ),
+ ast.Field(chain=["metric_type"]),
+ ]
+
+
+def _aggregation_expr(name: str, value: ast.Expr) -> ast.Expr:
+ """Build the HogQL AST for the cross-series aggregations.
+
+ `value` is the per-series value the inner query produced, never the raw
+ `value` column: aggregating raw rows counts each series once per sample, so
+ the result scales with the scrape rate. `count` takes no argument for the
+ same reason — one inner row per series means it counts series.
Kept as AST nodes (rather than string interpolation) so the
`hogql-no-fstring` semgrep rule doesn't have to special-case this
runner — the function name and percentile literal travel as a
typed expression, not as substituted text.
"""
- value_field = ast.Field(chain=["value"])
if name == "sum":
- return ast.Call(name="sum", args=[value_field])
+ return ast.Call(name="sum", args=[value])
if name == "avg":
- return ast.Call(name="avg", args=[value_field])
+ return ast.Call(name="avg", args=[value])
if name == "count":
return ast.Call(name="count", args=[])
if name == "p95":
- return ast.Call(name="quantile", params=[ast.Constant(value=0.95)], args=[value_field])
+ return ast.Call(name="quantile", params=[ast.Constant(value=0.95)], args=[value])
raise ValueError(f"Unsupported aggregation: {name!r}")
@@ -377,39 +427,76 @@ class MetricQueryRunner:
"use a coarser interval, a narrower range, or a lower-cardinality group_by"
)
- def _splice_group_columns(self, query: ast.SelectQuery) -> None:
+ def _splice_group_columns(self, query: ast.SelectQuery, *, resolve_in: ast.SelectQuery | None = None) -> None:
"""Insert the group_by label columns between `time` and `value` —
- parse_select placeholders can't express a variable column count."""
+ parse_select placeholders can't express a variable column count.
+
+ `attribute_field` resolves against the scope of the query it lands in,
+ so that query must expose `service_name`, `attributes` and
+ `resource_attributes` under those names — read straight off
+ `posthog.metrics`, or re-exported from a subquery. Pass `resolve_in`
+ when the labels have to be built a level down instead; `query` then
+ only forwards them up by name.
+ """
assert query.group_by is not None
for index, group in enumerate(self.group_by):
- label_expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])
- query.select.insert(1 + index, ast.Alias(alias=f"group_{index}", expr=label_expr))
- query.group_by.append(ast.Field(chain=[f"group_{index}"]))
+ alias = f"group_{index}"
+ label_expr: ast.Expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])
+ if resolve_in is not None:
+ assert resolve_in.group_by is not None
+ resolve_in.select.append(ast.Alias(alias=alias, expr=label_expr))
+ resolve_in.group_by.append(ast.Field(chain=[alias]))
+ label_expr = ast.Field(chain=[alias])
+ query.select.insert(1 + index, ast.Alias(alias=alias, expr=label_expr))
+ query.group_by.append(ast.Field(chain=[alias]))
def _type_filter_expr(self) -> ast.Expr:
return type_filter_expr(self.metric_type)
def _build_simple_query(self) -> ast.SelectQuery:
+ """sum/avg/count/p95: collapse each series to one value per bucket,
+ then aggregate across series — PromQL instant-vector semantics.
+
+ The inner query takes each series' last sample in the bucket, so a
+ metric scraped ten times contributes once rather than ten times.
+ Aggregating raw rows instead multiplied the cross-series total by the
+ scrape count, and the multiplier moved with partial buckets and
+ dropped scrapes.
+
+ Two samples of one series sharing a timestamp (a duplicate scrape)
+ make `argMax` pick between them arbitrarily; they are the same
+ reading, so either answer is right.
+
+ Group-by labels are built in the inner query, where the attribute maps
+ are still in scope. A label is constant within a series, so the outer
+ query just carries it up.
+ """
# `metrics` is only registered under the `posthog.` HogQL namespace
# (see posthog/hogql/database/database.py).
query = parse_select(
"""
SELECT
- toStartOfInterval(timestamp, {interval}) AS time,
+ time AS time,
{aggregation} AS value
- FROM posthog.metrics
- WHERE metric_name = {metric_name}
- AND timestamp >= {date_from}
- AND timestamp < {date_to}
- AND {filters}
- AND {type_filter}
+ FROM (
+ SELECT
+ toStartOfInterval(timestamp, {interval}) AS time,
+ argMax(value, timestamp) AS series_value
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND timestamp >= {date_from}
+ AND timestamp < {date_to}
+ AND {filters}
+ AND {type_filter}
+ GROUP BY time
+ )
GROUP BY time
ORDER BY time ASC
LIMIT {row_limit}
""",
placeholders={
"interval": _interval_expr(self.interval),
- "aggregation": _aggregation_expr(self.aggregation),
+ "aggregation": _aggregation_expr(self.aggregation, ast.Field(chain=["series_value"])),
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
@@ -419,7 +506,13 @@ class MetricQueryRunner:
},
)
assert isinstance(query, ast.SelectQuery)
- self._splice_group_columns(query)
+ # Appended rather than written into the template so the key stays
+ # defined in exactly one place; a placeholder can only carry one
+ # expression.
+ inner = query.select_from.table if query.select_from else None
+ assert isinstance(inner, ast.SelectQuery) and inner.group_by is not None
+ inner.group_by.extend(_series_key_exprs())
+ self._splice_group_columns(query, resolve_in=inner)
return query
def _build_counter_query(self) -> ast.SelectQuery:
@@ -467,7 +560,7 @@ class MetricQueryRunner:
attributes,
resource_attributes,
lagInFrame(toNullable(value)) OVER (
- PARTITION BY service_name, resource_fingerprint, toString(attributes)
+ PARTITION BY {series_key}
ORDER BY timestamp ASC
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
) AS prev_value
@@ -486,6 +579,7 @@ class MetricQueryRunner:
placeholders={
"interval": _interval_expr(self.interval),
"divisor": ast.Constant(value=divisor),
+ "series_key": ast.Tuple(exprs=_series_key_exprs()),
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
@@ -533,7 +627,7 @@ class MetricQueryRunner:
histogram_bounds,
arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,
lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (
- PARTITION BY service_name, resource_fingerprint, toString(attributes)
+ PARTITION BY {series_key}
ORDER BY timestamp ASC
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
) AS prev_counts
@@ -552,6 +646,7 @@ class MetricQueryRunner:
""",
placeholders={
"interval": _interval_expr(self.interval),
+ "series_key": ast.Tuple(exprs=_series_key_exprs()),
"metric_name": ast.Constant(value=self.metric_name),
"date_from": ast.Constant(value=self.date_from),
"date_to": ast.Constant(value=self.date_to),
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 6577f436cc8f..727e6b666688 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -136,7 +136,7 @@ class _MetricQueryBodySerializer(serializers.Serializer):
aggregation = serializers.ChoiceField(
choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],
default="sum",
- help_text="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'.",
+ help_text="Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. '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'.",
)
quantile = serializers.FloatField(
required=False,
diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.py
index faf5d7f44346..79e79173adba 100644
--- a/products/metrics/backend/tests/_seeder.py
+++ b/products/metrics/backend/tests/_seeder.py
@@ -60,6 +60,12 @@ def seed_metric(
) -> None:
"""Insert one row per `(timestamp, value)` point into `metrics1`.
+ Every point in one call is a sample of the *same* series, since the series
+ identity (`service_name`, `metric_type`, both attribute maps) is fixed per
+ call. Aggregations reduce each series to one value per bucket, so several
+ points in one bucket collapse to the last one. Seed distinct series with
+ separate calls.
+
`labels` populates the per-data-point `attributes_map_str` map (with the
`__str` type-tag suffix the schema expects). `resource_labels` populates
`resource_attributes` directly — those are tag-free.
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 685c9b7157aa..c42ba1e2470e 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -146,9 +146,15 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
metric_name="m1",
points=[
(anchor - dt.timedelta(minutes=5), 2.0),
- (anchor - dt.timedelta(minutes=5), 3.0),
(anchor - dt.timedelta(minutes=20), 4.0),
],
+ labels={"pod": "a"},
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=5), 3.0)],
+ labels={"pod": "b"},
)
# Different metric — should be filtered out.
seed_metric(
@@ -169,6 +175,62 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
values_by_bucket = {row["time"]: row["value"] for row in results}
self.assertEqual(sum(values_by_bucket.values()), 9.0)
+ @parameterized.expand(
+ [
+ # Summing raw samples would give 66 (every sample counted), and
+ # scrape count is not constant across buckets, so the error moves.
+ ("sum", 33.0),
+ # Sample-weighted would be 11.0.
+ ("avg", 16.5),
+ # Counting raw samples would give 6.
+ ("count", 2.0),
+ ]
+ )
+ def test_aggregations_run_across_series_not_samples(self, aggregation: str, expected: float):
+ anchor = timezone.now().replace(second=0, microsecond=0)
+ bucket = anchor - dt.timedelta(minutes=5)
+ for pod, values in (("a", (1.0, 2.0, 3.0)), ("b", (10.0, 20.0, 30.0))):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m_multi",
+ points=[(bucket + dt.timedelta(seconds=10 * i), value) for i, value in enumerate(values)],
+ labels={"pod": pod},
+ )
+
+ runner = MetricQueryRunner(
+ team=self.team,
+ metric_name="m_multi",
+ aggregation=aggregation,
+ date_from=anchor - dt.timedelta(hours=1),
+ date_to=anchor,
+ )
+
+ self.assertEqual([row["value"] for row in runner.run()], [expected])
+
+ def test_synthetic_original_timestamp_does_not_split_a_series(self):
+ anchor = timezone.now().replace(second=0, microsecond=0)
+ bucket = anchor - dt.timedelta(minutes=5)
+ # Ingest stamps `$originalTimestamp` on a point whose timestamp it had to
+ # override, with a different value per sample, and excludes it from the
+ # series identity it computes. Counting it here would give 6.0.
+ for index, value in enumerate((1.0, 2.0, 3.0)):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m_skewed",
+ points=[(bucket + dt.timedelta(seconds=10 * index), value)],
+ labels={"pod": "a", "$originalTimestamp": f"2020-01-0{index + 1}T00:00:00+00:00"},
+ )
+
+ runner = MetricQueryRunner(
+ team=self.team,
+ metric_name="m_skewed",
+ aggregation="sum",
+ date_from=anchor - dt.timedelta(hours=1),
+ date_to=anchor,
+ )
+
+ self.assertEqual([row["value"] for row in runner.run()], [3.0])
+
def test_respects_team_isolation(self):
anchor = timezone.now().replace(microsecond=0)
seed_metric(
@@ -238,10 +300,14 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):
seed_metric(
team_id=self.team.id,
metric_name="m1",
- points=[
- (anchor - dt.timedelta(minutes=10), 1.0),
- (anchor - dt.timedelta(minutes=10), 2.0),
- ],
+ points=[(anchor - dt.timedelta(minutes=10), 1.0)],
+ labels={"pod": "a"},
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=10), 2.0)],
+ labels={"pod": "b"},
)
response = self.client.post(
@@ -404,7 +470,14 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
seed_metric(
team_id=self.team.id,
metric_name="m1",
- points=[(anchor - dt.timedelta(minutes=10), 1.5), (anchor - dt.timedelta(minutes=10), 2.5)],
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ service_name="svc-a",
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=10), 2.5)],
+ service_name="svc-b",
)
series = run_metric_query(team=self.team, request=self._request())
@@ -1274,7 +1347,7 @@ class TestMetricTypeIsolation(ClickhouseTestMixin, APIBaseTest):
class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):
- """ClickHouse float aggregates can overflow to inf (two 1e308 samples in
+ """ClickHouse float aggregates can overflow to inf (two 1e308 series in
one bucket). A Python `inf` leaking into the response is at best invalid
JSON ("Infinity") and at worst a silent null downstream — the API contract
is an explicit null gap instead."""
@@ -1287,11 +1360,15 @@ class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):
self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
def _seed_huge(self, count: int) -> None:
- seed_metric(
- team_id=self.team.id,
- metric_name="m_huge",
- points=[(self.anchor + dt.timedelta(seconds=i), 1e308) for i in range(count)],
- )
+ # One series each: aggregation is across series, so repeated samples of
+ # a single series would collapse to one value and never overflow.
+ for index in range(count):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m_huge",
+ points=[(self.anchor, 1e308)],
+ labels={"shard": str(index)},
+ )
def _run(self, aggregation: str) -> list[dict[str, Any]]:
return MetricQueryRunner(
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index ff888457da4c..bdb4f5de1a5a 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -73,7 +73,7 @@ const SUMMARY_OPTIONS: { value: MetricSummary; label: string }[] = [
const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
{ value: 'sum', label: 'Sum' },
{ value: 'avg', label: 'Average' },
- { value: 'count', label: 'Count' },
+ { value: 'count', label: 'Series count' },
{ value: 'p95', label: 'p95' },
{ value: 'rate', label: 'Rate (/s)' },
{ value: 'increase', label: 'Increase' },
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index c12e5467f08b..6a3609eee707 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -576,7 +576,7 @@ export interface _MetricQueryBodyApi {
* * `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'.
+ /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. '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` - sum
* * `avg` - avg
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index c837c7e821af..444630691705 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -277,7 +277,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
)
.default(metricsQueryCreateBodyQueryOneAggregationDefault)
.describe(
- "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'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
+ "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. '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'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
),
quantile: zod
.number()
diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.md
index b2aa7d65e687..78ad70d7fb3d 100644
--- a/products/metrics/mcp/prompts/query-metrics.md
+++ b/products/metrics/mcp/prompts/query-metrics.md
@@ -11,6 +11,7 @@ All parameters are nested inside a `query` object. Two request forms:
2. **Pick the aggregation by metric type:**
- `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.
- `gauge`: `avg` (typical), `p95`, `sum`.
+ - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.
- `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.
3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.
4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 7d3ddf34397f..ef1b963fb40e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8317,7 +8317,7 @@
"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"
},
"query-metrics": {
- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.",
+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.",
"category": "Metrics",
"feature": "metrics",
"summary": "Query metrics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a5e6c2dfa7c2..eb6fd4aed365 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8844,7 +8844,7 @@
"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"
},
"query-metrics": {
- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.",
+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters are nested inside a `query` object. Two request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.",
"category": "Metrics",
"feature": "metrics",
"summary": "Query metrics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0db2e71d83e7..fe01afcb9341 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -84185,7 +84185,7 @@ export namespace Schemas {
* * `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'.
+ /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. '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` - sum
* * `avg` - avg
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index bcfbd009c471..a063a9d3b146 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -193,7 +193,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
)
.default(metricsQueryCreateBodyQueryOneAggregationDefault)
.describe(
- "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'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
+ "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. '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'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
),
quantile: zod
.number()