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.

refactor(metrics): remove the fundamentals tab, explain API, and flag (#110160)

Frank Hamand2b02d2d22aa6
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b39f460850df..26b8fbb06557 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -432,7 +432,6 @@ export const FEATURE_FLAGS = {
METRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)
METRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entries
METRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics charts
- METRICS_FUNDAMENTALS: 'metrics-fundamentals', // owner: #team-apm (@jonmcwest, @frankh), gates the Fundamentals tab and the explain API behind it, which check the metrics viewer's own reductions
METRICS_DASHBOARD_CONTROLS: 'metrics-dashboard-controls', // owner: #team-apm — shows each dashboard filter only for the tiles it changes, and adds the metric label filter
METRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit mode
ML_INFERENCE_DECISIONS: 'ml-inference-decisions', // owner: #team-ai-research, gates the decisions playground; the API checks the same flag server side
diff --git a/posthog/middleware.py b/posthog/middleware.py
index d14fde5e91e6..8e6d7c3286ad 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1579,7 +1579,7 @@ READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[tuple[str, str | re.Pattern]] =
# POST but read-only: same reasoning for the Metrics product
(
"POST",
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/metrics/(query|samples|characterize|explain)/?$"),
+ re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/metrics/(query|samples|characterize)/?$"),
),
# Allow upgrading from read-only to read-write impersonation
("POST", "/admin/impersonation/upgrade/"),
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 5d0e168a3529..0a6cf5115af0 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1127,7 +1127,6 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
("tracing_attribute_breakdown", "tracing/spans/attribute-breakdown/", {}),
("tracing_trace_by_id", "tracing/spans/trace/zzz/", {}),
("metrics_query", "metrics/query/", {}),
- ("metrics_explain", "metrics/explain/", {}),
("experiments_setup_context", "experiments/setup_context/", {}),
]
)
diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.py
deleted file mode 100644
index 0ee3419a0c49..000000000000
--- a/products/metrics/backend/diagnostics.py
+++ /dev/null
@@ -1,330 +0,0 @@
-"""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 (
- _QUERY_SETTINGS,
- _interval_step,
- counter_lookback,
- points_query,
- series_labels_query,
- series_scope_expr,
- type_filter_expr,
-)
-from products.metrics.backend.metric_samples_query_runner import build_metric_query_runner
-from products.metrics.backend.metrics4_samples import reads_metrics4_only
-
-# 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 _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,
- timezone: str,
-) -> ast.SelectQuery:
- # The labels are joined on after the LIMIT so the row bound applies to the
- # data points read, not to the join output. A series without a row yet
- # keeps its samples and shows empty labels.
- query = parse_select(
- """
- SELECT
- s.series_fingerprint,
- s.service_name,
- ser.attributes,
- ser.resource_attributes,
- s.metric_type,
- s.aggregation_temporality,
- s.timestamp,
- s.value
- FROM (
- SELECT
- series_fingerprint,
- service_name,
- metric_type,
- aggregation_temporality,
- timestamp,
- value
- FROM {points}
- ORDER BY timestamp ASC
- LIMIT {row_limit}
- ) AS s
- LEFT JOIN {series_labels} AS ser ON s.series_fingerprint = ser.series_fingerprint
- ORDER BY s.timestamp ASC
- """,
- placeholders={
- "points": points_query(
- from_samples=reads_metrics4_only(date_from),
- columns=(
- "series_fingerprint",
- "service_name",
- "metric_type",
- "aggregation_temporality",
- "timestamp",
- "value",
- ),
- metric_names=(metric_name,),
- date_from=date_from,
- date_to=bucket_end,
- timezone=timezone,
- row_filters=(series_scope_expr(metric_name, filters), type_filter_expr(metric_type)),
- ),
- "row_limit": ast.Constant(value=_MAX_ROWS_READ),
- "series_labels": series_labels_query(metric_name),
- },
- )
- assert isinstance(query, ast.SelectQuery)
- return query
-
-
-def _actual_value(
- *,
- team: Team,
- metric_name: str,
- aggregation: str,
- 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.
-
- The runner reaches back past `date_from` on its own for the counter
- functions' predecessor sample, so this asks for exactly the one bucket the
- decomposition is explaining.
- """
- rows = build_metric_query_runner(
- team=team,
- metric_name=metric_name,
- aggregation=aggregation,
- date_from=bucket_start,
- 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 newest sample before the bucket,
- # the way the chart's window function does, so their raw read reaches back
- # over exactly the runner's lookback. A shorter reach here would find a
- # different predecessor and report a disagreement the chart does not have.
- needs_boundary = aggregation in ("rate", "increase")
- read_from = bucket_start - counter_lookback(interval) if needs_boundary else bucket_start
-
- response = execute_hogql_query(
- query_type="MetricBucketDecomposition",
- query=_raw_samples_query(
- metric_name=metric_name,
- date_from=read_from,
- bucket_end=bucket_end,
- filters=filters,
- metric_type=metric_type,
- timezone=team.timezone,
- ),
- 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 by the fingerprint ingest assigned, which
- # is the same identity the chart's window functions partition on.
- grouped: dict[int, list[Sample]] = {}
- predecessors: dict[int, Sample] = {}
- identities: dict[int, tuple[str, dict[str, str], dict[str, str]]] = {}
- resolved_type = metric_type or ""
- temporality = ""
- for (
- key,
- service_name,
- attributes,
- resource_attributes,
- row_metric_type,
- row_temporality,
- timestamp,
- value,
- ) in rows:
- 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 or {}), dict(resource_attributes or {})))
- # 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]
- if plan.temporal is TemporalReducer.POOLED_SAMPLES:
- series_value = None
- else:
- # Normalized the same way as the bucket's total, so the series
- # a reader adds up still reach the number they are explaining.
- reduced = reduce_temporal(reduction_input[key], plan.temporal)
- series_value = None if reduced is None else reduced / plan.divisor
- breakdown.append(
- MetricSeriesBreakdown(
- service_name=service_name,
- 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,
- value=series_value,
- )
- )
-
- actual_value = _actual_value(
- team=team,
- metric_name=metric_name,
- aggregation=aggregation,
- 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 877652bf44f5..c23c6a2bb1e9 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -21,13 +21,11 @@ from posthog.models import Team
from products.error_tracking.backend.facade.api import list_spike_events
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,
MetricErrorSpike,
MetricEventSample,
MetricFilter,
@@ -567,34 +565,3 @@ 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 38967707adde..fe3b1aba222b 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -37,12 +37,6 @@ METRICS_FEATURE_FLAG = "metrics"
# Staff-only while it is a proof of concept.
METRICS_ERROR_OVERLAYS_FEATURE_FLAG = "metrics-error-overlays"
-# Fundamentals recomputes a chart point from its raw samples so the viewer's own
-# reductions can be checked. That makes it a tool for the people who build the
-# viewer, not a feature for the teams on the alpha, so it needs a gate of its own
-# on top of METRICS_FEATURE_FLAG.
-METRICS_FUNDAMENTALS_FEATURE_FLAG = "metrics-fundamentals"
-
@dataclass(frozen=True, slots=True)
class MetricFilter:
@@ -370,61 +364,3 @@ class MetricsOverview:
series: int
lookback_seconds: int
services: tuple[MetricsServiceOverview, ...]
-
-
-@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
deleted file mode 100644
index 5fa5753ce4b5..000000000000
--- a/products/metrics/backend/fundamentals.py
+++ /dev/null
@@ -1,273 +0,0 @@
-"""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 | None:
- """Collapse one series' samples to that series' value for the bucket.
-
- Returns None when the value is unknowable: a lone cumulative reading has
- no predecessor to diff against, and 0 would read as a flat counter.
- """
- if reducer in (TemporalReducer.NONE, TemporalReducer.POOLED_SAMPLES):
- raise ValueError(f"{reducer!r} has no single per-series value; apply it through a plan")
- ordered = _deduped_in_time_order(samples)
- if reducer == TemporalReducer.INCREASE:
- # A reading below its predecessor means the counter restarted, and the
- # post-restart reading is itself the increase.
- if len(ordered) < 2:
- return None
- total = 0.0
- for previous, current in zip(ordered, ordered[1:]):
- total += current.value - previous.value if current.value >= previous.value else current.value
- return total
- if not ordered:
- return 0.0
-
- 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)
- 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:
- # An unknowable series value contributes nothing rather than a fake 0,
- # and a bucket holding only unknowns has no value at all.
- reduced = (reduce_temporal(samples, plan.temporal) for samples in series_samples.values() if samples)
- per_series_values = [value for value in reduced if value is not None]
- value = reduce_spatial(per_series_values, plan.spatial, quantile=plan.quantile)
- # An empty bucket has no number, and normalizing None would invent one.
- return value if value is None else value / plan.divisor
-
-
-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 1ecde4439827..d41801825b1b 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -28,7 +28,6 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedR
from products.metrics.backend.facade.api import (
characterize_metric_anomaly,
- explain_metric_bucket,
get_metrics_overview,
list_metric_attribute_keys,
list_metric_attribute_values,
@@ -44,7 +43,6 @@ from products.metrics.backend.facade.contracts import (
MAX_SPARKLINE_BATCH_SIZE,
METRICS_ERROR_OVERLAYS_FEATURE_FLAG,
METRICS_FEATURE_FLAG,
- METRICS_FUNDAMENTALS_FEATURE_FLAG,
MetricFilter,
MetricGroupBy,
MetricQueryClause,
@@ -736,130 +734,6 @@ class _MetricErrorSpikesResponseSerializer(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", "min", "max", "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=MetricQueryInterval.choices,
- 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"
@@ -1177,72 +1051,6 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return Response({"results": [asdict(s) for s in spikes]}, 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."""
- # The class-level gate admits every team on the metrics alpha, which is wider
- # than this action should be. Fundamentals is a correctness tool for the people
- # who build the viewer, so it carries its own flag. Without this check the tab
- # is hidden in the UI but the data behind it stays one POST away.
- if not posthog_feature_flag_enabled(
- METRICS_FUNDAMENTALS_FEATURE_FLAG,
- str(cast(User, request.user).distinct_id),
- organization_id=self.team.organization_id,
- team_id=self.team.pk,
- ):
- raise PermissionDenied(
- f"This action requires feature flag {METRICS_FUNDAMENTALS_FEATURE_FLAG!r} to be enabled for your organization."
- )
-
- 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/conftest.py b/products/metrics/backend/tests/conftest.py
index 477d97eedeb2..d40800c3c666 100644
--- a/products/metrics/backend/tests/conftest.py
+++ b/products/metrics/backend/tests/conftest.py
@@ -5,18 +5,15 @@ from unittest.mock import patch
from posthog.api.snuffle_proxy import SNUFFLE_API_FEATURE_FLAG
-from products.metrics.backend.facade.contracts import METRICS_FUNDAMENTALS_FEATURE_FLAG
-
@pytest.fixture(autouse=True)
def enable_metrics_feature_flag() -> Iterator[None]:
# Enable the flags needed by the metrics endpoint tests.
# MetricsViewSet needs `metrics`.
- # The explain action needs `METRICS_FUNDAMENTALS_FEATURE_FLAG`.
# The Prometheus proxy needs `SNUFFLE_API_FEATURE_FLAG`.
# Gate tests set their flag to False.
def _feature_enabled(flag_key: str, *args: object, **kwargs: object) -> bool:
- return flag_key in ("metrics", METRICS_FUNDAMENTALS_FEATURE_FLAG, SNUFFLE_API_FEATURE_FLAG)
+ return flag_key in ("metrics", SNUFFLE_API_FEATURE_FLAG)
with patch("posthoganalytics.feature_enabled", side_effect=_feature_enabled):
yield
diff --git a/products/metrics/backend/tests/test_api.py b/products/metrics/backend/tests/test_api.py
index 0e14687a3245..33ac9e49bdd5 100644
--- a/products/metrics/backend/tests/test_api.py
+++ b/products/metrics/backend/tests/test_api.py
@@ -18,7 +18,6 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.facade.user_access_control import AccessControlLevelResource
from products.access_control.backend.models.access_control import AccessControl
from products.error_tracking.backend.facade.testing import create_issue, create_spike_event
-from products.metrics.backend.facade.contracts import METRICS_FUNDAMENTALS_FEATURE_FLAG
class TestMetricsValuesApi(APIBaseTest):
@@ -109,23 +108,6 @@ class TestMetricsFeatureFlagGate(APIBaseTest):
assert response.status_code == expected_status
- @parameterized.expand(
- [
- ("enabled", True, status.HTTP_400_BAD_REQUEST),
- ("disabled", False, status.HTTP_403_FORBIDDEN),
- ]
- )
- def test_fundamentals_flag_gates_the_explain_action(
- self, _name: str, fundamentals_enabled: bool, expected_status: int
- ) -> None:
- def feature_enabled(flag: str, *args: object, **kwargs: object) -> bool:
- return fundamentals_enabled if flag == METRICS_FUNDAMENTALS_FEATURE_FLAG else True
-
- with patch("posthoganalytics.feature_enabled", side_effect=feature_enabled):
- response = self.client.post(f"/api/projects/{self.team.id}/metrics/explain/", {}, format="json")
-
- assert response.status_code == expected_status
-
@pytest.mark.ee
class TestMetricsAccessControl(APIBaseTest):
@@ -182,7 +164,6 @@ class TestMetricsAccessControl(APIBaseTest):
("query", "POST", {}),
("samples", "POST", {}),
("error_spikes", "GET", {}),
- ("explain", "POST", {}),
("characterize", "POST", {}),
]
)
diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.py
deleted file mode 100644
index 191b16bf2466..000000000000
--- a/products/metrics/backend/tests/test_diagnostics.py
+++ /dev/null
@@ -1,361 +0,0 @@
-import datetime as dt
-
-import pytest
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from unittest.mock import patch
-
-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, truncate_metrics_tables
-
-BUCKET = dt.datetime(2026, 9, 15, 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()
- truncate_metrics_tables()
-
- 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_lone_cumulative_sample_has_no_increase_on_either_side(self) -> None:
- seed_metric(
- team_id=self.team.pk,
- metric_name="bytes_total",
- metric_type="sum",
- aggregation_temporality="cumulative",
- is_monotonic=True,
- points=[(BUCKET, 100.0)],
- )
-
- decomposition = decompose_bucket(
- team=self.team,
- metric_name="bytes_total",
- aggregation="increase",
- bucket_start=BUCKET,
- interval="minute_5",
- )
-
- # The sample's history is unknown, so both the reference and the chart
- # return no value — a 0 on either side would fabricate a flat counter.
- assert decomposition.reference_value is None
- assert decomposition.actual_value is None
- assert decomposition.agrees is True
-
- def test_empty_bucket_reports_no_series_rather_than_zero(self) -> None:
- decomposition = decompose_bucket(
- team=self.team,
- 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()
- truncate_metrics_tables()
-
- 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()
- truncate_metrics_tables()
- # 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_agrees_when_the_predecessor_sits_further_back_than_one_bucket(self) -> None:
- # A minute chart of a series scraped every few minutes: the reference
- # reduction and the runner have to reach back over the same window, or
- # one of them finds a predecessor the other doesn't and the tab reports
- # a disagreement the chart never had.
- seed_metric(
- team_id=self.team.pk,
- metric_name="packets_total",
- metric_type="sum",
- aggregation_temporality="cumulative",
- is_monotonic=True,
- points=[
- (BUCKET - dt.timedelta(minutes=3), 100.0),
- (BUCKET + dt.timedelta(seconds=30), 120.0),
- ],
- )
-
- decomposition = decompose_bucket(
- team=self.team,
- metric_name="packets_total",
- aggregation="increase",
- bucket_start=BUCKET,
- interval="minute",
- )
-
- assert decomposition.reference_value == 20.0
- assert decomposition.actual_value == 20.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()
- truncate_metrics_tables()
-
- 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
deleted file mode 100644
index 5a2bdc5603e9..000000000000
--- a/products/metrics/backend/tests/test_fundamentals.py
+++ /dev/null
@@ -1,206 +0,0 @@
-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_of_a_lone_sample_is_unknown_not_zero(self) -> None:
- # One reading has no predecessor to diff against; 0 would read as "flat".
- assert reduce_temporal(_samples(100), TemporalReducer.INCREASE) is None
-
- def test_avg_over_time_keeps_the_whole_bucket_not_just_the_tail(self) -> None:
- # A queue that spiked to 240 and settled at 8 did not average 8.
- 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
-
- def test_unknown_series_values_drop_out_rather_than_zeroing_the_bucket(self) -> None:
- plan = plan_reduction(aggregation="increase", metric_type="sum", temporality="cumulative")
- # A lone-sample series adds nothing to the total, and a bucket holding
- # only such series has no value at all — mirroring the runner, which
- # drops the bucket instead of plotting 0.
- assert apply_plan({"a": _samples(100), "b": _samples(10, 25)}, plan) == 15.0
- assert apply_plan({"a": _samples(100)}, plan) is None
-
-
-class TestPooledQuantile:
- def test_percentile_reads_the_samples_rather_than_one_value_per_series(self) -> None:
- # 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 970aee6728c6..0688dd06e09c 100644
--- a/products/metrics/frontend/MetricsScene.tsx
+++ b/products/metrics/frontend/MetricsScene.tsx
@@ -3,7 +3,6 @@ import posthog from 'posthog-js'
import { LemonBanner, LemonButton, LemonTabs } from '@posthog/lemon-ui'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconFeedback } from 'lib/lemon-ui/icons'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { sceneConfigurations } from 'scenes/scenes'
@@ -18,15 +17,13 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { metricNamePickerLogic } from './components/metricNamePickerLogic'
import { MetricsCatalog } from './components/MetricsCatalog'
import { metricsCatalogLogic } from './components/metricsCatalogLogic'
-import { MetricsFundamentals } from './components/MetricsFundamentals'
-import { metricsFundamentalsLogic } from './components/metricsFundamentalsLogic'
import { MetricsOverview } from './components/MetricsOverview'
import { MetricsSqlEditor } from './components/MetricsSqlEditor'
import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'
import { MetricsViewer } from './components/MetricsViewer'
import { metricsEmptyState } from './emptyState/metricsEmptyState'
import { metricsFeaturePreviewGate } from './featurePreviewGate'
-import { DEFAULT_ACTIVE_TAB, MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'
+import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'
export const METRICS_LOGIC_KEY = 'metrics'
@@ -37,7 +34,6 @@ const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[]
{ key: 'explore', label: 'Explore', 'data-attr': 'metrics-scene-tab-explore' },
{ 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 = {
@@ -60,13 +56,6 @@ export function MetricsScene(): JSX.Element {
const MetricsSceneContent = (): JSX.Element => {
const { activeTab } = useValues(metricsSceneLogic)
const { setActiveTab } = useActions(metricsSceneLogic)
- // Fundamentals checks the viewer's own reductions against the raw samples, so it is
- // built for the people who work on the viewer rather than for the teams on the alpha.
- const fundamentalsEnabled = useFeatureFlag('METRICS_FUNDAMENTALS')
- const visibleTabs = fundamentalsEnabled ? TABS : TABS.filter((tab) => tab.key !== 'fundamentals')
- // A guessed ?activeTab=fundamentals must not render the tab either, so fall back to the
- // default tab instead of leaving the scene with no visible content.
- const effectiveTab = activeTab === 'fundamentals' && !fundamentalsEnabled ? DEFAULT_ACTIVE_TAB : activeTab
const metricsViewerDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Metrics,
AccessControlLevel.Viewer
@@ -80,7 +69,6 @@ const MetricsSceneContent = (): JSX.Element => {
explore: metricsViewerDisabledReason,
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.
@@ -88,11 +76,9 @@ const MetricsSceneContent = (): JSX.Element => {
// Prime the metric-name list here rather than inside MetricsViewer, so the fetch
// races the has_metrics check instead of waiting on the setup prompt to resolve.
useMountedLogic(metricNamePickerLogic)
- // These two hold cross-tab state: a catalog card click preloads the viewer, and
- // the viewer's explain button preloads fundamentals. Mounted here, a tab flip
- // cannot unmount the logic and reset the handoff before the destination reads it.
+ // Holds cross-tab state: a catalog card click preloads the viewer. Mounted here, a tab
+ // flip cannot unmount the logic and reset the handoff before the destination reads it.
useMountedLogic(metricsCatalogLogic)
- useMountedLogic(metricsFundamentalsLogic)
const onFeedbackClick = (): void => {
posthog.displaySurvey(METRICS_FEEDBACK_SURVEY_ID)
@@ -124,24 +110,23 @@ const MetricsSceneContent = (): JSX.Element => {
Metrics is in alpha. Please share feedback on how to improve the product.
</LemonBanner>
<LemonTabs<MetricsSceneActiveTab>
- activeKey={effectiveTab}
+ activeKey={activeTab}
onChange={(tab) => {
if (!tabDisabledReasons[tab]) {
setActiveTab(tab)
}
}}
- tabs={visibleTabs.map((tab) => ({
+ tabs={TABS.map((tab) => ({
...tab,
disabledReason: tabDisabledReasons[tab.key] ?? undefined,
}))}
sceneInset
/>
<div className="flex flex-col gap-2 py-2 flex-1 min-h-0">
- {effectiveTab === 'overview' && <MetricsOverview />}
- {effectiveTab === 'explore' && <MetricsCatalog />}
- {effectiveTab === 'viewer' && <MetricsViewer />}
- {effectiveTab === 'sql' && <MetricsSqlEditor />}
- {effectiveTab === 'fundamentals' && <MetricsFundamentals />}
+ {activeTab === 'overview' && <MetricsOverview />}
+ {activeTab === 'explore' && <MetricsCatalog />}
+ {activeTab === 'viewer' && <MetricsViewer />}
+ {activeTab === 'sql' && <MetricsSqlEditor />}
</div>
</>
)
diff --git a/products/metrics/frontend/components/MetricsClauseRow.tsx b/products/metrics/frontend/components/MetricsClauseRow.tsx
index 60577575d465..606f1e9dc53d 100644
--- a/products/metrics/frontend/components/MetricsClauseRow.tsx
+++ b/products/metrics/frontend/components/MetricsClauseRow.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { IconEllipsis, IconInfo } from '@posthog/icons'
+import { IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonSelect, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -9,10 +9,8 @@ import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
-import { metricsSceneLogic } from '../metricsSceneLogic'
import { MetricNameFilter } from './MetricNameFilter'
import { MetricsClauseFilterBar } from './MetricsClauseFilterBar'
-import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'
import { MetricsGroupByButton } from './MetricsGroupByButton'
import {
MAX_CLAUSES,
@@ -41,7 +39,6 @@ export function MetricsClauseRow({
index,
isActive,
showAlias,
- showExplain = true,
disabledReason,
}: {
clause: MetricsViewerClause
@@ -49,8 +46,6 @@ export function MetricsClauseRow({
isActive: boolean
/** Aliases only mean something once there is more than one series. */
showAlias: boolean
- /** The explain button opens the `/metrics` Fundamentals tab, so only the viewer shows it. */
- showExplain?: boolean
disabledReason: string | null
}): JSX.Element {
const { viewerClauses, attributeEndpointFilters } = useValues(metricsViewerLogic)
@@ -110,17 +105,12 @@ export function MetricsClauseRow({
</Tooltip>
)}
<div className="flex flex-col gap-1">
- <div className="flex items-center gap-1">
- <MetricNameFilter
- value={clause.metricName}
- onChange={withSelect(setMetricName)}
- disabled={!!disabledReason}
- disabledReason={disabledReason}
- />
- {showExplain && clause.metricName && clause.selectedMetricType && (
- <MetricsClauseExplainButton clause={clause} />
- )}
- </div>
+ <MetricNameFilter
+ value={clause.metricName}
+ onChange={withSelect(setMetricName)}
+ disabled={!!disabledReason}
+ disabledReason={disabledReason}
+ />
{clause.selectedMetricType &&
recommendedAggregation &&
(clause.aggregation !== recommendedAggregation ? (
@@ -193,27 +183,3 @@ export function MetricsClauseRow({
</div>
)
}
-
-// A separate component, so the scene logics it uses only mount where the button shows.
-function MetricsClauseExplainButton({ clause }: { clause: MetricsViewerClause }): JSX.Element {
- const { setActiveTab } = useActions(metricsSceneLogic)
- const { explainMetric } = useActions(metricsFundamentalsLogic)
-
- return (
- <Tooltip title="Take this metric apart: see how its chart value is recomputed from raw samples.">
- <LemonButton
- size="small"
- type="tertiary"
- icon={<IconInfo />}
- onClick={() => {
- explainMetric({
- metricName: clause.metricName,
- aggregation: clause.aggregation,
- })
- setActiveTab('fundamentals')
- }}
- data-attr="metrics-clause-explain"
- />
- </Tooltip>
- )
-}
diff --git a/products/metrics/frontend/components/MetricsFundamentals.tsx b/products/metrics/frontend/components/MetricsFundamentals.tsx
deleted file mode 100644
index c80326c6fe29..000000000000
--- a/products/metrics/frontend/components/MetricsFundamentals.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-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: 'min', label: 'Min' },
- { value: 'max', label: 'Max' },
- { 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/MetricsQueryEditor.tsx b/products/metrics/frontend/components/MetricsQueryEditor.tsx
index 573df4f32ded..fe3e506ddac4 100644
--- a/products/metrics/frontend/components/MetricsQueryEditor.tsx
+++ b/products/metrics/frontend/components/MetricsQueryEditor.tsx
@@ -98,7 +98,6 @@ function MetricsQueryEditorControls({
index={index}
isActive={index === activeClauseIndex}
showAlias={viewerClauses.length > 1}
- showExplain={false}
disabledReason={disabledReason}
/>
))}
diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts b/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts
deleted file mode 100644
index af32645d3d39..000000000000
--- a/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-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()
- })
-
- it('explainMetric prefills the name and aggregation, then runs the check', async () => {
- // The viewer's "explain this number" hands over a metric the user is already
- // looking at, so the check must not make them retype it.
- jest.mocked(metricsQueryCreate).mockResolvedValue(queryResponse([{ time: '2026-01-01T00:05:00Z', value: 2 }]))
-
- await expectLogic(logic, () =>
- logic.actions.explainMetric({ metricName: 'cache_size', aggregation: 'avg' })
- ).toFinishAllListeners()
-
- expect(logic.values.metricName).toBe('cache_size')
- expect(logic.values.aggregation).toBe('avg')
- expect(metricsExplainCreate).toHaveBeenCalled()
- })
-})
diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.tsx b/products/metrics/frontend/components/metricsFundamentalsLogic.tsx
deleted file mode 100644
index cfa3fba23f12..000000000000
--- a/products/metrics/frontend/components/metricsFundamentalsLogic.tsx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { MakeLogicType, actions, kea, listeners, 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 {
- explainMetric: (payload: { aggregation: MetricAggregation; metricName: string }) => {
- aggregation: MetricAggregation
- metricName: string
- }
- 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,
- // The viewer's "explain this number" entry: prefill the metric the user is
- // already looking at and run the check, so the handoff needs no retyping.
- explainMetric: (payload: { metricName: string; aggregation: MetricAggregation }) => payload,
- }),
-
- reducers({
- metricName: [
- '',
- {
- setMetricName: (_, { metricName }) => metricName,
- explainMetric: (_, { metricName }) => metricName,
- },
- ],
- aggregation: [
- 'sum' as MetricAggregation,
- {
- setAggregation: (_, { aggregation }) => aggregation,
- explainMetric: (_, { 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() ?? ''],
- }),
-
- listeners(({ actions }) => ({
- explainMetric: () => {
- // Reducers have already prefilled the name and aggregation; run the check.
- actions.runCheck()
- },
- })),
-])
diff --git a/products/metrics/frontend/components/metricsHandoff.test.ts b/products/metrics/frontend/components/metricsHandoff.test.ts
index 72222257fccc..66d788767cd3 100644
--- a/products/metrics/frontend/components/metricsHandoff.test.ts
+++ b/products/metrics/frontend/components/metricsHandoff.test.ts
@@ -5,19 +5,16 @@ import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/typ
import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'
import { metricsCatalogLogic } from './metricsCatalogLogic'
-import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'
jest.mock('../generated/api', () => ({
...jest.requireActual('../generated/api'),
metricsNamesRetrieve: jest.fn(),
metricsValuesRetrieve: jest.fn(),
metricsQueryCreate: jest.fn(),
- metricsExplainCreate: jest.fn(),
}))
-// The catalog and fundamentals logics are keyed (global) logics whose state must
-// survive a tab flip: a card click preloads the viewer, and the viewer's explain
-// button preloads fundamentals. The scene mounts both, so unmounting the tab
+// The catalog logic is a keyed (global) logic whose state must survive a tab flip:
+// a card click preloads the viewer. The scene mounts it, so unmounting the tab
// component that also subscribes must not reset the preloaded state.
describe('metrics cross-tab handoffs', () => {
beforeEach(() => {
@@ -32,29 +29,6 @@ describe('metrics cross-tab handoffs', () => {
jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] } as any)
})
- it('explainMetric state survives the viewer tab unmounting', async () => {
- // Stand-in for the scene-level mount that keeps the logic alive across tabs.
- const sceneHold = metricsFundamentalsLogic()
- sceneHold.mount()
- // Stand-in for the MetricsClauseRow subscription inside the viewer tab.
- const viewerHold = metricsFundamentalsLogic()
- viewerHold.mount()
-
- await expectLogic(sceneHold, () =>
- sceneHold.actions.explainMetric({ metricName: 'cache_size', aggregation: 'avg' })
- ).toFinishAllListeners()
- expect(sceneHold.values.metricName).toBe('cache_size')
-
- // The viewer tab unmounts while fundamentals renders. With only the tab
- // holding a subscription, kea would unmount the logic and drop the
- // prefill; the scene hold must keep it alive.
- viewerHold.unmount()
-
- expect(sceneHold.values.metricName).toBe('cache_size')
- expect(sceneHold.values.aggregation).toBe('avg')
- sceneHold.unmount()
- })
-
it('a loaded catalog survives the explore tab unmounting', async () => {
const items = [{ name: 'jobs.processed', metric_type: 'sum' }]
jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: items } as any)
diff --git a/products/metrics/frontend/components/metricsOverviewLogic.test.ts b/products/metrics/frontend/components/metricsOverviewLogic.test.ts
index baeccfeb8994..bc8cdd38ce12 100644
--- a/products/metrics/frontend/components/metricsOverviewLogic.test.ts
+++ b/products/metrics/frontend/components/metricsOverviewLogic.test.ts
@@ -14,7 +14,6 @@ jest.mock('../generated/api', () => ({
metricsAttributeValuesRetrieve: jest.fn(),
metricsAttributesRetrieve: jest.fn(),
metricsCharacterizeCreate: jest.fn(),
- metricsExplainCreate: jest.fn(),
metricsHasMetricsRetrieve: jest.fn(),
metricsOverviewRetrieve: jest.fn(),
metricsQueryCreate: jest.fn(),
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 2d4c28c3b1ca..2c399d321e59 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -295,245 +295,6 @@ export interface _MetricErrorSpikesResponseApi {
results: _MetricErrorSpikeApi[]
}
-/**
- * * `gauge` - gauge
- * * `sum` - sum
- * * `histogram` - histogram
- * * `exponential_histogram` - exponential_histogram
- * * `summary` - summary
- */
-export type OtelMetricTypeEnumApi = (typeof OtelMetricTypeEnumApi)[keyof typeof OtelMetricTypeEnumApi]
-
-export const OtelMetricTypeEnumApi = {
- Gauge: 'gauge',
- Sum: 'sum',
- Histogram: 'histogram',
- ExponentialHistogram: 'exponential_histogram',
- Summary: 'summary',
-} as const
-
-/**
- * * `second_15` - second_15
- * * `second_30` - second_30
- * * `minute` - minute
- * * `minute_5` - minute_5
- * * `minute_15` - minute_15
- * * `minute_30` - minute_30
- * * `hour` - hour
- * * `hour_6` - hour_6
- * * `day` - day
- * * `week` - week
- */
-export type MetricQueryIntervalEnumApi = (typeof MetricQueryIntervalEnumApi)[keyof typeof MetricQueryIntervalEnumApi]
-
-export const MetricQueryIntervalEnumApi = {
- Second15: 'second_15',
- Second30: 'second_30',
- Minute: 'minute',
- Minute5: 'minute_5',
- Minute15: 'minute_15',
- Minute30: 'minute_30',
- Hour: 'hour',
- Hour6: 'hour_6',
- Day: 'day',
- 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
- * * `min` - min
- * * `max` - max
- * * `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_15` - second_15
- * * `second_30` - second_30
- * * `minute` - minute
- * * `minute_5` - minute_5
- * * `minute_15` - minute_15
- * * `minute_30` - minute_30
- * * `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
@@ -578,6 +339,23 @@ export interface _MetricsOverviewResponseApi {
services: _MetricsOverviewServiceApi[]
}
+/**
+ * * `gauge` - gauge
+ * * `sum` - sum
+ * * `histogram` - histogram
+ * * `exponential_histogram` - exponential_histogram
+ * * `summary` - summary
+ */
+export type OtelMetricTypeEnumApi = (typeof OtelMetricTypeEnumApi)[keyof typeof OtelMetricTypeEnumApi]
+
+export const OtelMetricTypeEnumApi = {
+ Gauge: 'gauge',
+ Sum: 'sum',
+ Histogram: 'histogram',
+ ExponentialHistogram: 'exponential_histogram',
+ Summary: 'summary',
+} as const
+
export interface _MetricGroupByApi {
/**
* Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
@@ -592,6 +370,33 @@ export interface _MetricGroupByApi {
scope?: MetricAttributeScopeEnumApi
}
+/**
+ * * `second_15` - second_15
+ * * `second_30` - second_30
+ * * `minute` - minute
+ * * `minute_5` - minute_5
+ * * `minute_15` - minute_15
+ * * `minute_30` - minute_30
+ * * `hour` - hour
+ * * `hour_6` - hour_6
+ * * `day` - day
+ * * `week` - week
+ */
+export type MetricQueryIntervalEnumApi = (typeof MetricQueryIntervalEnumApi)[keyof typeof MetricQueryIntervalEnumApi]
+
+export const MetricQueryIntervalEnumApi = {
+ Second15: 'second_15',
+ Second30: 'second_30',
+ Minute: 'minute',
+ Minute5: 'minute_5',
+ Minute15: 'minute_15',
+ Minute30: 'minute_30',
+ Hour: 'hour',
+ Hour6: 'hour_6',
+ Day: 'day',
+ Week: 'week',
+} as const
+
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 411333ea8d95..db916a058a92 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -23,8 +23,6 @@ import type {
_MetricAttributeValuesResponseApi,
_MetricCatalogValuesParamsApi,
_MetricErrorSpikesResponseApi,
- _MetricExplainRequestApi,
- _MetricExplainResponseApi,
_MetricNamesResponseApi,
_MetricPickerNamesResponseApi,
_MetricQueryRequestApi,
@@ -194,28 +192,6 @@ export const metricsErrorSpikesRetrieve = 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 a0b66034d4d6..cceaa08bb811 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -114,116 +114,6 @@ 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', 'min', 'max', 'p95', 'rate', 'increase', 'histogram_quantile'])
- .describe(
- '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `min` - min\n\* `max` - max\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\* `min` - min\n\* `max` - max\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_15',
- 'second_30',
- 'minute',
- 'minute_5',
- 'minute_15',
- 'minute_30',
- 'hour',
- 'hour_6',
- 'day',
- 'week',
- ])
- .describe(
- '\* `second_15` - second_15\n\* `second_30` - second_30\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `minute_30` - minute_30\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_15` - second_15\n\* `second_30` - second_30\n\* `minute` - minute\n\* `minute_5` - minute_5\n\* `minute_15` - minute_15\n\* `minute_30` - minute_30\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 bb6b562974c2..ef34f5050753 100644
--- a/products/metrics/frontend/metricsSceneLogic.tsx
+++ b/products/metrics/frontend/metricsSceneLogic.tsx
@@ -34,8 +34,8 @@ import {
export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'
-export type MetricsSceneActiveTab = 'overview' | 'explore' | 'viewer' | 'sql' | 'fundamentals'
-const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'explore', 'viewer', 'sql', 'fundamentals']
+export type MetricsSceneActiveTab = 'overview' | 'explore' | 'viewer' | 'sql'
+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'explore', 'viewer', 'sql']
export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'overview'
// kea-router pre-parses JSON-looking params, so anything a user types into the URL can reach
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4bbc73fe412e..76b55819c057 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -103226,26 +103226,6 @@ 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
@@ -107352,26 +107332,6 @@ export namespace Schemas {
notes: string;
}
- /**
- * * `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;
-
/**
* Anthropic text, image, or tool content blocks.
*/
@@ -112002,101 +111962,6 @@ 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 _MetricCatalogValuesParams {
/**
* Substring filter (case-insensitive) applied to metric names.
@@ -112237,68 +112102,6 @@ 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
- * * `min` - min
- * * `max` - max
- * * `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_15` - second_15
- * * `second_30` - second_30
- * * `minute` - minute
- * * `minute_5` - minute_5
- * * `minute_15` - minute_15
- * * `minute_30` - minute_30
- * * `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;