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): give the first chart bucket its whole interval (#89624)

Daniel Visca41baaef9c8ff
diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.py
index 122eb6ec620a..5f48fa03624e 100644
--- a/products/metrics/backend/diagnostics.py
+++ b/products/metrics/backend/diagnostics.py
@@ -234,6 +234,13 @@ def decompose_bucket(
for key in ordered_keys[:max_series]:
samples = grouped[key]
service_name, labels, resource_labels = identities[key]
+ if plan.temporal is TemporalReducer.POOLED_SAMPLES:
+ series_value = None
+ else:
+ # Normalized the same way as the bucket's total, so the series
+ # a reader adds up still reach the number they are explaining.
+ reduced = reduce_temporal(reduction_input[key], plan.temporal)
+ series_value = None if reduced is None else reduced / plan.divisor
breakdown.append(
MetricSeriesBreakdown(
service_name=service_name,
@@ -245,11 +252,7 @@ def decompose_bucket(
),
sample_count=len(samples),
samples_truncated=len(samples) > max_samples_per_series,
- # Normalized the same way as the bucket's total, so the series
- # a reader adds up still reach the number they are explaining.
- value=None
- if plan.temporal is TemporalReducer.POOLED_SAMPLES
- else reduce_temporal(reduction_input[key], plan.temporal) / plan.divisor,
+ value=series_value,
)
)
diff --git a/products/metrics/backend/fundamentals.py b/products/metrics/backend/fundamentals.py
index fc3ceaf14a00..5fa5753ce4b5 100644
--- a/products/metrics/backend/fundamentals.py
+++ b/products/metrics/backend/fundamentals.py
@@ -176,11 +176,24 @@ def _deduped_in_time_order(samples: Sequence[Sample]) -> list[Sample]:
return list(by_timestamp.values())
-def reduce_temporal(samples: Sequence[Sample], reducer: TemporalReducer) -> float:
- """Collapse one series' samples to that series' value for the bucket."""
+def reduce_temporal(samples: Sequence[Sample], reducer: TemporalReducer) -> float | None:
+ """Collapse one series' samples to that series' value for the bucket.
+
+ Returns None when the value is unknowable: a lone cumulative reading has
+ no predecessor to diff against, and 0 would read as a flat counter.
+ """
if reducer in (TemporalReducer.NONE, TemporalReducer.POOLED_SAMPLES):
raise ValueError(f"{reducer!r} has no single per-series value; apply it through a plan")
ordered = _deduped_in_time_order(samples)
+ if reducer == TemporalReducer.INCREASE:
+ # A reading below its predecessor means the counter restarted, and the
+ # post-restart reading is itself the increase.
+ if len(ordered) < 2:
+ return None
+ total = 0.0
+ for previous, current in zip(ordered, ordered[1:]):
+ total += current.value - previous.value if current.value >= previous.value else current.value
+ return total
if not ordered:
return 0.0
@@ -190,14 +203,6 @@ def reduce_temporal(samples: Sequence[Sample], reducer: TemporalReducer) -> floa
return sum(sample.value for sample in ordered)
if reducer == TemporalReducer.AVG_OVER_TIME:
return sum(sample.value for sample in ordered) / len(ordered)
- if reducer == TemporalReducer.INCREASE:
- # The first sample's history is unknown, so it contributes nothing. A
- # reading below its predecessor means the counter restarted, and the
- # post-restart reading is itself the increase.
- total = 0.0
- for previous, current in zip(ordered, ordered[1:]):
- total += current.value - previous.value if current.value >= previous.value else current.value
- return total
raise ValueError(f"Unsupported temporal reducer: {reducer!r}")
@@ -247,7 +252,10 @@ def apply_plan(series_samples: Mapping[K, Sequence[Sample]], plan: ReductionPlan
sample.value for samples in series_samples.values() for sample in _deduped_in_time_order(samples)
]
else:
- per_series_values = [reduce_temporal(samples, plan.temporal) for samples in series_samples.values() if samples]
+ # An unknowable series value contributes nothing rather than a fake 0,
+ # and a bucket holding only unknowns has no value at all.
+ reduced = (reduce_temporal(samples, plan.temporal) for samples in series_samples.values() if samples)
+ per_series_values = [value for value in reduced if value is not None]
value = reduce_spatial(per_series_values, plan.spatial, quantile=plan.quantile)
# An empty bucket has no number, and normalizing None would invent one.
return value if value is None else value / plan.divisor
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index db3c9941d0eb..17e60eeba3d9 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -42,10 +42,12 @@ _ROW_LIMIT = 10000
# Widest queryable range. Counter/histogram queries scan raw samples within
# the range on the ClickHouse cluster shared with the live logs/traces
-# products, so the span has to be bounded. Those two also scan
-# `counter_lookback(interval)` before `date_from` for a predecessor sample;
-# the bound stays on the requested range, since the extra reach costs at most
-# one more daily partition and returns no extra rows.
+# products, so the span has to be bounded. The bound stays on the requested
+# range: `date_from` snaps back to its bucket boundary and the counter and
+# histogram scans reach a further `counter_lookback(interval)` for a
+# predecessor sample, so the scan exceeds the request by under one interval
+# step plus the lookback (up to two weeks of extra daily partitions at the
+# `week` interval, a single one on the common sub-day charts).
MAX_QUERY_SPAN = dt.timedelta(days=31)
# These run on the shared logs cluster; cap how much one query may read.
@@ -260,6 +262,34 @@ def _interval_step(name: str) -> dt.timedelta:
raise ValueError(f"Unknown interval: {name!r}")
+# The grids `toStartOfInterval` produces: intervals count from the epoch,
+# except weeks, which count from a Monday.
+_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
+_WEEK_EPOCH = dt.datetime(1970, 1, 5, tzinfo=dt.UTC)
+
+
+def _align_to_interval(timestamp: dt.datetime, interval: str) -> dt.datetime:
+ """Floor `timestamp` onto the bucket grid `toStartOfInterval` uses.
+
+ The bucket labels come from `toStartOfInterval(sample_timestamp)`, so a
+ `date_from` inside a bucket would make that first bucket partial: labelled
+ as the whole interval but covering only the slice after `date_from`. Every
+ query scans and clips from this floor instead, so the first bucket holds
+ its full interval. Relative ranges like "-1h" resolve to now-minus-offset
+ with second precision, which makes the unaligned case the normal one.
+
+ Not `posthog.interval_specs.align`: that grid honors the team's
+ `week_start_day` and lacks the sub-hour steps, where `toStartOfInterval`
+ always counts weeks from Monday — the two would disagree exactly where
+ agreement with the SQL is the point.
+ """
+ if timestamp.tzinfo is None:
+ timestamp = timestamp.replace(tzinfo=dt.UTC)
+ epoch = _WEEK_EPOCH if interval == "week" else _EPOCH
+ step = _interval_step(interval)
+ return epoch + ((timestamp - epoch) // step) * step
+
+
# Prometheus's default lookback delta. One interval step on its own is not
# enough when the scrape interval is coarser than the bucket — a 60s scrape on
# a `second` or `minute` chart — and `metrics1` is partitioned by day with
@@ -273,9 +303,9 @@ def counter_lookback(interval: str) -> dt.timedelta:
Those aggregations diff each sample against the one before it, so the last
sample *outside* the requested range is an input to the first bucket inside
- it. Without it the first bucket diffs against nothing and plots 0
- (histograms drop the point instead). The pre-range rows are cut again
- before bucketing, so the returned grid is exactly the requested range.
+ it. Without it the first bucket diffs against nothing and is dropped as
+ uncomputable. The pre-range rows are cut again before bucketing, so the
+ returned grid is exactly the requested range.
`diagnostics.decompose_bucket` reads its raw samples over the same window
through this helper: a shorter reach there would find a different
@@ -371,11 +401,13 @@ class MetricQueryRunner:
self.team = team
self.metric_name = metric_name
self.aggregation = aggregation
- self.date_from = date_from
+ self.interval = interval or _pick_interval(date_from, date_to)
+ # Validation above bounds the requested range; the scan then starts at
+ # the bucket boundary so the first bucket covers its whole interval.
+ self.date_from = _align_to_interval(date_from, self.interval)
self.date_to = date_to
self.filters = tuple(filters)
self.group_by = tuple(group_by)
- self.interval = interval or _pick_interval(date_from, date_to)
self.quantile = quantile
self.metric_type = metric_type
@@ -559,8 +591,10 @@ class MetricQueryRunner:
- cumulative temporality: contribution = value - prev, clamped for
counter resets (value < prev means the counter restarted, so the
post-reset absolute value IS the increase); a sample with no
- predecessor within `counter_lookback` contributes 0 (its history is
- unknown).
+ predecessor within `counter_lookback` has an unknowable increase, so
+ it contributes NULL, and a bucket where nothing was computable is
+ dropped rather than plotted as 0 (the histogram path drops such
+ buckets too).
- delta temporality: each sample already is the increase, so it
contributes its own value.
@@ -586,7 +620,7 @@ class MetricQueryRunner:
resource_attributes AS resource_attributes,
multiIf(
aggregation_temporality = 'delta', value,
- isNull(prev_value), 0.0,
+ isNull(prev_value), NULL,
value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),
value
) AS contribution
@@ -613,6 +647,7 @@ class MetricQueryRunner:
)
WHERE sample_timestamp >= {date_from}
GROUP BY time
+ HAVING isNotNull(value)
ORDER BY time ASC
LIMIT {row_limit}
""",
diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.py
index 8ea4ed7c835f..6d4dd5288662 100644
--- a/products/metrics/backend/tests/test_diagnostics.py
+++ b/products/metrics/backend/tests/test_diagnostics.py
@@ -140,6 +140,30 @@ class TestBucketDecomposition(ClickhouseTestMixin, APIBaseTest):
# +20, then a restart whose post-reset reading is itself the increase.
assert decomposition.reference_value == 25.0
+ def test_lone_cumulative_sample_has_no_increase_on_either_side(self) -> None:
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="bytes_total",
+ metric_type="sum",
+ aggregation_temporality="cumulative",
+ is_monotonic=True,
+ points=[(BUCKET, 100.0)],
+ )
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="bytes_total",
+ aggregation="increase",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ # The sample's history is unknown, so both the reference and the chart
+ # return no value — a 0 on either side would fabricate a flat counter.
+ assert decomposition.reference_value is None
+ assert decomposition.actual_value is None
+ assert decomposition.agrees is True
+
def test_empty_bucket_reports_no_series_rather_than_zero(self) -> None:
decomposition = decompose_bucket(
team=self.team,
diff --git a/products/metrics/backend/tests/test_fundamentals.py b/products/metrics/backend/tests/test_fundamentals.py
index f595767a8294..5a2bdc5603e9 100644
--- a/products/metrics/backend/tests/test_fundamentals.py
+++ b/products/metrics/backend/tests/test_fundamentals.py
@@ -87,8 +87,9 @@ class TestTemporalReduction:
# 100 -> 120 is +20; the drop to 5 is a restart, so 5 itself is the increase; 5 -> 25 is +20.
assert reduce_temporal(_samples(100, 120, 5, 25), TemporalReducer.INCREASE) == 45
- def test_increase_ignores_history_before_the_first_sample(self) -> None:
- assert reduce_temporal(_samples(100), TemporalReducer.INCREASE) == 0
+ def test_increase_of_a_lone_sample_is_unknown_not_zero(self) -> None:
+ # One reading has no predecessor to diff against; 0 would read as "flat".
+ assert reduce_temporal(_samples(100), TemporalReducer.INCREASE) is None
def test_avg_over_time_keeps_the_whole_bucket_not_just_the_tail(self) -> None:
# A queue that spiked to 240 and settled at 8 did not average 8.
@@ -119,6 +120,14 @@ class TestSpatialReduction:
# returned 0 here would report every empty bucket as a disagreement.
assert reduce_spatial([], reducer) is None
+ def test_unknown_series_values_drop_out_rather_than_zeroing_the_bucket(self) -> None:
+ plan = plan_reduction(aggregation="increase", metric_type="sum", temporality="cumulative")
+ # A lone-sample series adds nothing to the total, and a bucket holding
+ # only such series has no value at all — mirroring the runner, which
+ # drops the bucket instead of plotting 0.
+ assert apply_plan({"a": _samples(100), "b": _samples(10, 25)}, plan) == 15.0
+ assert apply_plan({"a": _samples(100)}, plan) is None
+
class TestPooledQuantile:
def test_percentile_reads_the_samples_rather_than_one_value_per_series(self) -> None:
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 7a19940b41c8..1d41eaeb76a3 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -22,7 +22,9 @@ from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupB
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.metric_query_runner import (
+ _INTERVAL_LADDER,
MetricQueryRunner,
+ _align_to_interval,
_histogram_quantile,
_pick_interval,
attribute_field,
@@ -46,6 +48,33 @@ class TestPickInterval:
assert _pick_interval(start, start + delta) == expected
+class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):
+ @parameterized.expand([(name,) for name, _, _ in _INTERVAL_LADDER])
+ def test_matches_clickhouse_bucket_boundaries(self, interval: str) -> None:
+ # The runner snaps date_from onto the bucket grid before querying; if
+ # this floor ever disagrees with toStartOfInterval, first buckets go
+ # partial again.
+ awkward = dt.datetime(2026, 3, 11, 17, 47, 33, 123456, tzinfo=dt.UTC)
+ aligned = _align_to_interval(awkward, interval)
+
+ interval_call = next(expr for name, _, expr in _INTERVAL_LADDER if name == interval)
+ interval_arg = interval_call.args[0]
+ assert isinstance(interval_arg, ast.Constant)
+ interval_sql = f"{interval_call.name}({interval_arg.value})"
+ ((clickhouse_aligned,),) = sync_execute(
+ f"SELECT toStartOfInterval(toDateTime64(%(ts)s, 6, 'UTC'), {interval_sql})",
+ {"ts": awkward.strftime("%Y-%m-%d %H:%M:%S.%f")},
+ )
+ if not isinstance(clickhouse_aligned, dt.datetime):
+ # Week intervals come back as a bare Date.
+ clickhouse_aligned = dt.datetime.combine(clickhouse_aligned, dt.time(), tzinfo=dt.UTC)
+ elif clickhouse_aligned.tzinfo is None:
+ clickhouse_aligned = clickhouse_aligned.replace(tzinfo=dt.UTC)
+
+ self.assertEqual(aligned, clickhouse_aligned)
+ self.assertLessEqual(aligned, awkward)
+
+
class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
@@ -207,6 +236,39 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([row["value"] for row in runner.run()], [expected])
+ def test_unaligned_date_from_reads_the_whole_first_bucket(self):
+ # The viewer's relative presets ("-1h") resolve to now-minus-offset with
+ # second precision, so date_from usually lands inside a bucket. A series
+ # whose only report came before date_from but inside that bucket must
+ # still count — the bucket stands for its whole interval.
+ anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor + dt.timedelta(seconds=5), 3.0)],
+ labels={"pod": "a"},
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor + dt.timedelta(seconds=40), 4.0)],
+ labels={"pod": "b"},
+ )
+
+ rows = MetricQueryRunner(
+ team=self.team,
+ metric_name="m1",
+ aggregation="sum",
+ date_from=anchor + dt.timedelta(seconds=20),
+ date_to=anchor + dt.timedelta(minutes=1),
+ interval="minute",
+ ).run()
+
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["value"], 7.0)
+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
+ self.assertEqual(earliest, anchor)
+
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)
@@ -821,6 +883,52 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):
earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))
+ @parameterized.expand(
+ [
+ ("increase", [20.0, 20.0, 20.0]),
+ ("rate", [20.0 / 60.0, 20.0 / 60.0, 20.0 / 60.0]),
+ ]
+ )
+ def test_unaligned_date_from_still_charts_a_complete_first_bucket(self, aggregation: str, expected: list[float]):
+ # date_from usually lands inside a bucket (relative presets resolve to
+ # now-minus-offset with second precision). The first bucket must cover
+ # its whole interval, not just the slice after date_from.
+ self._seed_counter([(self.anchor + dt.timedelta(seconds=s), 100.0 + s / 3.0) for s in range(-60, 181, 15)])
+ rows = self._run(
+ aggregation,
+ date_from=self.anchor + dt.timedelta(seconds=20),
+ date_to=self.anchor + dt.timedelta(minutes=3),
+ )
+ for row, expected_value in zip(rows, expected):
+ self.assertAlmostEqual(row["value"], expected_value)
+ self.assertEqual(len(rows), len(expected))
+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
+ self.assertEqual(earliest, self.anchor)
+
+ def test_bucket_with_no_computable_increase_is_dropped_not_zero(self):
+ # Scraped every 10 minutes: the first in-range sample's predecessor sits
+ # beyond counter_lookback, so its increase is unknowable. Unknown must
+ # be a missing point, not a plotted 0 — the histogram path already
+ # drops such buckets.
+ start = self.anchor - dt.timedelta(minutes=self.anchor.minute % 5)
+ self._seed_counter(
+ [
+ (start - dt.timedelta(minutes=10), 100.0),
+ (start, 200.0),
+ (start + dt.timedelta(minutes=10), 300.0),
+ (start + dt.timedelta(minutes=20), 400.0),
+ ]
+ )
+ rows = self._run(
+ "increase",
+ date_from=start,
+ date_to=start + dt.timedelta(minutes=30),
+ interval="minute_5",
+ )
+ self.assertEqual([row["value"] for row in rows], [100.0, 100.0])
+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
+ self.assertEqual(earliest, start + dt.timedelta(minutes=10))
+
def test_rate_divides_by_bucket_seconds(self):
self._seed_counter(
[
@@ -1057,6 +1165,29 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):
earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))
+ def test_unaligned_date_from_keeps_the_first_buckets_full_distribution(self):
+ # Growth recorded before date_from but inside the first bucket is part
+ # of that bucket's distribution; clipping at date_from skews the
+ # quantile toward whatever happened to grow last.
+ self._seed_histogram(
+ [
+ (self.anchor, [100, 100, 100, 0]),
+ (self.anchor + dt.timedelta(seconds=20), [110, 100, 100, 0]),
+ (self.anchor + dt.timedelta(seconds=40), [110, 110, 100, 0]),
+ ],
+ temporality="cumulative",
+ )
+ rows = self._run(
+ 0.5,
+ date_from=self.anchor + dt.timedelta(seconds=30),
+ date_to=self.anchor + dt.timedelta(minutes=1),
+ )
+ self.assertEqual(len(rows), 1)
+ # Window contribution [10, 10, 0, 0]: p50 sits in the first bucket.
+ self.assertAlmostEqual(rows[0]["value"], 0.1)
+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)
+ self.assertEqual(earliest, self.anchor)
+
def test_mismatched_bounds_raise(self):
self._seed_histogram([(self.anchor + dt.timedelta(seconds=0), [1, 1, 1, 0])], temporality="delta")
self._seed_histogram(
diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.md
index 78ad70d7fb3d..de9922552294 100644
--- a/products/metrics/mcp/prompts/query-metrics.md
+++ b/products/metrics/mcp/prompts/query-metrics.md
@@ -25,4 +25,4 @@ All parameters are nested inside a `query` object. Two request forms:
4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.
5. 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.
-CRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now.
+CRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b286f82f61aa..5954cc97a800 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8494,7 +8494,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 - 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.",
+ "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. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
"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 92508d86d423..57a6ada7a0de 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9021,7 +9021,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 - 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.",
+ "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. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
"category": "Metrics",
"feature": "metrics",
"summary": "Query metrics",