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.

feat(metrics): add a Fundamentals tab that checks a chart point against its raw samples (#86775)

Daniel Visca8e92eee3f619
diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.py
new file mode 100644
index 000000000000..5ac83f99763d
--- /dev/null
+++ b/products/metrics/backend/diagnostics.py
@@ -0,0 +1,305 @@
+"""Recompute one chart point from its raw samples, and show the working.
+
+A metrics chart is several reductions deep by the time it reaches a pixel, and
+every one of them returns a plausible-looking number when it is wrong. The only
+way to know a point is right is to take the bucket apart: which series reported,
+what each one sent, what each collapsed to, and how those combined.
+
+`decompose_bucket` does that twice over. It reduces the raw samples in Python
+through `fundamentals`, and separately asks `MetricQueryRunner` for the same
+point. Two independent paths to one number means a disagreement is visible
+rather than inferred — and the per-series breakdown alongside it shows which
+step diverged.
+
+The Python side is deliberately not built from the HogQL builders. A reference
+that shares its assumptions with the thing it checks agrees with it by
+construction and catches nothing.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from collections.abc import Sequence
+from dataclasses import replace
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.models import Team
+
+from products.metrics.backend.facade.contracts import (
+ MetricBucketDecomposition,
+ MetricFilter,
+ MetricSampleView,
+ MetricSeriesBreakdown,
+)
+from products.metrics.backend.fundamentals import Sample, TemporalReducer, apply_plan, plan_reduction, reduce_temporal
+from products.metrics.backend.metric_query_runner import (
+ _INTERVAL_LADDER,
+ _QUERY_SETTINGS,
+ MetricQueryRunner,
+ filters_expr,
+ type_filter_expr,
+)
+
+# How much of a bucket the breakdown lists. Totals are computed over everything
+# in the bucket; these only bound what gets rendered, and the decomposition says
+# so when it has trimmed something.
+DEFAULT_MAX_SERIES = 20
+DEFAULT_MAX_SAMPLES_PER_SERIES = 12
+
+# A bucket on a wide metric can hold millions of rows. Reading every one to
+# explain a single point is not worth the cluster time, so the raw read is
+# bounded and reports when it hit the bound.
+_MAX_ROWS_READ = 50000
+
+
+def _interval_step(interval: str) -> dt.timedelta:
+ """The bucket's width, from the same ladder the chart uses."""
+ for name, step, _ in _INTERVAL_LADDER:
+ if name == interval:
+ return step
+ raise ValueError(f"Unknown interval: {interval!r}")
+
+
+def _as_utc(timestamp: dt.datetime) -> dt.datetime:
+ """ClickHouse hands timestamps back naive; the bucket edges are aware."""
+ return timestamp.replace(tzinfo=dt.UTC) if timestamp.tzinfo is None else timestamp.astimezone(dt.UTC)
+
+
+def _raw_samples_query(
+ *,
+ metric_name: str,
+ date_from: dt.datetime,
+ bucket_end: dt.datetime,
+ filters: Sequence[MetricFilter],
+ metric_type: str | None,
+) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT
+ service_name,
+ attributes,
+ resource_attributes,
+ metric_type,
+ aggregation_temporality,
+ timestamp,
+ value
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND timestamp >= {date_from}
+ AND timestamp < {date_to}
+ AND {filters}
+ AND {type_filter}
+ ORDER BY timestamp ASC
+ LIMIT {row_limit}
+ """,
+ placeholders={
+ "metric_name": ast.Constant(value=metric_name),
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=bucket_end),
+ "filters": filters_expr(filters),
+ "type_filter": type_filter_expr(metric_type),
+ "row_limit": ast.Constant(value=_MAX_ROWS_READ),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
+def _actual_value(
+ *,
+ team: Team,
+ metric_name: str,
+ aggregation: str,
+ date_from: dt.datetime,
+ bucket_start: dt.datetime,
+ bucket_end: dt.datetime,
+ interval: str,
+ filters: Sequence[MetricFilter],
+ metric_type: str | None,
+ quantile: float | None,
+) -> float | None:
+ """What the product would plot for this point, through the real runner.
+
+ `date_from` reaches back one bucket for the counter functions so the
+ runner's window function sees the predecessor sample, exactly as it does
+ under the chart; only the requested bucket's row is returned.
+ """
+ rows = MetricQueryRunner(
+ team=team,
+ metric_name=metric_name,
+ aggregation=aggregation,
+ date_from=date_from,
+ date_to=bucket_end,
+ interval=interval,
+ filters=filters,
+ metric_type=metric_type,
+ quantile=quantile,
+ ).run()
+ for row in rows:
+ if _as_utc(dt.datetime.fromisoformat(row["time"])) == bucket_start:
+ return row["value"]
+ return None
+
+
+def decompose_bucket(
+ *,
+ team: Team,
+ metric_name: str,
+ aggregation: str,
+ bucket_start: dt.datetime,
+ interval: str,
+ filters: Sequence[MetricFilter] = (),
+ metric_type: str | None = None,
+ quantile: float | None = None,
+ max_series: int = DEFAULT_MAX_SERIES,
+ max_samples_per_series: int = DEFAULT_MAX_SAMPLES_PER_SERIES,
+) -> MetricBucketDecomposition:
+ """Take one chart point apart into the series and samples behind it."""
+ bucket_start = _as_utc(bucket_start)
+ step = _interval_step(interval)
+ bucket_end = bucket_start + step
+ # The counter functions diff against the last sample before the bucket, the
+ # way the chart's window function does, so their raw read reaches back one
+ # bucket for that predecessor.
+ needs_boundary = aggregation in ("rate", "increase")
+ date_from = bucket_start - step if needs_boundary else bucket_start
+
+ response = execute_hogql_query(
+ query_type="MetricBucketDecomposition",
+ query=_raw_samples_query(
+ metric_name=metric_name,
+ date_from=date_from,
+ bucket_end=bucket_end,
+ filters=filters,
+ metric_type=metric_type,
+ ),
+ team=team,
+ workload=Workload.LOGS,
+ settings=_QUERY_SETTINGS,
+ )
+ rows = response.results or []
+ rows_truncated = len(rows) >= _MAX_ROWS_READ
+
+ # Group the raw rows into series, keyed the way a series is actually
+ # identified: everything that isn't the timestamp or the value.
+ grouped: dict[tuple, list[Sample]] = {}
+ predecessors: dict[tuple, Sample] = {}
+ identities: dict[tuple, tuple[str, dict[str, str], dict[str, str]]] = {}
+ resolved_type = metric_type or ""
+ temporality = ""
+ for service_name, attributes, resource_attributes, row_metric_type, row_temporality, timestamp, value in rows:
+ key = (
+ service_name,
+ tuple(sorted(dict(attributes).items())),
+ tuple(sorted(dict(resource_attributes).items())),
+ row_metric_type,
+ )
+ sample = Sample(timestamp=_as_utc(timestamp), value=float(value))
+ if sample.timestamp < bucket_start:
+ # Only a series' newest pre-bucket reading matters: it is the
+ # baseline its first in-bucket diff runs against.
+ held = predecessors.get(key)
+ if held is None or sample.timestamp > held.timestamp:
+ predecessors[key] = sample
+ else:
+ grouped.setdefault(key, []).append(sample)
+ identities.setdefault(key, (service_name, dict(attributes), dict(resource_attributes)))
+ # A bucket normally holds one type and one temporality; when a name has
+ # been ingested as several, the first is enough to plan a reduction and
+ # the type check reports the blend separately.
+ resolved_type = resolved_type or row_metric_type
+ temporality = temporality or row_temporality
+
+ plan = plan_reduction(
+ aggregation=aggregation,
+ metric_type=resolved_type,
+ temporality=temporality,
+ interval_seconds=step.total_seconds(),
+ )
+ if quantile is not None:
+ plan = replace(plan, quantile=quantile)
+
+ # Delta increments before the bucket belong to the previous point, so only
+ # the odometer-style reduction gets its baseline prepended.
+ if plan.temporal is TemporalReducer.INCREASE:
+ reduction_input = {
+ key: ([predecessors[key], *samples] if key in predecessors else samples) for key, samples in grouped.items()
+ }
+ else:
+ reduction_input = grouped
+
+ reference_value = apply_plan(reduction_input, plan)
+
+ # Largest contributors first — that is what someone reading a surprising
+ # total wants to see, and it makes the trimmed tail the least interesting part.
+ ordered_keys = sorted(grouped, key=lambda key: (-len(grouped[key]), identities[key][0]))
+ breakdown: list[MetricSeriesBreakdown] = []
+ for key in ordered_keys[:max_series]:
+ samples = grouped[key]
+ service_name, labels, resource_labels = identities[key]
+ breakdown.append(
+ MetricSeriesBreakdown(
+ service_name=service_name,
+ labels=labels,
+ resource_labels=resource_labels,
+ samples=tuple(
+ MetricSampleView(time=sample.timestamp.isoformat(), value=sample.value)
+ for sample in samples[:max_samples_per_series]
+ ),
+ 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,
+ )
+ )
+
+ actual_value = _actual_value(
+ team=team,
+ metric_name=metric_name,
+ aggregation=aggregation,
+ date_from=date_from,
+ bucket_start=bucket_start,
+ bucket_end=bucket_end,
+ interval=interval,
+ filters=filters,
+ metric_type=metric_type,
+ quantile=quantile,
+ )
+
+ return MetricBucketDecomposition(
+ metric_name=metric_name,
+ metric_type=resolved_type,
+ temporality=temporality,
+ aggregation=aggregation,
+ bucket_start=bucket_start.isoformat(),
+ interval=interval,
+ temporal_reducer=plan.temporal.value,
+ spatial_reducer=plan.spatial.value,
+ series=tuple(breakdown),
+ series_count=len(grouped),
+ sample_count=sum(len(samples) for samples in grouped.values()),
+ series_truncated=len(grouped) > max_series,
+ rows_truncated=rows_truncated,
+ reference_value=reference_value,
+ actual_value=actual_value,
+ # A truncated read means the reference covers only part of the bucket,
+ # so any verdict would be an artifact of the unequal inputs.
+ agrees=None if rows_truncated else _agrees(reference_value, actual_value),
+ )
+
+
+def _agrees(reference: float | None, actual: float | None) -> bool:
+ """Float reductions in ClickHouse and Python accumulate in different orders,
+ so exact equality would report noise as disagreement. The tolerance is far
+ tighter than any real reduction bug, which move totals by whole multiples."""
+ if reference is None or actual is None:
+ return reference is None and actual is None
+ scale = max(abs(reference), abs(actual), 1.0)
+ return abs(reference - actual) <= 1e-9 * scale
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 654e38b076ea..dd75b2ae5db5 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -13,11 +13,13 @@ from typing import Any
from posthog.models import Team
from products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomaly
+from products.metrics.backend.diagnostics import decompose_bucket as _decompose_bucket
from products.metrics.backend.facade.contracts import (
CompanionMetric,
IncidentContext,
InvestigationResult,
MetricAnomalyReport,
+ MetricBucketDecomposition,
MetricEventSample,
MetricFilter,
MetricPoint,
@@ -407,3 +409,34 @@ def investigate_incident(*, team: Team, context: IncidentContext) -> Investigati
filters=filters,
companions=context.companions,
)
+
+
+def explain_metric_bucket(
+ *,
+ team: Team,
+ metric_name: str,
+ aggregation: str,
+ bucket_start: dt.datetime,
+ interval: str,
+ filters: Sequence[MetricFilter] = (),
+ metric_type: MetricType | None = None,
+ quantile: float | None = None,
+) -> MetricBucketDecomposition:
+ """Take one chart point apart and show how it was built.
+
+ Returns the series that reported in the bucket, the samples each sent, and
+ the two reductions that combined them, alongside both the value the product
+ would plot and the value recomputed independently from the raw samples.
+ Reading them side by side is what makes an aggregation bug visible instead
+ of merely plausible. The presentation layer surfaces `ValueError` as a 400.
+ """
+ return _decompose_bucket(
+ team=team,
+ metric_name=metric_name,
+ aggregation=aggregation,
+ bucket_start=bucket_start,
+ interval=interval,
+ filters=filters,
+ metric_type=metric_type.value if metric_type is not None else None,
+ quantile=quantile,
+ )
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 8b29acf67413..435427d73891 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -307,3 +307,61 @@ class IncidentContext:
if self.fired_at.tzinfo is None:
raise ValueError("fired_at must be timezone-aware")
object.__setattr__(self, "fired_at", self.fired_at.astimezone(dt.UTC))
+
+
+@dataclass(frozen=True, slots=True)
+class MetricSampleView:
+ """One raw reading, as it sits in storage before any reduction."""
+
+ time: str
+ value: float
+
+
+@dataclass(frozen=True, slots=True)
+class MetricSeriesBreakdown:
+ """One physical series inside a bucket, and the value it contributed.
+
+ `samples` is trimmed for display; `sample_count` always reports how many
+ the series really sent, so a trimmed list can't be mistaken for a quiet one.
+ """
+
+ service_name: str
+ labels: dict[str, str]
+ resource_labels: dict[str, str]
+ samples: tuple[MetricSampleView, ...]
+ sample_count: int
+ samples_truncated: bool
+ # None when the aggregation has no per-series step, as percentiles do not:
+ # they read the pooled readings, so no single number is this series'
+ # contribution.
+ value: float | None
+
+
+@dataclass(frozen=True, slots=True)
+class MetricBucketDecomposition:
+ """One chart point taken apart into the series and samples behind it.
+
+ `reference_value` is recomputed from the raw samples independently of the
+ query builders; `actual_value` is what the product would plot. `agrees`
+ compares them, and is the part worth reading first — a mismatch means one
+ of the two reductions is wrong, and the breakdown shows where they parted.
+ """
+
+ metric_name: str
+ metric_type: str
+ temporality: str
+ aggregation: str
+ bucket_start: str
+ interval: str
+ temporal_reducer: str
+ spatial_reducer: str
+ series: tuple[MetricSeriesBreakdown, ...]
+ series_count: int
+ sample_count: int
+ series_truncated: bool
+ rows_truncated: bool
+ reference_value: float | None
+ actual_value: float | None
+ # None when the raw read was truncated: the reference then covers only part
+ # of the bucket, so comparing it to the chart proves nothing either way.
+ agrees: bool | None
diff --git a/products/metrics/backend/fundamentals.py b/products/metrics/backend/fundamentals.py
new file mode 100644
index 000000000000..fc3ceaf14a00
--- /dev/null
+++ b/products/metrics/backend/fundamentals.py
@@ -0,0 +1,265 @@
+"""The reduction rules every metric aggregation has to follow, as data.
+
+A bucket is not a bag of numbers. It holds a set of *series*, and each series
+holds a set of *samples*. Collapsing it to one number is therefore two ordered
+steps, never one:
+
+ value(bucket) = spatial( over each series: temporal(its samples) )
+
+`plan_reduction` picks both steps from the metric's type and temporality, which
+is the part that is easy to get wrong by hand: a gauge sample is a re-reading
+(take the last), a cumulative counter sample is an odometer (diff it), and a
+delta counter sample is itself an increment (add them up). Applying one reducer
+to all three silently returns a number that tracks the scrape rate instead of
+the data.
+
+The reducers here are deliberately pure and independent of the HogQL builders in
+`metric_query_runner`, so they can serve as the reference a query result is
+checked against rather than a second copy of the same assumptions.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from collections.abc import Mapping, Sequence
+from enum import StrEnum
+from typing import TypeVar
+
+from posthog.dataclasses import frozen
+
+# What `p95` means when a caller doesn't spell the percentile out.
+_DEFAULT_QUANTILE = 0.95
+
+# The reducers never read a series key; it only has to identify the series.
+K = TypeVar("K")
+
+
+@frozen
+class Sample:
+ """One raw reading of one series."""
+
+ timestamp: dt.datetime
+ value: float
+
+
+class TemporalReducer(StrEnum):
+ """How one series' samples collapse to that series' value for the bucket."""
+
+ # No temporal step: every raw sample flows into the spatial reducer. This is
+ # the shape of the bug this module exists to catch, kept nameable so a
+ # decomposition can report it rather than only failing a check.
+ NONE = "none"
+ # Gauges under an instant aggregation: the bucket's value is the most
+ # recent reading, matching PromQL's instant vector.
+ LAST = "last"
+ # Gauges under an average: the readings inside the bucket are all real
+ # observations, so the series' value for the bucket is their mean.
+ AVG_OVER_TIME = "avg_over_time"
+ # Percentiles: there is no per-series step at all. A percentile describes a
+ # distribution, and collapsing each series first would compute a percentile
+ # of summaries, which is not a percentile of anything. Samples are deduped
+ # by timestamp and pooled instead.
+ POOLED_SAMPLES = "pooled_samples"
+ # Delta counters: each sample is an increment already.
+ SUM_OVER_TIME = "sum_over_time"
+ # Cumulative counters: diff consecutive readings, treating a drop as a restart.
+ INCREASE = "increase"
+
+
+class SpatialReducer(StrEnum):
+ """How one value per series collapses to the bucket's number."""
+
+ SUM = "sum"
+ AVG = "avg"
+ MIN = "min"
+ MAX = "max"
+ QUANTILE = "quantile"
+ COUNT_SERIES = "count_series"
+
+
+@frozen
+class ReductionPlan:
+ temporal: TemporalReducer
+ spatial: SpatialReducer
+ quantile: float | None = None
+ # `rate` is an increase per second, so its bucket total is divided by the
+ # time that total accumulated over. Every other aggregation plots the total.
+ divisor: float = 1.0
+
+
+_SPATIAL_BY_AGGREGATION: dict[str, SpatialReducer] = {
+ "sum": SpatialReducer.SUM,
+ "avg": SpatialReducer.AVG,
+ "min": SpatialReducer.MIN,
+ "max": SpatialReducer.MAX,
+ "count": SpatialReducer.COUNT_SERIES,
+ "p95": SpatialReducer.QUANTILE,
+ "quantile": SpatialReducer.QUANTILE,
+ "rate": SpatialReducer.SUM,
+ "increase": SpatialReducer.SUM,
+}
+
+_COUNTER_FUNCTIONS = frozenset({"rate", "increase"})
+
+
+def _is_delta(temporality: str) -> bool:
+ return temporality == "delta"
+
+
+def _rate_divisor(aggregation: str, interval_seconds: float | None) -> float:
+ """How long the bucket's total accumulated over, for the aggregations that
+ plot a per-second figure rather than the total itself.
+
+ Refusing to default the interval keeps a plan built without one from
+ quietly reporting an increase where a rate was asked for — off by the
+ bucket length, which is the whole difference between the two.
+ """
+ if aggregation != "rate":
+ return 1.0
+ if interval_seconds is None or interval_seconds <= 0:
+ raise ValueError("rate is a per-second figure, so it needs a positive interval_seconds")
+ return float(interval_seconds)
+
+
+def plan_reduction(
+ *,
+ aggregation: str,
+ metric_type: str,
+ temporality: str = "",
+ interval_seconds: float | None = None,
+) -> ReductionPlan:
+ """Pick the two reduction steps for one aggregation on one kind of metric.
+
+ `temporality` is the OTel `aggregation_temporality` column; gauges leave it
+ empty. It matters even for the instant aggregations, because a delta sample
+ is an increment rather than a reading.
+
+ `interval_seconds` is the bucket's width, which only `rate` needs.
+ """
+ try:
+ spatial = _SPATIAL_BY_AGGREGATION[aggregation]
+ except KeyError:
+ raise ValueError(f"Unsupported aggregation: {aggregation!r}")
+
+ quantile = _DEFAULT_QUANTILE if spatial == SpatialReducer.QUANTILE else None
+ divisor = _rate_divisor(aggregation, interval_seconds)
+
+ if _is_delta(temporality):
+ # Delta samples are increments whatever the caller asked for, so summing
+ # them over the bucket is the only reduction that keeps the total whole.
+ return ReductionPlan(
+ temporal=TemporalReducer.SUM_OVER_TIME, spatial=spatial, quantile=quantile, divisor=divisor
+ )
+ if aggregation in _COUNTER_FUNCTIONS:
+ return ReductionPlan(temporal=TemporalReducer.INCREASE, spatial=spatial, quantile=quantile, divisor=divisor)
+ if spatial == SpatialReducer.QUANTILE:
+ return ReductionPlan(
+ temporal=TemporalReducer.POOLED_SAMPLES, spatial=spatial, quantile=quantile, divisor=divisor
+ )
+ if spatial == SpatialReducer.AVG:
+ return ReductionPlan(
+ temporal=TemporalReducer.AVG_OVER_TIME, spatial=spatial, quantile=quantile, divisor=divisor
+ )
+ return ReductionPlan(temporal=TemporalReducer.LAST, spatial=spatial, quantile=quantile, divisor=divisor)
+
+
+def _deduped_in_time_order(samples: Sequence[Sample]) -> list[Sample]:
+ """One reading per timestamp, oldest first.
+
+ A series re-delivered by the collector arrives as two rows sharing a
+ timestamp. That is one observation, so anything that adds samples together
+ has to collapse it first or the total moves with delivery luck.
+ """
+ by_timestamp: dict[dt.datetime, Sample] = {}
+ for sample in sorted(samples, key=lambda s: s.timestamp):
+ by_timestamp.setdefault(sample.timestamp, 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."""
+ 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 not ordered:
+ return 0.0
+
+ if reducer == TemporalReducer.LAST:
+ return ordered[-1].value
+ if reducer == TemporalReducer.SUM_OVER_TIME:
+ 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}")
+
+
+def _quantile(sorted_values: Sequence[float], quantile: float) -> float:
+ """Linear interpolation between the closest ranks."""
+ if len(sorted_values) == 1:
+ return sorted_values[0]
+ position = quantile * (len(sorted_values) - 1)
+ lower_index = int(position)
+ upper_index = min(lower_index + 1, len(sorted_values) - 1)
+ weight = position - lower_index
+ return sorted_values[lower_index] * (1 - weight) + sorted_values[upper_index] * weight
+
+
+def reduce_spatial(values: Sequence[float], reducer: SpatialReducer, *, quantile: float | None = None) -> float | None:
+ """Combine one value per series into the bucket's number.
+
+ Returns None for an empty bucket, which consumers render as a gap rather
+ than as a zero.
+ """
+ # An empty bucket has no value at all, including no series count. Returning
+ # 0 here would make every gap look like a real zero.
+ if not values:
+ return None
+ if reducer == SpatialReducer.COUNT_SERIES:
+ return float(len(values))
+
+ if reducer == SpatialReducer.SUM:
+ return sum(values)
+ if reducer == SpatialReducer.AVG:
+ return sum(values) / len(values)
+ if reducer == SpatialReducer.MIN:
+ return min(values)
+ if reducer == SpatialReducer.MAX:
+ return max(values)
+ if reducer == SpatialReducer.QUANTILE:
+ return _quantile(sorted(values), quantile if quantile is not None else _DEFAULT_QUANTILE)
+ raise ValueError(f"Unsupported spatial reducer: {reducer!r}")
+
+
+def apply_plan(series_samples: Mapping[K, Sequence[Sample]], plan: ReductionPlan) -> float | None:
+ """Run both reduction steps over a bucket's series and return its number."""
+ if plan.temporal == TemporalReducer.NONE:
+ per_series_values = [sample.value for samples in series_samples.values() for sample in samples]
+ elif plan.temporal == TemporalReducer.POOLED_SAMPLES:
+ per_series_values = [
+ 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]
+ 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
+
+
+def is_duplicate_invariant(series_samples: Mapping[K, Sequence[Sample]], plan: ReductionPlan) -> bool:
+ """Whether re-delivering every sample leaves the bucket's number unchanged.
+
+ Duplicating a scrape is the cheapest way to ask whether a reduction counts
+ series or counts rows, and it needs no reference implementation to compare
+ against — a correct plan simply returns the same number twice.
+ """
+ baseline = apply_plan(series_samples, plan)
+ doubled = {key: [*samples, *samples] for key, samples in series_samples.items()}
+ return apply_plan(doubled, plan) == baseline
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 679735ea836b..6577f436cc8f 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -25,6 +25,7 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedR
from products.metrics.backend.facade.api import (
characterize_metric_anomaly,
+ explain_metric_bucket,
list_metric_attribute_keys,
list_metric_attribute_values,
list_metric_event_samples,
@@ -559,6 +560,130 @@ class _MetricSamplesResponseSerializer(serializers.Serializer):
)
+class _MetricExplainBodySerializer(serializers.Serializer):
+ metricName = serializers.CharField(
+ max_length=255,
+ help_text="Exact metric name whose bucket should be taken apart.",
+ )
+ metricType = serializers.ChoiceField(
+ choices=[t.value for t in MetricType],
+ required=False,
+ allow_null=True,
+ help_text="Constrain the bucket to one metric type. A name can exist as several types; without this, rows of every type sharing the name are decomposed together.",
+ )
+ aggregation = serializers.ChoiceField(
+ choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],
+ default="sum",
+ help_text="The aggregation whose result should be explained. 'histogram_quantile' is rejected: it reduces bucket-count arrays rather than scalar samples, so there is no per-series value to lay out.",
+ )
+ quantile = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ min_value=0.0,
+ max_value=1.0,
+ help_text="Quantile in (0, 1) applied across series. Defaults to 0.95 for the 'p95' aggregation.",
+ )
+ filters = _MetricFilterSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Label predicates ANDed together, matching the chart the point came from.",
+ )
+ bucketStart = serializers.DateTimeField(
+ help_text="Start of the bucket to explain, as returned in a query result's 'time'. ISO 8601.",
+ )
+ interval = serializers.ChoiceField(
+ choices=["second", "minute", "minute_5", "minute_15", "hour", "hour_6", "day", "week"],
+ help_text="Bucket size the point was plotted at. Must match the query that produced it, or the decomposition explains a different span.",
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ if attrs.get("aggregation") == "histogram_quantile":
+ raise serializers.ValidationError(
+ "'histogram_quantile' cannot be decomposed: it reduces bucket-count arrays rather than scalar samples."
+ )
+ return attrs
+
+
+class _MetricExplainRequestSerializer(serializers.Serializer):
+ query = _MetricExplainBodySerializer(help_text="The chart point to take apart.")
+
+
+class _MetricSampleViewSerializer(serializers.Serializer):
+ time = serializers.CharField(help_text="Sample timestamp, ISO 8601.")
+ value = serializers.FloatField(help_text="Raw stored reading, before any reduction.")
+
+
+class _MetricSeriesBreakdownSerializer(serializers.Serializer):
+ service_name = serializers.CharField(help_text="Service that reported this series.")
+ labels = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Per-data-point attributes identifying the series.",
+ )
+ resource_labels = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Resource attributes identifying the scrape target.",
+ )
+ samples = _MetricSampleViewSerializer(
+ many=True,
+ help_text="The series' raw samples in this bucket, oldest first, trimmed for display.",
+ )
+ sample_count = serializers.IntegerField(
+ help_text="How many samples the series actually sent, even when 'samples' was trimmed."
+ )
+ samples_truncated = serializers.BooleanField(help_text="Whether 'samples' lists fewer samples than arrived.")
+ value = serializers.FloatField(
+ allow_null=True,
+ help_text="What this series contributed after the per-series reduction. Null for percentiles, which read the pooled readings and so have no single per-series contribution.",
+ )
+
+
+class _MetricBucketDecompositionSerializer(serializers.Serializer):
+ metric_name = serializers.CharField(help_text="Metric that was decomposed.")
+ metric_type = serializers.CharField(help_text="OTel metric type observed in the bucket.")
+ temporality = serializers.CharField(
+ allow_blank=True,
+ help_text="OTel aggregation temporality observed in the bucket ('cumulative', 'delta', or empty for gauges).",
+ )
+ aggregation = serializers.CharField(help_text="Aggregation that was explained.")
+ bucket_start = serializers.CharField(help_text="Start of the explained bucket, ISO 8601.")
+ interval = serializers.CharField(help_text="Bucket size the point was plotted at.")
+ temporal_reducer = serializers.ChoiceField(
+ choices=["none", "last", "avg_over_time", "sum_over_time", "increase", "pooled_samples"],
+ help_text="How each series' samples were collapsed to one value: 'last' for an instant gauge reading, 'avg_over_time' for an average, 'sum_over_time' for delta counters, 'increase' for cumulative counters, and 'pooled_samples' for percentiles, which skip the per-series step entirely.",
+ )
+ spatial_reducer = serializers.ChoiceField(
+ choices=["sum", "avg", "min", "max", "quantile", "count_series"],
+ help_text="How the per-series values were combined into the bucket's number.",
+ )
+ series = _MetricSeriesBreakdownSerializer(
+ many=True,
+ help_text="The series behind the point, largest contributors first, trimmed for display.",
+ )
+ series_count = serializers.IntegerField(help_text="How many series reported in the bucket.")
+ sample_count = serializers.IntegerField(help_text="How many raw samples the bucket held across all series.")
+ series_truncated = serializers.BooleanField(help_text="Whether 'series' lists fewer series than reported.")
+ rows_truncated = serializers.BooleanField(
+ help_text="Whether the bucket held more raw rows than the decomposition reads. Totals are computed only over the rows that were read."
+ )
+ reference_value = serializers.FloatField(
+ allow_null=True,
+ help_text="The bucket's value recomputed from the raw samples, independently of the query builders. Null when no series reported.",
+ )
+ actual_value = serializers.FloatField(
+ allow_null=True,
+ help_text="The value the product would plot for this point. Null when the query returned no row.",
+ )
+ agrees = serializers.BooleanField(
+ allow_null=True,
+ help_text="Whether the two values match. False means one of the reductions is wrong, and the series breakdown shows where they parted. Null when the raw read was truncated, so the two are not comparable.",
+ )
+
+
+class _MetricExplainResponseSerializer(serializers.Serializer):
+ decomposition = _MetricBucketDecompositionSerializer(help_text="The bucket taken apart.")
+
+
@extend_schema(tags=["metrics"])
class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "metrics"
@@ -765,6 +890,58 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return Response({"results": [asdict(s) for s in samples]}, status=status.HTTP_200_OK)
+ @extend_schema(request=_MetricExplainRequestSerializer, responses={200: _MetricExplainResponseSerializer})
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["metrics:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
+ def explain(self, request: Request, *args, **kwargs) -> Response:
+ """Take one chart point apart into the series and samples behind it,
+ and recompute it independently so the plotted number can be checked
+ rather than trusted."""
+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)
+
+ body = _MetricExplainRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ query_data = body.validated_data["query"]
+
+ filters = tuple(
+ MetricFilter(key=f["key"], op=FilterOp(f["op"]), value=f["value"], scope=AttributeScope(f["scope"]))
+ for f in query_data.get("filters") or []
+ )
+ try:
+ decomposition = explain_metric_bucket(
+ team=self.team,
+ metric_name=query_data["metricName"],
+ aggregation=query_data["aggregation"],
+ bucket_start=query_data["bucketStart"],
+ interval=query_data["interval"],
+ filters=filters,
+ metric_type=MetricType(query_data["metricType"]) if query_data.get("metricType") else None,
+ quantile=query_data.get("quantile"),
+ )
+ except ValueError as exc:
+ raise ParseError(str(exc))
+
+ report_user_action(
+ request.user,
+ "metrics bucket explained",
+ {
+ "aggregation": decomposition.aggregation,
+ "metric_type": decomposition.metric_type,
+ "series_count": decomposition.series_count,
+ "agrees": decomposition.agrees,
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(
+ _MetricExplainResponseSerializer({"decomposition": decomposition}).data, status=status.HTTP_200_OK
+ )
+
@extend_schema(request=_MetricAnomalyRequestSerializer, responses={200: _MetricAnomalyReportSerializer})
@action(
detail=False,
diff --git a/products/metrics/backend/tests/test_api.py b/products/metrics/backend/tests/test_api.py
index 32a04babd7fe..f77c0a6df0bb 100644
--- a/products/metrics/backend/tests/test_api.py
+++ b/products/metrics/backend/tests/test_api.py
@@ -111,6 +111,7 @@ class TestMetricsAccessControl(APIBaseTest):
("attribute_values", "GET", {}),
("query", "POST", {}),
("samples", "POST", {}),
+ ("explain", "POST", {}),
("characterize", "POST", {}),
]
)
diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.py
new file mode 100644
index 000000000000..b7f73eb97562
--- /dev/null
+++ b/products/metrics/backend/tests/test_diagnostics.py
@@ -0,0 +1,310 @@
+import datetime as dt
+
+import pytest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
+
+from posthog.clickhouse.client import sync_execute
+
+from products.metrics.backend import diagnostics
+from products.metrics.backend.diagnostics import decompose_bucket
+from products.metrics.backend.fundamentals import SpatialReducer, TemporalReducer
+from products.metrics.backend.tests._seeder import seed_metric
+
+BUCKET = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)
+
+
+class TestBucketDecomposition(ClickhouseTestMixin, APIBaseTest):
+ """The decomposition recomputes a chart point from raw samples in Python and
+ reports it next to what the HogQL runner returned. The two disagreeing is the
+ signal — it means one of the reductions is wrong, and the breakdown shows which."""
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+
+ def _seed_gauge_pair(self) -> None:
+ # Two pods reporting the same gauge, three scrapes each inside one bucket.
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cache_size",
+ metric_type="gauge",
+ aggregation_temporality="",
+ labels={"pod": "a"},
+ points=[
+ (BUCKET, 5.0),
+ (BUCKET + dt.timedelta(seconds=60), 8.0),
+ (BUCKET + dt.timedelta(seconds=120), 11.0),
+ ],
+ )
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cache_size",
+ metric_type="gauge",
+ aggregation_temporality="",
+ labels={"pod": "b"},
+ points=[
+ (BUCKET, 20.0),
+ (BUCKET + dt.timedelta(seconds=60), 21.0),
+ (BUCKET + dt.timedelta(seconds=120), 22.0),
+ ],
+ )
+
+ def test_gauge_breakdown_reduces_each_series_to_its_latest_reading(self) -> None:
+ self._seed_gauge_pair()
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="cache_size",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.temporal_reducer == TemporalReducer.LAST
+ assert decomposition.spatial_reducer == SpatialReducer.SUM
+ assert decomposition.series_count == 2
+ assert decomposition.sample_count == 6
+ # 11 and 22 are the latest readings; the four earlier samples are re-readings.
+ contributions = [series.value for series in decomposition.series]
+ assert sorted(value for value in contributions if value is not None) == [11.0, 22.0]
+ assert None not in contributions
+ assert decomposition.reference_value == 33.0
+
+ def test_reports_disagreement_between_the_runner_and_the_reference(self) -> None:
+ """Whether these agree depends on the runner, which is the point: the check
+ holds a reduction the runner does not share, so a regression on either side
+ shows up as a disagreement rather than as a plausible-looking number."""
+ self._seed_gauge_pair()
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="cache_size",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.actual_value is not None
+ assert decomposition.agrees == (decomposition.actual_value == decomposition.reference_value)
+
+ def test_delta_counter_totals_every_increment_rather_than_the_last_one(self) -> None:
+ # Each delta sample IS an increment, so keeping only the newest would drop
+ # the rest of the bucket's traffic.
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="requests_total",
+ metric_type="sum",
+ aggregation_temporality="delta",
+ is_monotonic=True,
+ labels={"pod": "a"},
+ points=[(BUCKET, 3.0), (BUCKET + dt.timedelta(seconds=60), 4.0), (BUCKET + dt.timedelta(seconds=120), 5.0)],
+ )
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="requests_total",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.temporality == "delta"
+ assert decomposition.temporal_reducer == TemporalReducer.SUM_OVER_TIME
+ assert decomposition.reference_value == 12.0
+
+ def test_cumulative_counter_increase_diffs_within_the_series(self) -> None:
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="bytes_total",
+ metric_type="sum",
+ aggregation_temporality="cumulative",
+ is_monotonic=True,
+ labels={"pod": "a"},
+ points=[
+ (BUCKET, 100.0),
+ (BUCKET + dt.timedelta(seconds=60), 120.0),
+ (BUCKET + dt.timedelta(seconds=120), 5.0),
+ ],
+ )
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="bytes_total",
+ aggregation="increase",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.temporal_reducer == TemporalReducer.INCREASE
+ # +20, then a restart whose post-reset reading is itself the increase.
+ assert decomposition.reference_value == 25.0
+
+ def test_empty_bucket_reports_no_series_rather_than_zero(self) -> None:
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="nothing_here",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.series_count == 0
+ assert decomposition.reference_value is None
+
+ def test_truncation_is_reported_rather_than_silently_dropping_series(self) -> None:
+ for index in range(4):
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="wide_metric",
+ metric_type="gauge",
+ aggregation_temporality="",
+ labels={"pod": f"pod-{index}"},
+ points=[(BUCKET, float(index))],
+ )
+
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="wide_metric",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ max_series=2,
+ )
+
+ # The totals stay whole; only the per-series listing is shortened.
+ assert decomposition.series_count == 4
+ assert len(decomposition.series) == 2
+ assert decomposition.series_truncated is True
+ assert decomposition.reference_value == 6.0
+
+
+class TestExplainEndpoint(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+
+ def test_explain_returns_the_series_behind_a_point(self) -> None:
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cache_size",
+ metric_type="gauge",
+ aggregation_temporality="",
+ labels={"pod": "a"},
+ points=[(BUCKET, 5.0), (BUCKET + dt.timedelta(seconds=60), 11.0)],
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/explain/",
+ {
+ "query": {
+ "metricName": "cache_size",
+ "aggregation": "sum",
+ "bucketStart": BUCKET.isoformat(),
+ "interval": "minute_5",
+ }
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.json()
+ decomposition = response.json()["decomposition"]
+ assert decomposition["temporal_reducer"] == "last"
+ assert decomposition["series_count"] == 1
+ assert decomposition["reference_value"] == 11.0
+ assert [sample["value"] for sample in decomposition["series"][0]["samples"]] == [5.0, 11.0]
+
+ def test_rejects_an_interval_the_chart_could_not_have_used(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/explain/",
+ {
+ "query": {
+ "metricName": "cache_size",
+ "aggregation": "sum",
+ "bucketStart": BUCKET.isoformat(),
+ "interval": "fortnight",
+ }
+ },
+ format="json",
+ )
+
+ assert response.status_code == 400
+
+
+class TestCounterBoundary(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ # The predecessor sample sits in the previous bucket; the chart's window
+ # function diffs across that edge, so the check has to as well.
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="bytes_total",
+ metric_type="sum",
+ aggregation_temporality="cumulative",
+ is_monotonic=True,
+ labels={"pod": "a"},
+ points=[
+ (BUCKET - dt.timedelta(seconds=60), 100.0),
+ (BUCKET + dt.timedelta(seconds=60), 120.0),
+ (BUCKET + dt.timedelta(seconds=120), 140.0),
+ ],
+ )
+
+ def test_increase_counts_the_rise_across_the_bucket_edge(self) -> None:
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="bytes_total",
+ aggregation="increase",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ # 100 -> 120 -> 140: the bucket rose by 40, of which 20 crosses the
+ # edge. Read in isolation, both sides would drop that 20 and agree on
+ # a value the chart never plotted.
+ assert decomposition.reference_value == 40.0
+ assert decomposition.actual_value == 40.0
+ assert decomposition.agrees is True
+
+ def test_rate_normalizes_the_boundary_increase_too(self) -> None:
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="bytes_total",
+ aggregation="rate",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ assert decomposition.reference_value == pytest.approx(40.0 / 300.0)
+ assert decomposition.agrees is True
+
+
+class TestTruncatedBucket(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+
+ def test_truncated_read_reports_not_comparable_instead_of_a_verdict(self) -> None:
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name="cache_size",
+ metric_type="gauge",
+ aggregation_temporality="",
+ labels={"pod": "a"},
+ points=[(BUCKET + dt.timedelta(seconds=10 * i), float(i)) for i in range(6)],
+ )
+
+ with patch.object(diagnostics, "_MAX_ROWS_READ", 5):
+ decomposition = decompose_bucket(
+ team=self.team,
+ metric_name="cache_size",
+ aggregation="sum",
+ bucket_start=BUCKET,
+ interval="minute_5",
+ )
+
+ # The reference saw 5 of 6 rows while the runner saw all of them, so
+ # any verdict would be an artifact of the unequal inputs.
+ assert decomposition.rows_truncated is True
+ assert decomposition.agrees is None
diff --git a/products/metrics/backend/tests/test_fundamentals.py b/products/metrics/backend/tests/test_fundamentals.py
new file mode 100644
index 000000000000..f595767a8294
--- /dev/null
+++ b/products/metrics/backend/tests/test_fundamentals.py
@@ -0,0 +1,197 @@
+import datetime as dt
+
+import pytest
+
+from parameterized import parameterized
+
+from products.metrics.backend.fundamentals import (
+ ReductionPlan,
+ Sample,
+ SpatialReducer,
+ TemporalReducer,
+ apply_plan,
+ is_duplicate_invariant,
+ plan_reduction,
+ reduce_spatial,
+ reduce_temporal,
+)
+
+BUCKET = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)
+
+
+def _samples(*values: float, step_seconds: int = 30) -> list[Sample]:
+ return [Sample(timestamp=BUCKET + dt.timedelta(seconds=i * step_seconds), value=v) for i, v in enumerate(values)]
+
+
+class TestPlanReduction:
+ @parameterized.expand(
+ [
+ # A gauge sample is a re-reading, so the bucket's current value is the last one.
+ ("gauge_sum", "sum", "gauge", "", TemporalReducer.LAST, SpatialReducer.SUM, 1.0),
+ # A gauge that moves inside the bucket has a meaningful mean, so the
+ # per-series step averages over time rather than keeping one reading.
+ ("gauge_avg", "avg", "gauge", "", TemporalReducer.AVG_OVER_TIME, SpatialReducer.AVG, 1.0),
+ ("gauge_count", "count", "gauge", "", TemporalReducer.LAST, SpatialReducer.COUNT_SERIES, 1.0),
+ # A percentile describes a distribution, so it needs the readings
+ # themselves rather than one summary number per series.
+ ("gauge_p95", "p95", "gauge", "", TemporalReducer.POOLED_SAMPLES, SpatialReducer.QUANTILE, 1.0),
+ # A cumulative counter carries an absolute odometer reading.
+ ("cumulative_sum", "sum", "sum", "cumulative", TemporalReducer.LAST, SpatialReducer.SUM, 1.0),
+ (
+ "cumulative_increase",
+ "increase",
+ "sum",
+ "cumulative",
+ TemporalReducer.INCREASE,
+ SpatialReducer.SUM,
+ 1.0,
+ ),
+ # Same two reduction steps as `increase`; only the divisor separates them.
+ ("cumulative_rate", "rate", "sum", "cumulative", TemporalReducer.INCREASE, SpatialReducer.SUM, 300.0),
+ # A delta sample IS an increment, so the bucket total is their sum. Taking the
+ # last sample here keeps one increment and discards the rest.
+ ("delta_sum", "sum", "sum", "delta", TemporalReducer.SUM_OVER_TIME, SpatialReducer.SUM, 1.0),
+ ("delta_increase", "increase", "sum", "delta", TemporalReducer.SUM_OVER_TIME, SpatialReducer.SUM, 1.0),
+ ("delta_rate", "rate", "sum", "delta", TemporalReducer.SUM_OVER_TIME, SpatialReducer.SUM, 300.0),
+ ]
+ )
+ def test_plan_maps_type_and_temporality(
+ self,
+ _name: str,
+ aggregation: str,
+ metric_type: str,
+ temporality: str,
+ expected_temporal: TemporalReducer,
+ expected_spatial: SpatialReducer,
+ expected_divisor: float,
+ ) -> None:
+ plan = plan_reduction(
+ aggregation=aggregation, metric_type=metric_type, temporality=temporality, interval_seconds=300
+ )
+ assert plan.temporal == expected_temporal
+ assert plan.spatial == expected_spatial
+ assert plan.divisor == expected_divisor
+
+
+class TestTemporalReduction:
+ def test_last_uses_latest_timestamp_not_largest_value(self) -> None:
+ # A falling gauge: the peak is stale, the current reading is the tail.
+ assert reduce_temporal(_samples(100, 50, 10), TemporalReducer.LAST) == 10
+
+ def test_sum_over_time_dedupes_duplicate_timestamps(self) -> None:
+ # Two rows at one timestamp are one increment delivered twice, not two increments.
+ duplicated = [*_samples(3, 4), Sample(timestamp=BUCKET, value=3)]
+ assert reduce_temporal(duplicated, TemporalReducer.SUM_OVER_TIME) == 7
+
+ def test_increase_corrects_counter_reset(self) -> None:
+ # 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_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.
+ assert reduce_temporal(_samples(6, 240, 5, 210, 7, 8), TemporalReducer.AVG_OVER_TIME) == pytest.approx(
+ 79.33, abs=0.01
+ )
+
+
+class TestSpatialReduction:
+ @parameterized.expand(
+ [
+ ("sum", SpatialReducer.SUM, 30.0),
+ ("avg", SpatialReducer.AVG, 10.0),
+ ("min", SpatialReducer.MIN, 5.0),
+ ("max", SpatialReducer.MAX, 15.0),
+ ("count_series", SpatialReducer.COUNT_SERIES, 3.0),
+ ]
+ )
+ def test_combines_one_value_per_series(self, _name: str, reducer: SpatialReducer, expected: float) -> None:
+ assert reduce_spatial([10.0, 5.0, 15.0], reducer) == expected
+
+ def test_quantile_runs_over_series_values(self) -> None:
+ assert reduce_spatial([1.0, 2.0, 3.0, 4.0], SpatialReducer.QUANTILE, quantile=0.5) == pytest.approx(2.5)
+
+ @parameterized.expand([("sum", SpatialReducer.SUM), ("count_series", SpatialReducer.COUNT_SERIES)])
+ def test_empty_bucket_has_no_value(self, _name: str, reducer: SpatialReducer) -> None:
+ # The runner returns no row for an empty bucket, so a reference that
+ # returned 0 here would report every empty bucket as a disagreement.
+ assert reduce_spatial([], reducer) is None
+
+
+class TestPooledQuantile:
+ def test_percentile_reads_the_samples_rather_than_one_value_per_series(self) -> None:
+ # One series that swings inside the bucket still has a tail.
+ plan = plan_reduction(aggregation="p95", metric_type="gauge")
+ spiky = {"a": _samples(6, 240, 5, 210, 7, 8)}
+ assert apply_plan(spiky, plan) == pytest.approx(232.5)
+
+ def test_percentile_pools_across_series(self) -> None:
+ plan = plan_reduction(aggregation="p95", metric_type="gauge")
+ pooled = apply_plan({"a": _samples(1, 2), "b": _samples(3, 4)}, plan)
+ assert pooled == pytest.approx(_quantile_of([1.0, 2.0, 3.0, 4.0]))
+
+
+class TestRateNormalization:
+ @parameterized.expand(
+ [
+ # A counter climbing 60 over a five-minute bucket is 0.2/s.
+ ("rate_is_per_second", "rate", 0.2),
+ ("increase_is_the_total", "increase", 60.0),
+ ]
+ )
+ def test_only_rate_divides_by_the_bucket_length(self, _name: str, aggregation: str, expected: float) -> None:
+ # The runner divides a rate by the bucket length, so a reference that
+ # skips it disagrees with every correct rate chart by that length.
+ plan = plan_reduction(
+ aggregation=aggregation, metric_type="sum", temporality="cumulative", interval_seconds=300
+ )
+ assert apply_plan({"a": _samples(10, 70)}, plan) == pytest.approx(expected)
+
+ def test_rate_refuses_to_plan_without_a_bucket_length(self) -> None:
+ # Defaulting the interval would silently plot an increase as a rate.
+ with pytest.raises(ValueError):
+ plan_reduction(aggregation="rate", metric_type="sum", temporality="cumulative")
+
+
+def _quantile_of(values: list[float]) -> float:
+ position = 0.95 * (len(values) - 1)
+ lower = int(position)
+ upper = min(lower + 1, len(values) - 1)
+ weight = position - lower
+ return values[lower] * (1 - weight) + values[upper] * weight
+
+
+class TestDuplicateSampleInvariance:
+ """Re-delivering a scrape must not move the number. This is the property that
+ both known aggregation bugs violate, in opposite directions."""
+
+ @parameterized.expand(
+ [
+ ("gauge_sum", "sum", "gauge", ""),
+ ("gauge_avg", "avg", "gauge", ""),
+ ("gauge_p95", "p95", "gauge", ""),
+ ("gauge_count", "count", "gauge", ""),
+ ("delta_sum", "sum", "sum", "delta"),
+ ("cumulative_increase", "increase", "sum", "cumulative"),
+ ]
+ )
+ def test_planned_reduction_is_invariant(
+ self, _name: str, aggregation: str, metric_type: str, temporality: str
+ ) -> None:
+ plan = plan_reduction(aggregation=aggregation, metric_type=metric_type, temporality=temporality)
+ series = {"a": _samples(5, 7, 9), "b": _samples(2, 4)}
+ assert is_duplicate_invariant(series, plan) is True
+
+ @parameterized.expand(
+ [
+ ("sum", SpatialReducer.SUM),
+ ("count_series", SpatialReducer.COUNT_SERIES),
+ ]
+ )
+ def test_detects_a_plan_with_no_temporal_step(self, _name: str, spatial: SpatialReducer) -> None:
+ # NONE routes every raw sample to the spatial reducer, so the answer tracks the
+ # scrape rate rather than the data.
+ plan = ReductionPlan(temporal=TemporalReducer.NONE, spatial=spatial)
+ assert is_duplicate_invariant({"a": _samples(5, 5, 5)}, plan) is False
diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsx
index 25626afae40c..d631af187409 100644
--- a/products/metrics/frontend/MetricsScene.tsx
+++ b/products/metrics/frontend/MetricsScene.tsx
@@ -12,6 +12,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { MetricsFundamentals } from './components/MetricsFundamentals'
import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'
import { MetricsSqlEditor } from './components/MetricsSqlEditor'
import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'
@@ -25,6 +26,7 @@ export const METRICS_LOGIC_KEY = 'metrics'
const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[] = [
{ key: 'viewer', label: 'Viewer', 'data-attr': 'metrics-scene-tab-viewer' },
{ key: 'sql', label: 'SQL', 'data-attr': 'metrics-scene-tab-sql' },
+ { key: 'fundamentals', label: 'Fundamentals', 'data-attr': 'metrics-scene-tab-fundamentals' },
]
export const scene: SceneExport = {
@@ -58,6 +60,7 @@ const MetricsSceneContent = (): JSX.Element => {
const tabDisabledReasons: Record<MetricsSceneActiveTab, string | null> = {
viewer: metricsViewerDisabledReason,
sql: metricsSqlDisabledReason,
+ fundamentals: metricsViewerDisabledReason,
}
// Scene-level so tab switches in both directions are captured; keeps the viewer
// and samples logics (its connect targets) mounted across tab flips as a side effect.
@@ -102,6 +105,7 @@ const MetricsSceneContent = (): JSX.Element => {
<div className="flex flex-col gap-2 py-2 flex-1 min-h-0">
{activeTab === 'viewer' && <MetricsViewer />}
{activeTab === 'sql' && <MetricsSqlEditor />}
+ {activeTab === 'fundamentals' && <MetricsFundamentals />}
</div>
</MetricsSetupPrompt>
</>
diff --git a/products/metrics/frontend/components/MetricsFundamentals.tsx b/products/metrics/frontend/components/MetricsFundamentals.tsx
new file mode 100644
index 000000000000..77cccd415d5c
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsFundamentals.tsx
@@ -0,0 +1,233 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonCollapse, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import type { _MetricBucketDecompositionApi, _MetricSeriesBreakdownApi } from '../generated/api.schemas'
+import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'
+import type { MetricAggregation } from './metricsViewerLogic'
+
+// Each rule states what should happen, then the formula, then a worked example
+// small enough to check by eye. Someone who has never thought about metric
+// aggregation should be able to read one card and know what to look for.
+const RULES: { key: string; title: string; should: string; formula: string; example: string }[] = [
+ {
+ key: 'two-axes',
+ title: 'A bucket holds series, not numbers',
+ should: 'Every value is reduced twice. First each series is collapsed on its own, then those results are combined across series. Doing it in one step counts a series once per scrape, so the answer follows how often you collect rather than what you measured.',
+ formula: 'value = combine(over each series: collapse(its samples))',
+ example:
+ 'Two pods, three scrapes each, one bucket. That is 6 samples but only 2 series. A total should add 2 numbers, not 6.',
+ },
+ {
+ key: 'typing',
+ title: 'The metric type decides how a series collapses',
+ should: 'A gauge sample is a fresh reading, so the newest one wins. A cumulative counter is an odometer, so you subtract consecutive readings. A delta counter reports an increment each time, so you add them up. One rule applied to all three is wrong for two of them.',
+ formula: 'gauge: last · cumulative counter: sum of diffs · delta counter: sum',
+ example:
+ 'A counter reading 100, 120, 5, 25 rose by 45. The drop to 5 is a restart, so 5 is itself an increase.',
+ },
+ {
+ key: 'scrape-rate',
+ title: 'Collecting more often must not change the answer',
+ should: 'Sending the same reading twice is one observation delivered twice. If a value moves when a scrape is duplicated, dropped, or a bucket is still filling, the reduction is counting rows instead of series.',
+ formula: 'value(samples) == value(samples delivered twice)',
+ example:
+ 'A gauge scraped 10 times a bucket that reads 10x too high is the classic case. The multiplier moves with the scrape rate, so the chart jumps for no real reason.',
+ },
+ {
+ key: 'staleness',
+ title: 'A series that goes quiet is not a zero',
+ should: 'A series that reports in one bucket and not the next has not dropped to zero, it just has not been heard from. Totals over sparsely reported metrics swing on how many series happened to report, which reads as a real change but is not one.',
+ formula: 'absent series should carry forward or drop out, never count as 0',
+ example:
+ 'A total across 300 series where only 5 report each minute swings by millions between buckets purely on who reported. The check above cannot catch this one. It reads a single bucket, so a series that never reported is invisible to it. Compare neighbouring buckets by hand.',
+ },
+ {
+ key: 'ordering',
+ title: 'Percentiles and rates do not survive being averaged',
+ should: 'A percentile of percentiles is not a percentile, and a rate of summed counters misreads restarts. Rates reduce inside each series first, then combine. Percentiles go the other way and read every reading in the bucket, because collapsing a series to one number throws away the tail the percentile is asking about. The tradeoff is that a series collected more often contributes more readings to that tail.',
+ formula: 'sum(rate(x)), never rate(sum(x))',
+ example:
+ 'Host A serves 1,000 requests at p95 of 1ms, host B serves 10 at 2,000ms. Averaging the two p95s gives about 1,000ms. The real combined p95 is about 1ms.',
+ },
+]
+
+// These describe the reduction the check itself applied, which is only also
+// what the chart did when the two agree. The wording says so either way.
+const TEMPORAL_REDUCER_COPY: Record<string, string> = {
+ last: 'took each series latest reading',
+ avg_over_time: 'averaged each series readings over the bucket',
+ sum_over_time: 'added up each series increments',
+ increase: 'measured how much each series rose',
+ pooled_samples: 'used every reading rather than one value per series',
+ none: 'did not reduce per series, so every raw sample counted',
+}
+
+const SPATIAL_REDUCER_COPY: Record<string, string> = {
+ sum: 'added the series together',
+ avg: 'averaged across series',
+ min: 'took the smallest series',
+ max: 'took the largest series',
+ quantile: 'took a percentile across series',
+ count_series: 'counted how many series reported',
+}
+
+const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
+ { value: 'sum', label: 'Sum' },
+ { value: 'avg', label: 'Average' },
+ { value: 'count', label: 'Count' },
+ { value: 'p95', label: 'p95' },
+ { value: 'rate', label: 'Rate (/s)' },
+ { value: 'increase', label: 'Increase' },
+]
+
+// Float reductions land on values like 79.33333333333333, which are unreadable
+// next to each other and imply a precision the comparison does not use.
+const formatValue = (value: number | null): string =>
+ value === null ? 'no value' : Number(value.toPrecision(10)).toLocaleString('en-US', { maximumFractionDigits: 4 })
+
+const SeriesRow = ({ series }: { series: _MetricSeriesBreakdownApi }): JSX.Element => {
+ const labelText =
+ Object.entries(series.labels)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(' ') || 'no labels'
+
+ return (
+ <div className="flex flex-col gap-1 py-2 border-b last:border-b-0">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-mono text-xs truncate">
+ {series.service_name} {labelText}
+ </span>
+ <span className="font-semibold shrink-0">
+ {series.value === null ? `${series.sample_count} readings` : formatValue(series.value)}
+ </span>
+ </div>
+ <div className="font-mono text-xs text-muted">
+ {series.samples.map((sample) => sample.value).join(', ')}
+ {series.samples_truncated && ` and ${series.sample_count - series.samples.length} more`}
+ </div>
+ </div>
+ )
+}
+
+const Decomposition = ({ decomposition }: { decomposition: _MetricBucketDecompositionApi }): JSX.Element => {
+ const temporal = TEMPORAL_REDUCER_COPY[decomposition.temporal_reducer] ?? decomposition.temporal_reducer
+ const spatial = SPATIAL_REDUCER_COPY[decomposition.spatial_reducer] ?? decomposition.spatial_reducer
+
+ return (
+ <div className="flex flex-col gap-3">
+ <LemonBanner type={decomposition.agrees === null ? 'warning' : decomposition.agrees ? 'success' : 'error'}>
+ {decomposition.agrees === null ? (
+ <>
+ This bucket holds more raw samples than the check reads, so the recomputed value covers only
+ part of the data and proves nothing about the chart's {formatValue(decomposition.actual_value)}.
+ Narrow with a filter and check again.
+ </>
+ ) : decomposition.agrees ? (
+ <>
+ The chart shows {formatValue(decomposition.actual_value)} for this bucket, and recomputing it
+ from the raw samples gives the same number.
+ </>
+ ) : (
+ <>
+ The chart shows {formatValue(decomposition.actual_value)} for this bucket, but recomputing it
+ from the raw samples gives {formatValue(decomposition.reference_value)}. One of the two is
+ wrong. The series below show what the data actually contains.
+ </>
+ )}
+ </LemonBanner>
+
+ <div className="flex flex-wrap gap-1">
+ <LemonTag>{decomposition.metric_type || 'unknown type'}</LemonTag>
+ {decomposition.temporality && <LemonTag>{decomposition.temporality}</LemonTag>}
+ <LemonTag>{decomposition.series_count} series</LemonTag>
+ <LemonTag>{decomposition.sample_count} samples</LemonTag>
+ </div>
+
+ <p className="mb-0">
+ To get {formatValue(decomposition.reference_value)}, the check {temporal}, then {spatial}.
+ {decomposition.aggregation === 'rate' &&
+ ' The result is divided by the bucket length, so it is per second.'}
+ {decomposition.agrees === false && ' The chart reached its number a different way.'}
+ </p>
+
+ <div>
+ <h4>Series in this bucket</h4>
+ {decomposition.series.map((series, index) => (
+ <SeriesRow key={index} series={series} />
+ ))}
+ {decomposition.series_truncated && (
+ <p className="text-muted mt-2 mb-0">
+ Showing the {decomposition.series.length} largest of {decomposition.series_count} series. The
+ totals above cover all of them.
+ </p>
+ )}
+ </div>
+ </div>
+ )
+}
+
+export function MetricsFundamentals(): JSX.Element {
+ const { metricName, aggregation, checkResult, checkResultLoading } = useValues(metricsFundamentalsLogic)
+ const { setMetricName, setAggregation, runCheck } = useActions(metricsFundamentalsLogic)
+
+ return (
+ <div className="flex flex-col gap-4 overflow-y-auto">
+ <p className="mb-0">
+ What a metrics chart shows depends on how its numbers were combined, and a wrong combination still looks
+ like a normal chart. This page explains the rules a correct chart follows, then checks a real point
+ against them.
+ </p>
+
+ <div>
+ <h3>Check a point</h3>
+ <p className="text-muted">
+ Pick a metric and we take its most recent complete 5 minute bucket apart. The value is recomputed
+ from the raw samples and compared against what the chart would draw.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ value={metricName}
+ onChange={setMetricName}
+ onPressEnter={() => runCheck()}
+ placeholder="Metric name"
+ className="w-80"
+ />
+ <LemonSelect<MetricAggregation>
+ value={aggregation}
+ onChange={setAggregation}
+ options={AGGREGATION_OPTIONS}
+ />
+ <LemonButton
+ type="primary"
+ onClick={() => runCheck()}
+ loading={checkResultLoading}
+ disabledReason={!metricName ? 'Enter a metric name' : undefined}
+ >
+ Check
+ </LemonButton>
+ </div>
+ </div>
+
+ {checkResult && !checkResultLoading && <Decomposition decomposition={checkResult.decomposition} />}
+
+ <div>
+ <h3>The rules</h3>
+ <LemonCollapse
+ multiple
+ panels={RULES.map((rule) => ({
+ key: rule.key,
+ header: rule.title,
+ content: (
+ <div className="flex flex-col gap-2">
+ <p className="mb-0">{rule.should}</p>
+ <code className="text-xs">{rule.formula}</code>
+ <p className="text-muted mb-0">{rule.example}</p>
+ </div>
+ ),
+ }))}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts b/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts
new file mode 100644
index 000000000000..30e01504b329
--- /dev/null
+++ b/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts
@@ -0,0 +1,99 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+import { AppContext } from '~/types'
+
+import { metricsExplainCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'
+import type {
+ _MetricBucketDecompositionApi,
+ _MetricQueryPointApi,
+ _MetricQueryResponseApi,
+} from 'products/metrics/frontend/generated/api.schemas'
+
+import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'
+
+jest.mock('products/metrics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/metrics/frontend/generated/api'),
+ metricsQueryCreate: jest.fn(),
+ metricsExplainCreate: jest.fn(),
+}))
+
+const decomposition: _MetricBucketDecompositionApi = {
+ metric_name: 'cache_size',
+ metric_type: 'gauge',
+ temporality: '',
+ aggregation: 'sum',
+ bucket_start: '2026-01-01T00:05:00Z',
+ interval: '5m',
+ temporal_reducer: 'last',
+ spatial_reducer: 'sum',
+ series: [],
+ series_count: 0,
+ sample_count: 0,
+ series_truncated: false,
+ rows_truncated: false,
+ reference_value: 33,
+ actual_value: 33,
+ agrees: true,
+}
+
+const queryResponse = (points: _MetricQueryPointApi[]): _MetricQueryResponseApi => ({
+ results: [{ labels: {}, points }],
+})
+
+describe('metricsFundamentalsLogic', () => {
+ let logic: ReturnType<typeof metricsFundamentalsLogic.build>
+
+ beforeEach(() => {
+ window.POSTHOG_APP_CONTEXT = { current_project: { id: 997 } } as unknown as AppContext
+ initKeaTests()
+ logic = metricsFundamentalsLogic()
+ logic.mount()
+ jest.mocked(metricsExplainCreate).mockResolvedValue({ decomposition })
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.clearAllMocks()
+ })
+
+ it('explains the newest bucket that has a value, not the newest bucket', async () => {
+ // The most recent bucket is usually still filling, so it comes back empty.
+ // Explaining it would decompose nothing while looking like it worked.
+ jest.mocked(metricsQueryCreate).mockResolvedValue(
+ queryResponse([
+ { time: '2026-01-01T00:00:00Z', value: 1 },
+ { time: '2026-01-01T00:05:00Z', value: 2 },
+ { time: '2026-01-01T00:10:00Z', value: null },
+ ])
+ )
+
+ logic.actions.setMetricName('cache_size')
+ await expectLogic(logic, () => logic.actions.runCheck()).toFinishAllListeners()
+
+ expect(jest.mocked(metricsExplainCreate).mock.calls[0][1].query.bucketStart).toEqual('2026-01-01T00:05:00Z')
+ })
+
+ it('drops the previous result when a new check starts', async () => {
+ // Otherwise the old metric's decomposition sits under the new metric's
+ // name while the new one loads, and reads as its answer.
+ jest.mocked(metricsQueryCreate).mockResolvedValue(queryResponse([{ time: '2026-01-01T00:00:00Z', value: 1 }]))
+ logic.actions.setMetricName('cache_size')
+ await expectLogic(logic, () => logic.actions.runCheck()).toFinishAllListeners()
+ expect(logic.values.checkResult).not.toBeNull()
+
+ logic.actions.setMetricName('other_metric')
+ expectLogic(logic, () => logic.actions.runCheck())
+ expect(logic.values.checkResult).toBeNull()
+ })
+
+ it('does not explain anything when the metric reported no values', async () => {
+ jest.mocked(metricsQueryCreate).mockResolvedValue(queryResponse([]))
+
+ logic.actions.setMetricName('cache_size')
+ await expectLogic(logic, () => logic.actions.runCheck()).toFinishAllListeners()
+
+ expect(metricsExplainCreate).not.toHaveBeenCalled()
+ expect(logic.values.checkResult).toBeNull()
+ })
+})
diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.tsx b/products/metrics/frontend/components/metricsFundamentalsLogic.tsx
new file mode 100644
index 000000000000..de46263d8584
--- /dev/null
+++ b/products/metrics/frontend/components/metricsFundamentalsLogic.tsx
@@ -0,0 +1,148 @@
+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import { metricsExplainCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'
+import type { _MetricBucketDecompositionApi } from 'products/metrics/frontend/generated/api.schemas'
+
+import type { MetricAggregation } from './metricsViewerLogic'
+
+// Bucket size the check runs at. Fixed rather than auto-picked, because a
+// decomposition is only meaningful next to the interval it was computed for.
+export const CHECK_INTERVAL = 'minute_5'
+
+// How far back to look for a bucket with data in it. The most recent bucket is
+// usually still filling, so the check walks back to the last complete one.
+const LOOKBACK_MINUTES = 60
+
+export interface FundamentalsCheckResult {
+ decomposition: _MetricBucketDecompositionApi
+ checkedAt: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface metricsFundamentalsLogicValues {
+ aggregation: MetricAggregation
+ checkResult: FundamentalsCheckResult | null
+ checkResultLoading: boolean
+ metricName: string
+ projectId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface metricsFundamentalsLogicActions {
+ runCheck: () => {
+ value: true
+ }
+ runCheckFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ runCheckSuccess: (
+ checkResult: {
+ checkedAt: string
+ decomposition: _MetricBucketDecompositionApi
+ } | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ checkResult: {
+ checkedAt: string
+ decomposition: _MetricBucketDecompositionApi
+ } | null
+ payload?: {
+ value: true
+ }
+ }
+ setAggregation: (aggregation: MetricAggregation) => {
+ aggregation: MetricAggregation
+ }
+ setMetricName: (metricName: string) => {
+ metricName: string
+ }
+}
+
+export type metricsFundamentalsLogicType = MakeLogicType<
+ metricsFundamentalsLogicValues,
+ metricsFundamentalsLogicActions
+>
+
+export const metricsFundamentalsLogic = kea<metricsFundamentalsLogicType>([
+ path(['products', 'metrics', 'frontend', 'components', 'metricsFundamentalsLogic']),
+
+ actions({
+ setMetricName: (metricName: string) => ({ metricName }),
+ setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
+ runCheck: true,
+ }),
+
+ reducers({
+ metricName: ['', { setMetricName: (_, { metricName }) => metricName }],
+ aggregation: ['sum' as MetricAggregation, { setAggregation: (_, { aggregation }) => aggregation }],
+ // Drop the previous decomposition the moment a new check starts. The
+ // loading flag alone leaves a frame where the old answer is still on
+ // screen under the new metric name, which reads as the new answer.
+ checkResult: [null as FundamentalsCheckResult | null, { runCheck: () => null }],
+ }),
+
+ loaders(({ values }) => ({
+ checkResult: [
+ null as FundamentalsCheckResult | null,
+ {
+ runCheck: async (_, breakpoint) => {
+ if (!values.metricName) {
+ return null
+ }
+ await breakpoint(300)
+
+ const dateTo = dayjs().startOf('minute')
+ const dateFrom = dateTo.subtract(LOOKBACK_MINUTES, 'minute')
+
+ // Ask the chart what it would plot first, so the bucket being
+ // explained is one the product actually drew rather than one
+ // picked blind — an empty bucket explains nothing.
+ const series = await metricsQueryCreate(values.projectId, {
+ query: {
+ metricName: values.metricName,
+ aggregation: values.aggregation,
+ interval: CHECK_INTERVAL,
+ dateFrom: dateFrom.toISOString(),
+ dateTo: dateTo.toISOString(),
+ },
+ })
+ breakpoint()
+
+ const points = series.results?.[0]?.points ?? []
+ const latest = [...points].reverse().find((point) => point.value !== null)
+ if (!latest) {
+ lemonToast.info(`No data for ${values.metricName} in the last hour`)
+ return null
+ }
+
+ const response = await metricsExplainCreate(values.projectId, {
+ query: {
+ metricName: values.metricName,
+ aggregation: values.aggregation,
+ bucketStart: latest.time,
+ interval: CHECK_INTERVAL,
+ },
+ })
+ breakpoint()
+
+ return { decomposition: response.decomposition, checkedAt: dayjs().toISOString() }
+ },
+ },
+ ],
+ })),
+
+ selectors({
+ projectId: [() => [], () => window.POSTHOG_APP_CONTEXT?.current_project?.id?.toString() ?? ''],
+ }),
+])
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index cecff4c65249..c12e5467f08b 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -270,11 +270,6 @@ export interface _MetricAnomalyReportApi {
series: _MetricSeriesApi
}
-export interface _HasMetricsResponseApi {
- /** Whether the team has ingested any metrics. */
- hasMetrics: boolean
-}
-
/**
* * `gauge` - gauge
* * `sum` - sum
@@ -292,20 +287,6 @@ export const OtelMetricTypeEnumApi = {
Summary: 'summary',
} as const
-export interface _MetricGroupByApi {
- /**
- * Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
- * @maxLength 255
- */
- key: string
- /** Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.
- *
- * * `resource` - resource
- * * `attribute` - attribute
- * * `auto` - auto */
- scope?: MetricAttributeScopeEnumApi
-}
-
/**
* * `second` - second
* * `minute` - minute
@@ -329,6 +310,216 @@ export const MetricQueryIntervalEnumApi = {
Week: 'week',
} as const
+export interface _MetricExplainBodyApi {
+ /**
+ * Exact metric name whose bucket should be taken apart.
+ * @maxLength 255
+ */
+ metricName: string
+ /** Constrain the bucket to one metric type. A name can exist as several types; without this, rows of every type sharing the name are decomposed together.
+ *
+ * * `gauge` - gauge
+ * * `sum` - sum
+ * * `histogram` - histogram
+ * * `exponential_histogram` - exponential_histogram
+ * * `summary` - summary */
+ metricType?: OtelMetricTypeEnumApi | null
+ /** The aggregation whose result should be explained. 'histogram_quantile' is rejected: it reduces bucket-count arrays rather than scalar samples, so there is no per-series value to lay out.
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile */
+ aggregation?: AggregationEnumApi
+ /**
+ * Quantile in (0, 1) applied across series. Defaults to 0.95 for the 'p95' aggregation.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ quantile?: number | null
+ /** Label predicates ANDed together, matching the chart the point came from. */
+ filters?: _MetricFilterApi[]
+ /** Start of the bucket to explain, as returned in a query result's 'time'. ISO 8601. */
+ bucketStart: string
+ /** Bucket size the point was plotted at. Must match the query that produced it, or the decomposition explains a different span.
+ *
+ * * `second` - second
+ * * `minute` - minute
+ * * `minute_5` - minute_5
+ * * `minute_15` - minute_15
+ * * `hour` - hour
+ * * `hour_6` - hour_6
+ * * `day` - day
+ * * `week` - week */
+ interval: MetricQueryIntervalEnumApi
+}
+
+export interface _MetricExplainRequestApi {
+ /** The chart point to take apart. */
+ query: _MetricExplainBodyApi
+}
+
+/**
+ * * `none` - none
+ * * `last` - last
+ * * `avg_over_time` - avg_over_time
+ * * `sum_over_time` - sum_over_time
+ * * `increase` - increase
+ * * `pooled_samples` - pooled_samples
+ */
+export type TemporalReducerEnumApi = (typeof TemporalReducerEnumApi)[keyof typeof TemporalReducerEnumApi]
+
+export const TemporalReducerEnumApi = {
+ None: 'none',
+ Last: 'last',
+ AvgOverTime: 'avg_over_time',
+ SumOverTime: 'sum_over_time',
+ Increase: 'increase',
+ PooledSamples: 'pooled_samples',
+} as const
+
+/**
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `min` - min
+ * * `max` - max
+ * * `quantile` - quantile
+ * * `count_series` - count_series
+ */
+export type SpatialReducerEnumApi = (typeof SpatialReducerEnumApi)[keyof typeof SpatialReducerEnumApi]
+
+export const SpatialReducerEnumApi = {
+ Sum: 'sum',
+ Avg: 'avg',
+ Min: 'min',
+ Max: 'max',
+ Quantile: 'quantile',
+ CountSeries: 'count_series',
+} as const
+
+export interface _MetricSampleViewApi {
+ /** Sample timestamp, ISO 8601. */
+ time: string
+ /** Raw stored reading, before any reduction. */
+ value: number
+}
+
+/**
+ * Per-data-point attributes identifying the series.
+ */
+export type _MetricSeriesBreakdownApiLabels = { [key: string]: string }
+
+/**
+ * Resource attributes identifying the scrape target.
+ */
+export type _MetricSeriesBreakdownApiResourceLabels = { [key: string]: string }
+
+export interface _MetricSeriesBreakdownApi {
+ /** Service that reported this series. */
+ service_name: string
+ /** Per-data-point attributes identifying the series. */
+ labels: _MetricSeriesBreakdownApiLabels
+ /** Resource attributes identifying the scrape target. */
+ resource_labels: _MetricSeriesBreakdownApiResourceLabels
+ /** The series' raw samples in this bucket, oldest first, trimmed for display. */
+ samples: _MetricSampleViewApi[]
+ /** How many samples the series actually sent, even when 'samples' was trimmed. */
+ sample_count: number
+ /** Whether 'samples' lists fewer samples than arrived. */
+ samples_truncated: boolean
+ /**
+ * What this series contributed after the per-series reduction. Null for percentiles, which read the pooled readings and so have no single per-series contribution.
+ * @nullable
+ */
+ value: number | null
+}
+
+export interface _MetricBucketDecompositionApi {
+ /** Metric that was decomposed. */
+ metric_name: string
+ /** OTel metric type observed in the bucket. */
+ metric_type: string
+ /** OTel aggregation temporality observed in the bucket ('cumulative', 'delta', or empty for gauges). */
+ temporality: string
+ /** Aggregation that was explained. */
+ aggregation: string
+ /** Start of the explained bucket, ISO 8601. */
+ bucket_start: string
+ /** Bucket size the point was plotted at. */
+ interval: string
+ /** How each series' samples were collapsed to one value: 'last' for an instant gauge reading, 'avg_over_time' for an average, 'sum_over_time' for delta counters, 'increase' for cumulative counters, and 'pooled_samples' for percentiles, which skip the per-series step entirely.
+ *
+ * * `none` - none
+ * * `last` - last
+ * * `avg_over_time` - avg_over_time
+ * * `sum_over_time` - sum_over_time
+ * * `increase` - increase
+ * * `pooled_samples` - pooled_samples */
+ temporal_reducer: TemporalReducerEnumApi
+ /** How the per-series values were combined into the bucket's number.
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `min` - min
+ * * `max` - max
+ * * `quantile` - quantile
+ * * `count_series` - count_series */
+ spatial_reducer: SpatialReducerEnumApi
+ /** The series behind the point, largest contributors first, trimmed for display. */
+ series: _MetricSeriesBreakdownApi[]
+ /** How many series reported in the bucket. */
+ series_count: number
+ /** How many raw samples the bucket held across all series. */
+ sample_count: number
+ /** Whether 'series' lists fewer series than reported. */
+ series_truncated: boolean
+ /** Whether the bucket held more raw rows than the decomposition reads. Totals are computed only over the rows that were read. */
+ rows_truncated: boolean
+ /**
+ * The bucket's value recomputed from the raw samples, independently of the query builders. Null when no series reported.
+ * @nullable
+ */
+ reference_value: number | null
+ /**
+ * The value the product would plot for this point. Null when the query returned no row.
+ * @nullable
+ */
+ actual_value: number | null
+ /**
+ * Whether the two values match. False means one of the reductions is wrong, and the series breakdown shows where they parted. Null when the raw read was truncated, so the two are not comparable.
+ * @nullable
+ */
+ agrees: boolean | null
+}
+
+export interface _MetricExplainResponseApi {
+ /** The bucket taken apart. */
+ decomposition: _MetricBucketDecompositionApi
+}
+
+export interface _HasMetricsResponseApi {
+ /** Whether the team has ingested any metrics. */
+ hasMetrics: boolean
+}
+
+export interface _MetricGroupByApi {
+ /**
+ * Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
+ * @maxLength 255
+ */
+ key: string
+ /** Where the attribute lives; same semantics as filter scope. Use 'auto' unless you know the exact scope.
+ *
+ * * `resource` - resource
+ * * `attribute` - attribute
+ * * `auto` - auto */
+ scope?: MetricAttributeScopeEnumApi
+}
+
export interface _MetricClauseApi {
/**
* Clause name a formula refers to (e.g. 'a').
diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.ts
index 83d32d119f8e..b6ff3cadd7cb 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -19,6 +19,8 @@ import type {
_MetricAnomalyRequestApi,
_MetricAttributeKeysResponseApi,
_MetricAttributeValuesResponseApi,
+ _MetricExplainRequestApi,
+ _MetricExplainResponseApi,
_MetricNamesResponseApi,
_MetricQueryRequestApi,
_MetricQueryResponseApi,
@@ -155,6 +157,28 @@ export const metricsCharacterizeCreate = async (
})
}
+export const getMetricsExplainCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/metrics/explain/`
+}
+
+/**
+ * Take one chart point apart into the series and samples behind it,
+ * and recompute it independently so the plotted number can be checked
+ * rather than trusted.
+ */
+export const metricsExplainCreate = async (
+ projectId: string,
+ _metricExplainRequestApi: _MetricExplainRequestApi,
+ options?: RequestInit
+): Promise<_MetricExplainResponseApi> => {
+ return apiMutator<_MetricExplainResponseApi>(getMetricsExplainCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_metricExplainRequestApi),
+ })
+}
+
export const getMetricsHasMetricsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/metrics/has_metrics/`
}
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index e1ec2507a61b..c837c7e821af 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -114,6 +114,105 @@ export const MetricsCharacterizeCreateBody = /* @__PURE__ */ zod.object({
.describe('The anomaly characterization to run.'),
})
+/**
+ * Take one chart point apart into the series and samples behind it,
+ * and recompute it independently so the plotted number can be checked
+ * rather than trusted.
+ */
+export const metricsExplainCreateBodyQueryOneMetricNameMax = 255
+
+export const metricsExplainCreateBodyQueryOneAggregationDefault = `sum`
+export const metricsExplainCreateBodyQueryOneQuantileMin = 0
+export const metricsExplainCreateBodyQueryOneQuantileMax = 1
+
+export const metricsExplainCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsExplainCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsExplainCreateBodyQueryOneFiltersItemValueMax = 1024
+
+export const metricsExplainCreateBodyQueryOneFiltersItemScopeDefault = `auto`
+
+export const MetricsExplainCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ metricName: zod
+ .string()
+ .max(metricsExplainCreateBodyQueryOneMetricNameMax)
+ .describe('Exact metric name whose bucket should be taken apart.'),
+ 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 bucket to one metric type. A name can exist as several types; without this, rows of every type sharing the name are decomposed together.\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(
+ '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile'
+ )
+ .default(metricsExplainCreateBodyQueryOneAggregationDefault)
+ .describe(
+ "The aggregation whose result should be explained. 'histogram_quantile' is rejected: it reduces bucket-count arrays rather than scalar samples, so there is no per-series value to lay out.\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()
+ .min(metricsExplainCreateBodyQueryOneQuantileMin)
+ .max(metricsExplainCreateBodyQueryOneQuantileMax)
+ .nullish()
+ .describe("Quantile in (0, 1) applied across series. Defaults to 0.95 for the 'p95' aggregation."),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsExplainCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex')
+ .default(metricsExplainCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'\/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .max(metricsExplainCreateBodyQueryOneFiltersItemValueMax)
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto')
+ .default(metricsExplainCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates ANDed together, matching the chart the point came from.'),
+ bucketStart: zod.iso
+ .datetime({ offset: true })
+ .describe("Start of the bucket to explain, as returned in a query result's 'time'. ISO 8601."),
+ interval: zod
+ .enum(['second', 'minute', 'minute_5', 'minute_15', 'hour', 'hour_6', 'day', 'week'])
+ .describe(
+ '\* `second` - second\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `hour` - hour\n\* `hour_6` - hour_6\n\* `day` - day\n\* `week` - week'
+ )
+ .describe(
+ 'Bucket size the point was plotted at. Must match the query that produced it, or the decomposition explains a different span.\n\n\* `second` - second\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `hour` - hour\n\* `hour_6` - hour_6\n\* `day` - day\n\* `week` - week'
+ ),
+ })
+ .describe('The chart point to take apart.'),
+})
+
export const metricsQueryCreateBodyQueryOneMetricNameMax = 255
export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`
diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsx
index fce3e32d17c2..59fad689c073 100644
--- a/products/metrics/frontend/metricsSceneLogic.tsx
+++ b/products/metrics/frontend/metricsSceneLogic.tsx
@@ -10,8 +10,8 @@ import { Params } from 'scenes/sceneTypes'
export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'
-export type MetricsSceneActiveTab = 'viewer' | 'sql'
-const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['viewer', 'sql']
+export type MetricsSceneActiveTab = 'viewer' | 'sql' | 'fundamentals'
+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['viewer', 'sql', 'fundamentals']
export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'viewer'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yaml
index 1f152c93609c..4fd160ab08f1 100644
--- a/products/metrics/mcp/tools.yaml
+++ b/products/metrics/mcp/tools.yaml
@@ -44,6 +44,9 @@ tools:
metrics-attributes-retrieve:
operation: metrics_attributes_retrieve
enabled: false
+ metrics-explain-create:
+ operation: metrics_explain_create
+ enabled: false
metrics-has-metrics-retrieve:
operation: metrics_has_metrics_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 60c06acc94dc..1199c731bb4f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -78087,6 +78087,26 @@ export namespace Schemas {
Bytes: 'bytes',
} as const;
+ /**
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `min` - min
+ * * `max` - max
+ * * `quantile` - quantile
+ * * `count_series` - count_series
+ */
+ export type SpatialReducerEnum = typeof SpatialReducerEnum[keyof typeof SpatialReducerEnum];
+
+
+ export const SpatialReducerEnum = {
+ Sum: 'sum',
+ Avg: 'avg',
+ Min: 'min',
+ Max: 'max',
+ Quantile: 'quantile',
+ CountSeries: 'count_series',
+ } as const;
+
/**
* Raw cached payload as stored in Redis, or null on a miss.
* @nullable
@@ -81393,6 +81413,26 @@ export namespace Schemas {
has_membership_data: boolean;
}
+ /**
+ * * `none` - none
+ * * `last` - last
+ * * `avg_over_time` - avg_over_time
+ * * `sum_over_time` - sum_over_time
+ * * `increase` - increase
+ * * `pooled_samples` - pooled_samples
+ */
+ export type TemporalReducerEnum = typeof TemporalReducerEnum[keyof typeof TemporalReducerEnum];
+
+
+ export const TemporalReducerEnum = {
+ None: 'none',
+ Last: 'last',
+ AvgOverTime: 'avg_over_time',
+ SumOverTime: 'sum_over_time',
+ Increase: 'increase',
+ PooledSamples: 'pooled_samples',
+ } as const;
+
export type TestHogRequestConditionsItem = { [key: string]: unknown };
export interface TestHogTargetConfig {
@@ -83824,6 +83864,101 @@ export namespace Schemas {
results: _MetricAttributeValue[];
}
+ export interface _MetricSampleView {
+ /** Sample timestamp, ISO 8601. */
+ time: string;
+ /** Raw stored reading, before any reduction. */
+ value: number;
+ }
+
+ /**
+ * Per-data-point attributes identifying the series.
+ */
+ export type _MetricSeriesBreakdownLabels = {[key: string]: string};
+
+ /**
+ * Resource attributes identifying the scrape target.
+ */
+ export type _MetricSeriesBreakdownResourceLabels = {[key: string]: string};
+
+ export interface _MetricSeriesBreakdown {
+ /** Service that reported this series. */
+ service_name: string;
+ /** Per-data-point attributes identifying the series. */
+ labels: _MetricSeriesBreakdownLabels;
+ /** Resource attributes identifying the scrape target. */
+ resource_labels: _MetricSeriesBreakdownResourceLabels;
+ /** The series' raw samples in this bucket, oldest first, trimmed for display. */
+ samples: _MetricSampleView[];
+ /** How many samples the series actually sent, even when 'samples' was trimmed. */
+ sample_count: number;
+ /** Whether 'samples' lists fewer samples than arrived. */
+ samples_truncated: boolean;
+ /**
+ * What this series contributed after the per-series reduction. Null for percentiles, which read the pooled readings and so have no single per-series contribution.
+ * @nullable
+ */
+ value: number | null;
+ }
+
+ export interface _MetricBucketDecomposition {
+ /** Metric that was decomposed. */
+ metric_name: string;
+ /** OTel metric type observed in the bucket. */
+ metric_type: string;
+ /** OTel aggregation temporality observed in the bucket ('cumulative', 'delta', or empty for gauges). */
+ temporality: string;
+ /** Aggregation that was explained. */
+ aggregation: string;
+ /** Start of the explained bucket, ISO 8601. */
+ bucket_start: string;
+ /** Bucket size the point was plotted at. */
+ interval: string;
+ /** How each series' samples were collapsed to one value: 'last' for an instant gauge reading, 'avg_over_time' for an average, 'sum_over_time' for delta counters, 'increase' for cumulative counters, and 'pooled_samples' for percentiles, which skip the per-series step entirely.
+ *
+ * * `none` - none
+ * * `last` - last
+ * * `avg_over_time` - avg_over_time
+ * * `sum_over_time` - sum_over_time
+ * * `increase` - increase
+ * * `pooled_samples` - pooled_samples */
+ temporal_reducer: TemporalReducerEnum;
+ /** How the per-series values were combined into the bucket's number.
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `min` - min
+ * * `max` - max
+ * * `quantile` - quantile
+ * * `count_series` - count_series */
+ spatial_reducer: SpatialReducerEnum;
+ /** The series behind the point, largest contributors first, trimmed for display. */
+ series: _MetricSeriesBreakdown[];
+ /** How many series reported in the bucket. */
+ series_count: number;
+ /** How many raw samples the bucket held across all series. */
+ sample_count: number;
+ /** Whether 'series' lists fewer series than reported. */
+ series_truncated: boolean;
+ /** Whether the bucket held more raw rows than the decomposition reads. Totals are computed only over the rows that were read. */
+ rows_truncated: boolean;
+ /**
+ * The bucket's value recomputed from the raw samples, independently of the query builders. Null when no series reported.
+ * @nullable
+ */
+ reference_value: number | null;
+ /**
+ * The value the product would plot for this point. Null when the query returned no row.
+ * @nullable
+ */
+ actual_value: number | null;
+ /**
+ * Whether the two values match. False means one of the reductions is wrong, and the series breakdown shows where they parted. Null when the raw read was truncated, so the two are not comparable.
+ * @nullable
+ */
+ agrees: boolean | null;
+ }
+
export interface _MetricGroupBy {
/**
* Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
@@ -83919,6 +84054,64 @@ export namespace Schemas {
resource_attributes: _MetricEventSampleResourceAttributes;
}
+ export interface _MetricExplainBody {
+ /**
+ * Exact metric name whose bucket should be taken apart.
+ * @maxLength 255
+ */
+ metricName: string;
+ /** Constrain the bucket to one metric type. A name can exist as several types; without this, rows of every type sharing the name are decomposed together.
+ *
+ * * `gauge` - gauge
+ * * `sum` - sum
+ * * `histogram` - histogram
+ * * `exponential_histogram` - exponential_histogram
+ * * `summary` - summary */
+ metricType?: OtelMetricTypeEnum | null;
+ /** The aggregation whose result should be explained. 'histogram_quantile' is rejected: it reduces bucket-count arrays rather than scalar samples, so there is no per-series value to lay out.
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile */
+ aggregation?: AggregationEnum;
+ /**
+ * Quantile in (0, 1) applied across series. Defaults to 0.95 for the 'p95' aggregation.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ quantile?: number | null;
+ /** Label predicates ANDed together, matching the chart the point came from. */
+ filters?: _MetricFilter[];
+ /** Start of the bucket to explain, as returned in a query result's 'time'. ISO 8601. */
+ bucketStart: string;
+ /** Bucket size the point was plotted at. Must match the query that produced it, or the decomposition explains a different span.
+ *
+ * * `second` - second
+ * * `minute` - minute
+ * * `minute_5` - minute_5
+ * * `minute_15` - minute_15
+ * * `hour` - hour
+ * * `hour_6` - hour_6
+ * * `day` - day
+ * * `week` - week */
+ interval: MetricQueryIntervalEnum;
+ }
+
+ export interface _MetricExplainRequest {
+ /** The chart point to take apart. */
+ query: _MetricExplainBody;
+ }
+
+ export interface _MetricExplainResponse {
+ /** The bucket taken apart. */
+ decomposition: _MetricBucketDecomposition;
+ }
+
export interface _MetricName {
/** Metric name as it appears in the team's data. */
name: string;