Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(metrics): chart one line per series by default with operation chips (#113473)

Frank Hamandd972cb189afc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index faffb567772b..d7fbfee832b8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6326,14 +6326,6 @@ snapshots:
hash: v1.k794b7964.ce83d5c6298b08ac62a7eeb1365881f3eaad9e77a2ffc762a8683bb5360cf49f.ZybY7nObSqgkgX4qZO0IbHSimFba2tRWMI3lKApT73o
metrics-group-by--default--light:
hash: v1.k794b7964.6569c85c82c01e61526ea93e8d61158da38a1c465eac8cafad2b87e2d09a287a.RVDxyDYqLRvzRQdz3BZmwkiYQQ0pCllfzH6Z5xQJiGw
- metrics-metricscatalog--default--dark:
- hash: v1.k794b7964.a1464d9a9bef8d961229aa836b02bba22e3baf5683fd6928bad2043e661fb63c.uJFa3cShWZCenILbuE_EpT0yJMsK1lbSZhPfe0ghE0Y
- metrics-metricscatalog--default--light:
- hash: v1.k794b7964.abf03105e43775229318033668be854ce9984399ad5443c6f807f489b7f6804d.ihwV_9JDumkdExc2ZxSOnUFULoe4iX7uMDqWezNx_qU
- metrics-metricscatalog--narrow--dark:
- hash: v1.k794b7964.2bcd3736aebabc2318ff73411a9a91afe46482ad9bd6b956384d5bae6df59471.K6FU2bGvPPBZdFlHEPr5VDzBofsHaZtUvErUaJZ2f6Y
- metrics-metricscatalog--narrow--light:
- hash: v1.k794b7964.a3e0f3eca9aaa6069dba0367ecd31c7bd9d47c9172e06ac68f0ebdad551dcb56.EhcEcU7jd55Gt3GugyXqtOowPSUwBvacNVGulhHN1t0
posthog-3000-keyboard-shortcut--default--dark:
hash: v1.k794b7964.a5fc5a426df52137d3fb6377a06c7b39c36b041280de154cf2b95cbe46932b8d.f2HHu2jv6bztshqmrVtHpiuuv3PJZNskIh7SbZRgIpk
posthog-3000-keyboard-shortcut--default--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b86c78f8ff8f..235ff33c7edc 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -39460,7 +39460,8 @@
"additionalProperties": false,
"properties": {
"aggregation": {
- "$ref": "#/definitions/MetricsAggregation"
+ "$ref": "#/definitions/MetricsAggregation",
+ "description": "Omit to get one line per series (at most 100), without combining them"
},
"filters": {
"items": {
@@ -39488,9 +39489,13 @@
"quantile": {
"description": "In (0, 1); required for `quantile` / `histogram_quantile` aggregations",
"type": "number"
+ },
+ "rangeFunction": {
+ "$ref": "#/definitions/MetricsRangeFunction",
+ "description": "Applied to each series before `aggregation`, like `rate()` in PromQL"
}
},
- "required": ["name", "metricName", "aggregation"],
+ "required": ["name", "metricName"],
"type": "object"
},
"MetricsQueryFilter": {
@@ -39636,6 +39641,11 @@
"required": ["labels", "points"],
"type": "object"
},
+ "MetricsRangeFunction": {
+ "description": "Counter-aware transform applied to each series before any aggregation",
+ "enum": ["rate", "increase"],
+ "type": "string"
+ },
"MetricsReducer": {
"description": "How a series collapses to one number for the scalar panels and legend calcs.",
"enum": ["last", "mean", "min", "max", "sum", "delta"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ee04527219e9..9e69605c2927 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4866,6 +4866,9 @@ export type MetricsAggregation =
| 'increase'
| 'histogram_quantile'
+/** Counter-aware transform applied to each series before any aggregation */
+export type MetricsRangeFunction = 'rate' | 'increase'
+
export interface MetricsQueryFilter {
key: string
op: MetricsFilterOp
@@ -4882,7 +4885,10 @@ export interface MetricsQueryClause {
/** Alias a formula refers to (e.g. "a"); must be unique within the query */
name: string
metricName: string
- aggregation: MetricsAggregation
+ /** Omit to get one line per series (at most 100), without combining them */
+ aggregation?: MetricsAggregation
+ /** Applied to each series before `aggregation`, like `rate()` in PromQL */
+ rangeFunction?: MetricsRangeFunction
/** Series identity includes the OTel type — one name can exist as e.g. both a
* counter and a gauge — so a clause pins it to avoid blending distinct series. */
metricType?: MetricsOtelType
diff --git a/posthog/schema.py b/posthog/schema.py
index 53dfb52b758e..de5ace498f16 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -212,6 +212,7 @@ from posthog.schema_enums import (
MetricsFilterOp as MetricsFilterOp,
MetricsNullMode as MetricsNullMode,
MetricsOtelType as MetricsOtelType,
+ MetricsRangeFunction as MetricsRangeFunction,
MetricsReducer as MetricsReducer,
MetricsStatSummary as MetricsStatSummary,
MetricSummary as MetricSummary,
@@ -6838,7 +6839,10 @@ class MetricsQueryClause(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
- aggregation: MetricsAggregation
+ aggregation: MetricsAggregation | None = Field(
+ default=None,
+ description=("Omit to get one line per series (at most 100), without combining them"),
+ )
filters: list[MetricsQueryFilter] | None = None
groupBy: list[MetricsQueryGroupBy] | None = None
metricName: str
@@ -6858,6 +6862,10 @@ class MetricsQueryClause(BaseModel):
default=None,
description=("In (0, 1); required for `quantile` / `histogram_quantile` aggregations"),
)
+ rangeFunction: MetricsRangeFunction | None = Field(
+ default=None,
+ description=("Applied to each series before `aggregation`, like `rate()` in PromQL"),
+ )
class MultiQuestionFormField(BaseModel):
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index f27bb2fe85aa..020aba5a4596 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2197,6 +2197,11 @@ class MetricsOtelType(StrEnum):
SUMMARY = "summary"
+class MetricsRangeFunction(StrEnum):
+ RATE = "rate"
+ INCREASE = "increase"
+
+
class MetricsReducer(StrEnum):
LAST = "last"
MEAN = "mean"
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4262a9437faa..3758be23cc98 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -624,6 +624,9 @@ SPECTACULAR_SETTINGS = {
# Matches the shared alerts skeleton's PlatformAlert.State.
"BillingAlertConfigurationStateEnum": "products.billing_alerts.backend.models.BillingAlertConfiguration.State",
"LogsPatternsSourceEnum": ["stored_patterns", "body_mining"],
+ # The anomaly and explain bodies keep this name; the metrics query clause's own
+ # aggregation adds 'none' and is named by its MetricQueryAggregation class.
+ "AggregationEnum": ["sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"],
# AutoresearchRun.Status and AutoresearchTrainingRun.Status share this set.
"ZendeskImportJobStatusEnum": "products.conversations.backend.models.zendesk_import_job.ZendeskImportJob.Status",
#
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index c23c6a2bb1e9..f49789cfea54 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -8,6 +8,7 @@ so import-linter's strict-mode contract holds.
import math
import datetime as dt
from collections.abc import Sequence
+from dataclasses import replace
from typing import Any
from posthog.hogql import ast
@@ -45,11 +46,13 @@ from products.metrics.backend.metric_attributes_query_runner import (
)
from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner
from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner, cached_metric_names
+from products.metrics.backend.metric_query_runner import MAX_RAW_SERIES
from products.metrics.backend.metric_samples_query_runner import build_metric_query_runner
from products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunner
# MetricQueryRunner still speaks the legacy aggregation strings; this shrinks
# as later PRs teach the runner the remaining MetricAggregation values.
+# NONE maps to no aggregation, which is not a string.
_RUNNER_AGGREGATIONS: dict[MetricAggregation, str] = {
MetricAggregation.SUM: "sum",
MetricAggregation.AVG: "avg",
@@ -117,7 +120,8 @@ def _unit_for_fingerprints(fingerprints: set[int], units_by_fingerprint: dict[in
# Hard cap on series returned per clause; the largest series (by summed
# absolute value) win so the most significant groups survive truncation.
-MAX_SERIES_PER_CLAUSE = 100
+# A clause without an aggregation is capped earlier, in the query, at the same number.
+MAX_SERIES_PER_CLAUSE = MAX_RAW_SERIES
def _assemble_series(
@@ -130,11 +134,14 @@ def _assemble_series(
) -> list[MetricSeries]:
"""Split bucketed rows into one series per label-set, zero-filled onto
the shared grid so every series (and later, every clause of a formula)
- has identical timestamps."""
- by_labels: dict[tuple[tuple[str, str], ...], dict[str, float | None]] = {}
- fingerprints_by_labels: dict[tuple[tuple[str, str], ...], set[int]] = {}
+ has identical timestamps.
+
+ A row with a `series_key` stays apart from rows of another key, even when
+ their labels match: two physical series can share a label-set."""
+ by_labels: dict[tuple[tuple[tuple[str, str], ...], int | None], dict[str, float | None]] = {}
+ fingerprints_by_labels: dict[tuple[tuple[tuple[str, str], ...], int | None], set[int]] = {}
for row in rows:
- key = tuple(sorted(row["labels"].items()))
+ key = (tuple(sorted(row["labels"].items())), row.get("series_key"))
by_labels.setdefault(key, {})[row["time"]] = row["value"]
fingerprints_by_labels.setdefault(key, set()).update(row["series_fingerprints"])
@@ -147,7 +154,7 @@ def _assemble_series(
)
return [
MetricSeries(
- labels=dict(key),
+ labels=dict(key[0]),
points=tuple(MetricPoint(time=time, value=values.get(time, 0.0)) for time in grid),
metric_name=metric_name,
clause=clause_name,
@@ -157,7 +164,68 @@ def _assemble_series(
]
-def _resolve_runner_aggregation(clause: MetricQueryClause) -> str:
+def _labels_by_fingerprint(team: Team, metric_name: str, fingerprints: set[int]) -> dict[int, dict[str, str]]:
+ """The label set of each series, for a clause that returns series unaggregated.
+
+ Resource attributes come first, so a datapoint attribute of the same name wins.
+ """
+ if not fingerprints:
+ return {}
+ query = parse_select(
+ """
+ SELECT series_fingerprint, any(resource_attributes), any(attributes)
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ AND series_fingerprint IN {fingerprints}
+ GROUP BY series_fingerprint
+ """,
+ placeholders={
+ "metric_name": ast.Constant(value=metric_name),
+ "fingerprints": ast.Tuple(exprs=[ast.Constant(value=fp) for fp in sorted(fingerprints)]),
+ },
+ )
+ response = execute_hogql_query(
+ query_type="MetricSeriesLabelsLookup",
+ query=query,
+ team=team,
+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ settings=HogQLGlobalSettings(
+ max_execution_time=30,
+ max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,
+ read_overflow_mode="throw",
+ ),
+ )
+ return {
+ int(row[0]): {str(key): str(value) for key, value in {**(row[1] or {}), **(row[2] or {})}.items() if value}
+ for row in (response.results or [])
+ }
+
+
+def _attach_series_labels(team: Team, metric_name: str, rows: list[dict[str, Any]]) -> None:
+ """Give each row of an unaggregated clause the labels of its series."""
+ labels = _labels_by_fingerprint(team, metric_name, {fp for row in rows for fp in row["series_fingerprints"]})
+ for row in rows:
+ (fingerprint,) = row["series_fingerprints"]
+ row["labels"] = labels.get(int(fingerprint), {})
+ row["series_key"] = int(fingerprint)
+
+
+def _drop_shared_labels(series: list[MetricSeries]) -> list[MetricSeries]:
+ """With several series, keep only the labels that tell them apart.
+
+ A label that has the same value on every series only repeats in each legend entry.
+ """
+ if len(series) < 2:
+ return series
+ shared = {
+ key for key, value in series[0].labels.items() if all(other.labels.get(key) == value for other in series[1:])
+ }
+ return [replace(s, labels={k: v for k, v in s.labels.items() if k not in shared}) for s in series]
+
+
+def _resolve_runner_aggregation(clause: MetricQueryClause) -> str | None:
+ if clause.aggregation.is_raw:
+ return None
if clause.aggregation == MetricAggregation.QUANTILE and clause.quantile == 0.95:
return "p95"
if clause.aggregation == MetricAggregation.HISTOGRAM_QUANTILE:
@@ -255,8 +323,12 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
interval=request.interval,
quantile=clause.quantile if runner_aggregation == "histogram_quantile" else None,
metric_type=clause.metric_type.value if clause.metric_type is not None else None,
+ range_function=clause.range_function.value if clause.range_function is not None else None,
)
- rows_by_clause[clause.name] = runner.run()
+ rows = runner.run()
+ if runner_aggregation is None:
+ _attach_series_labels(team, clause.metric_name, rows)
+ rows_by_clause[clause.name] = rows
grid = sorted({row["time"] for rows in rows_by_clause.values() for row in rows})
if not grid:
@@ -286,7 +358,15 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
if formula_node_checked is not None:
return _evaluate_formula(formula_node_checked, series_by_clause, grid)
- return [series for clause in request.clauses for series in series_by_clause[clause.name]]
+ return [
+ series
+ for clause in request.clauses
+ for series in (
+ _drop_shared_labels(series_by_clause[clause.name])
+ if clause.aggregation.is_raw
+ else series_by_clause[clause.name]
+ )
+ ]
def list_metric_names(
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index fe3b1aba222b..c93801389689 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -22,7 +22,7 @@ from __future__ import annotations
import datetime as dt
from dataclasses import dataclass
-from .enums import AttributeScope, FilterOp, MetricAggregation, MetricType
+from .enums import AttributeScope, FilterOp, MetricAggregation, MetricRangeFunction, MetricType
# Each clause runs its own ClickHouse query on the shared logs cluster, so
# the clause count per request is hard-capped.
@@ -71,8 +71,14 @@ class MetricQueryClause:
quantile: float | None = None
# Constrains rows to one metric type; None keeps all types (legacy).
metric_type: MetricType | None = None
+ # Applied to each series before `aggregation` combines them.
+ range_function: MetricRangeFunction | None = None
def __post_init__(self) -> None:
+ if self.aggregation.is_raw and self.group_by:
+ raise ValueError("group_by needs an aggregation; without one every series stays separate")
+ if self.range_function is not None and self.aggregation.is_counter_function:
+ raise ValueError("range_function cannot combine with the legacy rate or increase aggregation")
if self.aggregation.needs_quantile:
if self.quantile is None:
raise ValueError(f"{self.aggregation} requires a quantile")
diff --git a/products/metrics/backend/facade/enums.py b/products/metrics/backend/facade/enums.py
index 39ec8c0e0ec7..df931a73084c 100644
--- a/products/metrics/backend/facade/enums.py
+++ b/products/metrics/backend/facade/enums.py
@@ -10,6 +10,8 @@ from __future__ import annotations
from enum import StrEnum
+from posthog.enums import LabeledStrEnum
+
class AttributeScope(StrEnum):
"""Where a label lives on a `metrics1` row.
@@ -71,8 +73,12 @@ class MetricAggregation(StrEnum):
arrays rather than the scalar `value`.
QUANTILE and HISTOGRAM_QUANTILE require the clause's `quantile` field.
+
+ NONE combines nothing: the clause returns one series per physical series,
+ capped at 100 series.
"""
+ NONE = "none"
SUM = "sum"
AVG = "avg"
COUNT = "count"
@@ -83,6 +89,10 @@ class MetricAggregation(StrEnum):
INCREASE = "increase"
HISTOGRAM_QUANTILE = "histogram_quantile"
+ @property
+ def is_raw(self) -> bool:
+ return self is MetricAggregation.NONE
+
@property
def needs_quantile(self) -> bool:
return self in (MetricAggregation.QUANTILE, MetricAggregation.HISTOGRAM_QUANTILE)
@@ -90,3 +100,15 @@ class MetricAggregation(StrEnum):
@property
def is_counter_function(self) -> bool:
return self in (MetricAggregation.RATE, MetricAggregation.INCREASE)
+
+
+class MetricRangeFunction(LabeledStrEnum):
+ """A per-series transform that runs before the cross-series aggregation.
+
+ Both read the change in a counter across each bucket (cumulative counters
+ get reset-corrected; deltas are summed). RATE divides by the bucket length
+ in seconds.
+ """
+
+ RATE = "rate", "rate"
+ INCREASE = "increase", "increase"
diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.py
index af9321158afe..441ac5a0d795 100644
--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py
+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py
@@ -37,7 +37,13 @@ from products.metrics.backend.facade.contracts import (
MetricQueryClause,
MetricQueryRequest,
)
-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType
+from products.metrics.backend.facade.enums import (
+ AttributeScope,
+ FilterOp,
+ MetricAggregation,
+ MetricRangeFunction,
+ MetricType,
+)
if TYPE_CHECKING:
from posthog.models import User
@@ -112,7 +118,8 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):
MetricQueryClause(
name=clause.name,
metric_name=clause.metricName,
- aggregation=MetricAggregation(clause.aggregation.value),
+ aggregation=MetricAggregation(clause.aggregation.value if clause.aggregation else "none"),
+ range_function=MetricRangeFunction(clause.rangeFunction.value) if clause.rangeFunction else None,
metric_type=MetricType(clause.metricType.value) if clause.metricType is not None else None,
filters=tuple(
MetricFilter(
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 648884781db5..950d544e5cf6 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -32,6 +32,13 @@ _ALLOWED_ATTRIBUTE_SCOPES: frozenset[str] = frozenset({"resource", "attribute",
# Limit bucket rows. Raise an error instead of hiding recent buckets.
_ROW_LIMIT = 10000
+# A query without an aggregation returns one line per series. Cap the lines
+# so a high-cardinality metric cannot flood the chart or the cluster.
+MAX_RAW_SERIES = 100
+
+# Raw rows are one per (series, bucket), so the cap scales with the series cap.
+_RAW_ROW_LIMIT = MAX_RAW_SERIES * 1000
+
# A series record updates every 30 minutes. The one-hour buffer allows late updates.
_SERIES_LAST_SEEN_BUFFER = dt.timedelta(hours=1)
@@ -118,8 +125,7 @@ _ALLOWED_AGGREGATIONS: frozenset[str] = frozenset(
{"sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"}
)
-# These aggregations also read the predecessor lookback before `date_from`.
-_LOOKBACK_AGGREGATIONS: frozenset[str] = frozenset({"rate", "increase", "histogram_quantile"})
+_ALLOWED_RANGE_FUNCTIONS: frozenset[str] = frozenset({"rate", "increase"})
# Derive this from the contract enum to match ingestion values.
_ALLOWED_METRIC_TYPES: frozenset[str] = frozenset(t.value for t in MetricType)
@@ -152,7 +158,7 @@ def _histogram_quantile(quantile: float, bounds: list[float], counts: list[float
_TARGET_BUCKET_COUNT = 60
# Upper bound on buckets in one query. A finer interval is coarsened to stay under it.
-_MAX_BUCKET_COUNT = 10000
+_MAX_BUCKET_COUNT = 500
# List intervals from finest to coarsest.
_INTERVAL_LADDER: list[tuple[str, dt.timedelta, ast.Call]] = [
@@ -368,31 +374,48 @@ def _active_since_expr(date_from: dt.datetime | None) -> ast.Expr:
def series_scope_expr(
- metric_name: str, filters: Sequence[MetricFilter], date_from: dt.datetime | None = None
+ metric_name: str,
+ filters: Sequence[MetricFilter],
+ date_from: dt.datetime | None = None,
+ *,
+ metric_type: str | None = None,
+ limit: int | None = None,
) -> ast.Expr:
"""Limit `metrics` rows to series that match label filters.
Labels are in `metric_series`, so filters select matching fingerprints.
Without filters, points with missing series rows still count.
+
+ `limit` keeps only that many series, the most recently seen first. It
+ always reads `metric_series`, so a series without a row there is dropped.
"""
- if not filters:
+ if not filters and limit is None:
return ast.Constant(value=True)
- return parse_expr(
+ query = parse_select(
"""
- series_fingerprint IN (
- SELECT series_fingerprint
- FROM posthog.metric_series
- WHERE metric_name = {metric_name}
- AND {active_since}
- AND {filters}
- )
+ SELECT series_fingerprint
+ FROM posthog.metric_series
+ WHERE metric_name = {metric_name}
+ AND {active_since}
+ AND {filters}
+ AND {metric_type}
+ GROUP BY series_fingerprint
""",
placeholders={
"metric_name": ast.Constant(value=metric_name),
"active_since": _active_since_expr(date_from),
"filters": filters_expr(filters),
+ "metric_type": type_filter_expr(metric_type),
},
)
+ assert isinstance(query, ast.SelectQuery)
+ if limit is not None:
+ query.order_by = [
+ ast.OrderExpr(expr=parse_expr("max(last_seen)"), order="DESC"),
+ ast.OrderExpr(expr=ast.Field(chain=["series_fingerprint"]), order="ASC"),
+ ]
+ query.limit = ast.Constant(value=limit)
+ return ast.CompareOperation(op=ast.CompareOperationOp.In, left=ast.Field(chain=["series_fingerprint"]), right=query)
def series_labels_query(metric_name: str, date_from: dt.datetime | None = None) -> ast.SelectQuery:
@@ -453,7 +476,7 @@ class MetricQueryRunner:
self,
team: Team,
metric_name: str,
- aggregation: str,
+ aggregation: str | None,
date_from: dt.datetime,
date_to: dt.datetime,
filters: Sequence[MetricFilter] = (),
@@ -461,9 +484,24 @@ class MetricQueryRunner:
interval: str | None = None,
quantile: float | None = None,
metric_type: str | None = None,
+ range_function: str | None = None,
) -> None:
- if aggregation not in _ALLOWED_AGGREGATIONS:
+ """`aggregation=None` returns one row per series and bucket, for at most `MAX_RAW_SERIES` series.
+
+ The legacy `rate` and `increase` aggregations mean a range function with a sum across series.
+ """
+ if aggregation in _ALLOWED_RANGE_FUNCTIONS:
+ if range_function is not None:
+ raise ValueError("range_function cannot combine with the rate or increase aggregation")
+ aggregation, range_function = "sum", aggregation
+ if aggregation is not None and aggregation not in _ALLOWED_AGGREGATIONS:
raise ValueError(f"Unsupported aggregation: {aggregation!r}")
+ if range_function is not None and range_function not in _ALLOWED_RANGE_FUNCTIONS:
+ raise ValueError(f"Unsupported range function: {range_function!r}")
+ if aggregation is None and group_by:
+ raise ValueError("group_by needs an aggregation; without one every series stays separate")
+ if aggregation == "histogram_quantile" and range_function is not None:
+ raise ValueError("histogram_quantile cannot combine with a range function")
if metric_type is not None and metric_type not in _ALLOWED_METRIC_TYPES:
raise ValueError(f"Unknown metric_type: {metric_type!r}")
if date_to <= date_from:
@@ -477,6 +515,7 @@ class MetricQueryRunner:
self.team = team
self.metric_name = metric_name
self.aggregation = aggregation
+ self.range_function = range_function
self.interval = _resolve_interval(date_from, date_to, interval)
# Start at the bucket boundary so the first bucket is complete.
self.date_from = _align_to_interval(date_from, self.interval, tzinfo=team.timezone_info)
@@ -489,7 +528,7 @@ class MetricQueryRunner:
@property
def scan_from(self) -> dt.datetime:
"""The earliest point time that the query reads, including the predecessor lookback."""
- if self.aggregation in _LOOKBACK_AGGREGATIONS:
+ if self.range_function is not None or self.aggregation == "histogram_quantile":
return self.date_from - counter_lookback(self.interval)
return self.date_from
@@ -501,7 +540,7 @@ class MetricQueryRunner:
honestly even when the bucket merged several series."""
if self.aggregation == "histogram_quantile":
return self._run_histogram_quantile()
- if self.aggregation in ("rate", "increase"):
+ if self.range_function is not None:
query = self._build_counter_query()
else:
query = self._build_simple_query()
@@ -528,6 +567,10 @@ class MetricQueryRunner:
)
return rows
+ @property
+ def _row_limit(self) -> int:
+ return _RAW_ROW_LIMIT if self.aggregation is None else _ROW_LIMIT
+
def _run_histogram_quantile(self) -> list[dict[str, Any]]:
"""Calculate quantiles from the distributions that ClickHouse sums."""
assert self.quantile is not None
@@ -568,10 +611,10 @@ class MetricQueryRunner:
def _raise_on_truncation(self, results: list[Any]) -> None:
"""Raise an error when the row limit drops recent buckets."""
- if len(results) >= _ROW_LIMIT:
+ if len(results) >= self._row_limit:
raise ValueError(
- "query produced too many (time bucket, group) rows; "
- "use a coarser interval, a narrower range, or a lower-cardinality group_by"
+ "query produced too many (time bucket, series) rows; "
+ "use a coarser interval, a narrower range, an aggregation, or a lower-cardinality group_by"
)
def _splice_group_columns(self, query: ast.SelectQuery) -> None:
@@ -603,6 +646,14 @@ class MetricQueryRunner:
return type_filter_expr(self.metric_type)
def _series_scope_expr(self) -> ast.Expr:
+ if self.aggregation is None:
+ return series_scope_expr(
+ self.metric_name,
+ self.filters,
+ self.date_from,
+ metric_type=self.metric_type,
+ limit=MAX_RAW_SERIES,
+ )
return series_scope_expr(self.metric_name, self.filters, self.date_from)
def _points_query(self, columns: Sequence[str], point_filters: Sequence[ast.Expr] = ()) -> ast.SelectQuery:
@@ -617,42 +668,70 @@ class MetricQueryRunner:
point_filters=point_filters,
)
+ def _combine_series(self, per_series: ast.SelectQuery) -> ast.SelectQuery:
+ """Combine the per-series query, whose rows are `(time, series_fingerprint, series_value)`.
+
+ Without an aggregation, each row stays a separate point of one series.
+ Group-by joins labels by fingerprint after the combine.
+ """
+ if self.aggregation is None:
+ query = parse_select(
+ """
+ SELECT
+ time AS time,
+ series_value AS value,
+ array(s.series_fingerprint) AS series_fingerprints
+ FROM (SELECT 1) AS s
+ ORDER BY time ASC, s.series_fingerprint ASC
+ LIMIT {row_limit}
+ """,
+ placeholders={"row_limit": ast.Constant(value=self._row_limit)},
+ )
+ else:
+ query = parse_select(
+ """
+ SELECT
+ time AS time,
+ {aggregation} AS value,
+ groupUniqArray(s.series_fingerprint) AS series_fingerprints
+ FROM (SELECT 1) AS s
+ GROUP BY time
+ ORDER BY time ASC
+ LIMIT {row_limit}
+ """,
+ placeholders={
+ "aggregation": _aggregation_expr(self.aggregation, ast.Field(chain=["series_value"])),
+ "row_limit": ast.Constant(value=self._row_limit),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery) and query.select_from is not None
+ query.select_from.table = per_series
+ self._splice_group_columns(query)
+ return query
+
def _build_simple_query(self) -> ast.SelectQuery:
- """Build sum, average, count, and p95 queries.
+ """Build queries over each series' last value per bucket.
Reduce each series to its last value per bucket before aggregation.
- Group-by joins labels by fingerprint after reduction.
"""
# `metrics` is registered only in the `posthog.` HogQL namespace.
- query = parse_select(
+ per_series = parse_select(
"""
SELECT
- time AS time,
- {aggregation} AS value,
- groupUniqArray(s.series_fingerprint) AS series_fingerprints
- FROM (
- SELECT
- toStartOfInterval(timestamp, {interval}) AS time,
- series_fingerprint AS series_fingerprint,
- argMax(value, timestamp) AS series_value
- FROM {points}
- GROUP BY time, {series_key}
- ) AS s
- GROUP BY time
- ORDER BY time ASC
- LIMIT {row_limit}
+ toStartOfInterval(timestamp, {interval}) AS time,
+ series_fingerprint AS series_fingerprint,
+ argMax(value, timestamp) AS series_value
+ FROM {points}
+ GROUP BY time, {series_key}
""",
placeholders={
"interval": _interval_expr(self.interval),
- "aggregation": _aggregation_expr(self.aggregation, ast.Field(chain=["series_value"])),
"points": self._points_query(("timestamp", "series_fingerprint", "value")),
"series_key": _series_key_expr(),
- "row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
- assert isinstance(query, ast.SelectQuery)
- self._splice_group_columns(query)
- return query
+ assert isinstance(per_series, ast.SelectQuery)
+ return self._combine_series(per_series)
def _build_counter_query(self) -> ast.SelectQuery:
"""Build rate and increase queries from per-series deltas.
@@ -662,13 +741,13 @@ class MetricQueryRunner:
provides a predecessor before the requested range.
"""
step_seconds = _interval_step(self.interval).total_seconds()
- divisor = step_seconds if self.aggregation == "rate" else 1.0
- query = parse_select(
+ divisor = step_seconds if self.range_function == "rate" else 1.0
+ per_series = parse_select(
"""
SELECT
toStartOfInterval(sample_timestamp, {interval}) AS time,
- sum(contribution) / {divisor} AS value,
- groupUniqArray(s.series_fingerprint) AS series_fingerprints
+ series_fingerprint AS series_fingerprint,
+ sum(contribution) / {divisor} AS series_value
FROM (
SELECT
timestamp AS sample_timestamp,
@@ -692,12 +771,10 @@ class MetricQueryRunner:
) AS prev_value
FROM {points}
)
- ) AS s
+ )
WHERE sample_timestamp >= {date_from}
- GROUP BY time
- HAVING isNotNull(value)
- ORDER BY time ASC
- LIMIT {row_limit}
+ GROUP BY time, series_fingerprint
+ HAVING isNotNull(series_value)
""",
placeholders={
"interval": _interval_expr(self.interval),
@@ -705,12 +782,10 @@ class MetricQueryRunner:
"series_key": _series_key_expr(),
"points": self._points_query(("timestamp", "series_fingerprint", "value", "aggregation_temporality")),
"date_from": ast.Constant(value=self.date_from),
- "row_limit": ast.Constant(value=_ROW_LIMIT),
},
)
- assert isinstance(query, ast.SelectQuery)
- self._splice_group_columns(query)
- return query
+ assert isinstance(per_series, ast.SelectQuery)
+ return self._combine_series(per_series)
def _build_histogram_query(self) -> ast.SelectQuery:
"""Build histogram distributions with rate and increase semantics."""
diff --git a/products/metrics/backend/metric_samples_query_runner.py b/products/metrics/backend/metric_samples_query_runner.py
index cda088ee86b4..8011adc9e7bc 100644
--- a/products/metrics/backend/metric_samples_query_runner.py
+++ b/products/metrics/backend/metric_samples_query_runner.py
@@ -25,7 +25,7 @@ def build_metric_query_runner(
*,
team: Team,
metric_name: str,
- aggregation: str,
+ aggregation: str | None,
date_from: dt.datetime,
date_to: dt.datetime,
filters: Sequence[MetricFilter] = (),
@@ -33,6 +33,7 @@ def build_metric_query_runner(
interval: str | None = None,
quantile: float | None = None,
metric_type: str | None = None,
+ range_function: str | None = None,
) -> MetricQueryRunner:
"""Return the runner for the table that holds all points of the range."""
runner = MetricQueryRunner(
@@ -46,6 +47,7 @@ def build_metric_query_runner(
interval=interval,
quantile=quantile,
metric_type=metric_type,
+ range_function=range_function,
)
if not reads_metrics4_only(runner.scan_from):
return runner
@@ -60,4 +62,5 @@ def build_metric_query_runner(
interval=interval,
quantile=quantile,
metric_type=metric_type,
+ range_function=range_function,
)
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index a80f147bee3c..3a923cc4431f 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -48,7 +48,13 @@ from products.metrics.backend.facade.contracts import (
MetricQueryClause,
MetricQueryRequest,
)
-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType
+from products.metrics.backend.facade.enums import (
+ AttributeScope,
+ FilterOp,
+ MetricAggregation,
+ MetricRangeFunction,
+ MetricType,
+)
__all__ = ["MetricsViewSet"]
@@ -59,6 +65,19 @@ class MetricAttributeScope(models.TextChoices):
AUTO = "auto", "auto"
+class MetricQueryAggregation(models.TextChoices):
+ NONE = "none", "none"
+ SUM = "sum", "sum"
+ AVG = "avg", "avg"
+ COUNT = "count", "count"
+ MIN = "min", "min"
+ MAX = "max", "max"
+ P95 = "p95", "p95"
+ RATE = "rate", "rate"
+ INCREASE = "increase", "increase"
+ HISTOGRAM_QUANTILE = "histogram_quantile", "histogram_quantile"
+
+
class Op(models.TextChoices):
EQ = "eq", "eq"
NEQ = "neq", "neq"
@@ -116,10 +135,16 @@ class _MetricClauseSerializer(serializers.Serializer):
help_text="Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.",
)
aggregation = serializers.ChoiceField(
- choices=["sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"],
+ choices=MetricQueryAggregation.choices,
default="sum",
help_text="Aggregation applied per time bucket; same semantics as the top-level aggregation.",
)
+ rangeFunction = serializers.ChoiceField(
+ choices=MetricRangeFunction.choices,
+ required=False,
+ allow_null=True,
+ help_text="Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.",
+ )
quantile = serializers.FloatField(
required=False,
allow_null=True,
@@ -167,9 +192,15 @@ class _MetricQueryBodySerializer(serializers.Serializer):
help_text="Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.",
)
aggregation = serializers.ChoiceField(
- choices=["sum", "avg", "count", "min", "max", "p95", "rate", "increase", "histogram_quantile"],
+ choices=MetricQueryAggregation.choices,
default="sum",
- help_text="Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.",
+ help_text="Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'. 'none' skips the aggregation and returns one series per label set, at most 100, using each series' last sample per bucket; it cannot be combined with 'groupBy'.",
+ )
+ rangeFunction = serializers.ChoiceField(
+ choices=MetricRangeFunction.choices,
+ required=False,
+ allow_null=True,
+ help_text="Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.",
)
quantile = serializers.FloatField(
required=False,
@@ -249,12 +280,14 @@ def _build_clause(data: dict, *, name: str) -> MetricQueryClause:
aggregation = MetricAggregation(aggregation_raw)
metric_type_raw = data.get("metricType")
+ range_function_raw = data.get("rangeFunction")
return MetricQueryClause(
name=name,
metric_name=data["metricName"],
aggregation=aggregation,
quantile=quantile,
metric_type=MetricType(metric_type_raw) if metric_type_raw else None,
+ range_function=MetricRangeFunction(range_function_raw) if range_function_raw else None,
filters=tuple(
MetricFilter(key=f["key"], op=FilterOp(f["op"]), value=f["value"], scope=AttributeScope(f["scope"]))
for f in data.get("filters") or []
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index e81d28832115..6fa41a41cfee 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -19,7 +19,7 @@ from posthog.clickhouse.client.connection import Workload
from products.metrics.backend.facade.api import run_metric_query
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
-from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricRangeFunction
from products.metrics.backend.metric_query_runner import (
_INTERVAL_LADDER,
MetricQueryRunner,
@@ -103,9 +103,10 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("too_fine_is_coarsened", dt.timedelta(days=2), "second_15", "second_30"),
+ ("too_fine_is_coarsened", dt.timedelta(days=2), "second_15", "minute_15"),
("fitting_interval_is_kept", dt.timedelta(hours=2), "second_15", "second_15"),
- ("fifteen_seconds", dt.timedelta(hours=6), "second_15", "second_15"),
+ ("limit_is_kept", dt.timedelta(minutes=125), "second_15", "second_15"),
+ ("six_hours_is_coarsened", dt.timedelta(hours=6), "second_15", "minute"),
("thirty_minutes", dt.timedelta(days=2), "minute_30", "minute_30"),
]
)
@@ -1824,6 +1825,91 @@ class TestRateIncreaseOnSamples(TestRateIncrease):
runner_class = MetricSamplesQueryRunner
+class TestUnaggregatedSeries(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ truncate_metrics_tables()
+ self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
+
+ def _seed_pod(self, pod: str, points, metric_name: str = "requests_total") -> None:
+ seed_metric(
+ team_id=self.team.id,
+ metric_name=metric_name,
+ metric_type="sum",
+ is_monotonic=True,
+ points=points,
+ resource_labels={"k8s.pod.name": pod},
+ labels={"env": "prod"},
+ )
+
+ def _run(self, **clause_overrides):
+ clause: dict[str, Any] = {
+ "name": "a",
+ "metric_name": "requests_total",
+ "aggregation": MetricAggregation.NONE,
+ }
+ clause.update(clause_overrides)
+ return run_metric_query(
+ team=self.team,
+ request=MetricQueryRequest(
+ clauses=(MetricQueryClause(**clause),),
+ date_from=self.anchor - dt.timedelta(minutes=1),
+ date_to=self.anchor + dt.timedelta(minutes=2),
+ interval="minute",
+ ),
+ )
+
+ def test_one_series_per_physical_series_keeping_only_distinguishing_labels(self):
+ self._seed_pod("web-1", [(self.anchor + dt.timedelta(seconds=10), 5.0)])
+ self._seed_pod("web-2", [(self.anchor + dt.timedelta(seconds=10), 7.0)])
+
+ series = self._run()
+
+ self.assertEqual({s.labels["k8s.pod.name"] for s in series}, {"web-1", "web-2"})
+ self.assertTrue(all("env" not in s.labels for s in series))
+ self.assertEqual(
+ {s.labels["k8s.pod.name"]: [p.value for p in s.points][-1] for s in series},
+ {"web-1": 5.0, "web-2": 7.0},
+ )
+
+ def test_keeps_the_most_recently_reporting_series_when_over_the_cap(self):
+ for index in range(4):
+ self._seed_pod(f"web-{index}", [(self.anchor + dt.timedelta(seconds=index * 10), 1.0)])
+
+ with patch("products.metrics.backend.metric_query_runner.MAX_RAW_SERIES", 2):
+ series = self._run()
+
+ self.assertEqual({s.labels["k8s.pod.name"] for s in series}, {"web-2", "web-3"})
+
+ def test_rate_function_runs_per_series_and_sums_like_the_legacy_rate(self):
+ for pod, last in (("web-1", 60.0), ("web-2", 6.0)):
+ self._seed_pod(
+ pod,
+ [(self.anchor + dt.timedelta(seconds=0), 0.0), (self.anchor + dt.timedelta(seconds=30), last)],
+ )
+
+ per_series = self._run(range_function=MetricRangeFunction.RATE)
+ summed = self._run(aggregation=MetricAggregation.SUM, range_function=MetricRangeFunction.RATE)
+ legacy = self._run(aggregation=MetricAggregation.RATE)
+
+ self.assertEqual(
+ {s.labels["k8s.pod.name"]: [p.value for p in s.points][-1] for s in per_series},
+ {"web-1": 1.0, "web-2": 0.1},
+ )
+ self.assertEqual([p.value for p in summed[0].points], [p.value for p in legacy[0].points])
+
+ def test_rejects_group_by_without_an_aggregation(self):
+ with self.assertRaises(ValueError):
+ MetricQueryClause(
+ name="a",
+ metric_name="requests_total",
+ aggregation=MetricAggregation.NONE,
+ group_by=(MetricGroupBy(key="env"),),
+ )
+
+
class TestBuildMetricQueryRunner(APIBaseTest):
@parameterized.expand(
[
diff --git a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py b/products/metrics/backend/tests/test_metrics_histogram_query_runner.py
index 2170a7808ff1..caa5562145f7 100644
--- a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_histogram_query_runner.py
@@ -167,9 +167,9 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):
},
interval="minute",
)
- # One-minute buckets over 30 days exceed the bucket limit, so the runner uses five-minute buckets.
+ # One-minute buckets over 30 days exceed the bucket limit, so the runner uses six-hour buckets.
first, second = (dt.datetime.fromisoformat(t) for t in response.times[:2])
- self.assertEqual(second - first, dt.timedelta(minutes=5))
+ self.assertEqual(second - first, dt.timedelta(hours=6))
def test_invalid_range_surfaces_as_client_error_not_500(self):
with self.assertRaises(ExposedHogQLError):
diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsx
index b57390078941..9d158d7caa9e 100644
--- a/products/metrics/frontend/MetricsScene.tsx
+++ b/products/metrics/frontend/MetricsScene.tsx
@@ -16,8 +16,6 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { metricNamePickerLogic } from './components/metricNamePickerLogic'
-import { MetricsCatalog } from './components/MetricsCatalog'
-import { metricsCatalogLogic } from './components/metricsCatalogLogic'
import { MetricsOverview } from './components/MetricsOverview'
import { MetricsSqlEditor } from './components/MetricsSqlEditor'
import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'
@@ -32,7 +30,6 @@ const METRICS_FEEDBACK_SURVEY_ID = '01a07c35-6be3-0000-16b3-4cd66a6873f3'
const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[] = [
{ key: 'overview', label: 'Overview', 'data-attr': 'metrics-scene-tab-overview' },
- { 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' },
]
@@ -67,7 +64,6 @@ const MetricsSceneContent = (): JSX.Element => {
)
const tabDisabledReasons: Record<MetricsSceneActiveTab, string | null> = {
overview: metricsViewerDisabledReason,
- explore: metricsViewerDisabledReason,
viewer: metricsViewerDisabledReason,
sql: metricsSqlDisabledReason,
}
@@ -81,9 +77,6 @@ const MetricsSceneContent = (): JSX.Element => {
useOnMountEffect(() => {
primeItems()
})
- // 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)
const onFeedbackClick = (): void => {
posthog.displaySurvey(METRICS_FEEDBACK_SURVEY_ID)
@@ -129,7 +122,6 @@ const MetricsSceneContent = (): JSX.Element => {
/>
<div className="flex flex-col gap-2 py-2 flex-1 min-h-0">
{activeTab === 'overview' && <MetricsOverview />}
- {activeTab === 'explore' && <MetricsCatalog />}
{activeTab === 'viewer' && <MetricsViewer />}
{activeTab === 'sql' && <MetricsSqlEditor />}
</div>
diff --git a/products/metrics/frontend/components/MetricNameFilter.tsx b/products/metrics/frontend/components/MetricNameFilter.tsx
index b74fa14b7ee5..0ba4d63c3096 100644
--- a/products/metrics/frontend/components/MetricNameFilter.tsx
+++ b/products/metrics/frontend/components/MetricNameFilter.tsx
@@ -7,12 +7,12 @@ import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'
import { metricNamePickerLogic } from './metricNamePickerLogic'
-const ROW_HEIGHT = 44
+const ROW_HEIGHT = 32
const MAX_DROPDOWN_HEIGHT = 320
const DROPDOWN_WIDTH = 320
interface OptionRowData {
- items: { name: string; metric_type: string }[]
+ items: { name: string }[]
selected: string
onPick: (name: string) => void
}
@@ -39,10 +39,7 @@ function MetricOptionRow({
onClick={() => onPick(item.name)}
data-attr={`metrics-name-option-${item.name}`}
>
- <div className="min-w-0 flex flex-col items-start gap-0.5 py-0.5">
- <span className="truncate">{item.name}</span>
- {item.metric_type && <span className="text-xs text-muted">{item.metric_type}</span>}
- </div>
+ <span className="truncate">{item.name}</span>
</LemonButton>
</div>
)
@@ -91,9 +88,15 @@ function MetricNameFilterInner({
disabled?: boolean
disabledReason?: string | null
}): JSX.Element {
- const { items, itemsLoading, search } = useValues(metricNamePickerLogic)
+ const { items: pickerItems, itemsLoading, search } = useValues(metricNamePickerLogic)
const { setSearch } = useActions(metricNamePickerLogic)
+ // The list holds one entry per name and type, and the type is not shown.
+ const items = useMemo(
+ () => pickerItems.filter((item, index) => pickerItems.findIndex((other) => other.name === item.name) === index),
+ [pickerItems]
+ )
+
const onPick = useCallback(
(name: string) => {
// Single-select: replace on pick. Comparing several metrics is done with
@@ -110,9 +113,7 @@ function MetricNameFilterInner({
return Math.min(height, MAX_DROPDOWN_HEIGHT)
}, [items.length])
- const selectedType = useMemo(() => items.find((item) => item.name === value)?.metric_type, [items, value])
-
- const triggerLabel = !value ? placeholder : selectedType ? `${value} (${selectedType})` : value
+ const triggerLabel = value || placeholder
return (
<LemonDropdown
diff --git a/products/metrics/frontend/components/MetricsCatalog.stories.tsx b/products/metrics/frontend/components/MetricsCatalog.stories.tsx
deleted file mode 100644
index a3208778b0d0..000000000000
--- a/products/metrics/frontend/components/MetricsCatalog.stories.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import { mswDecorator } from '~/mocks/browser'
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
-
-import type { _MetricCatalogValuesParamsApi } from '../generated/api.schemas'
-import { MetricsCatalog } from './MetricsCatalog'
-
-const items = Array.from({ length: 40 }, (_, index) => ({
- name: `example.queue.${index}`,
- metric_type: 'gauge',
-}))
-
-const meta: Meta<typeof MetricsCatalog> = {
- title: 'Metrics/MetricsCatalog',
- component: MetricsCatalog,
- beforeEach: () => {
- const context = window.POSTHOG_APP_CONTEXT!
- const previous = context.resource_access_control
- context.resource_access_control = {
- ...previous,
- [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
- }
- return () => {
- context.resource_access_control = previous
- }
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/metrics/names/': { results: items },
- },
- post: {
- '/api/projects/:team_id/metrics/values/': async ({ request }) => {
- const { names } = (await request.json()) as _MetricCatalogValuesParamsApi
- return [
- 200,
- {
- results: names.map((name) => ({
- name,
- metric_type: 'gauge',
- sparkline: [4, 6, 3, 7, 9, 5, 8, 4, 7, 10, 6, 9, 8, 5, 7, 11, 6, 8, 10, 7, 9, 6, 8, 12],
- })),
- },
- ]
- },
- },
- }),
- ],
- parameters: {
- testOptions: {
- snapshotBrowsers: ['chromium'],
- waitForLoadersToDisappear: false,
- waitForSelector: 'canvas[aria-label]',
- },
- },
- render: () => (
- <div className="h-[600px] w-[1200px] max-w-full overflow-auto">
- <MetricsCatalog />
- </div>
- ),
-}
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Default: Story = {}
-
-export const Narrow: Story = {
- decorators: [
- (Story) => (
- <div className="w-[520px]">
- <Story />
- </div>
- ),
- ],
-}
diff --git a/products/metrics/frontend/components/MetricsCatalog.test.tsx b/products/metrics/frontend/components/MetricsCatalog.test.tsx
deleted file mode 100644
index acebe534bbd5..000000000000
--- a/products/metrics/frontend/components/MetricsCatalog.test.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import '@testing-library/jest-dom'
-
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
-import { Provider } from 'kea'
-
-import { initKeaTests } from '~/test/init'
-import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
-
-import { metricsNamesRetrieve, metricsValuesCreate } from '../generated/api'
-import { MetricsCatalog } from './MetricsCatalog'
-
-jest.mock('../generated/api', () => ({
- ...jest.requireActual('../generated/api'),
- metricsNamesRetrieve: jest.fn(),
- metricsValuesCreate: jest.fn(),
- metricsQueryCreate: jest.fn(),
-}))
-
-const CATALOG_ITEMS = [
- { name: 'http.server.duration', metric_type: 'histogram' },
- { name: 'queue.depth', metric_type: 'gauge' },
-]
-
-// Stands in for the browser's observer so a test can say which cards are in view.
-class FakeIntersectionObserver {
- static observers: { callback: IntersectionObserverCallback; elements: Element[] }[] = []
- private entry: { callback: IntersectionObserverCallback; elements: Element[] }
-
- constructor(callback: IntersectionObserverCallback) {
- this.entry = { callback, elements: [] }
- FakeIntersectionObserver.observers.push(this.entry)
- }
-
- observe(element: Element): void {
- this.entry.elements.push(element)
- }
-
- disconnect(): void {
- this.entry.elements = []
- }
-
- unobserve(): void {}
-}
-
-const scrollIntoView = (testId: string): void => {
- for (const observer of FakeIntersectionObserver.observers) {
- for (const element of observer.elements) {
- if (element.getAttribute('data-attr') === testId) {
- observer.callback([{ isIntersecting: true, target: element } as IntersectionObserverEntry], null as any)
- }
- }
- }
-}
-
-describe('MetricsCatalog', () => {
- beforeEach(() => {
- window.POSTHOG_APP_CONTEXT = {
- ...window.POSTHOG_APP_CONTEXT,
- resource_access_control: {
- ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
- [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
- },
- } as AppContext
- initKeaTests()
- FakeIntersectionObserver.observers = []
- window.IntersectionObserver = FakeIntersectionObserver as unknown as typeof IntersectionObserver
- jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)
- jest.mocked(metricsValuesCreate).mockReset()
- jest.mocked(metricsValuesCreate).mockResolvedValue({ results: [] } as any)
- })
-
- afterEach(() => cleanup())
-
- it('requests a card sparkline only once that card scrolls into view', async () => {
- render(
- <Provider>
- <MetricsCatalog />
- </Provider>
- )
- expect(await screen.findByText('queue.depth')).toBeInTheDocument()
- expect(metricsValuesCreate).not.toHaveBeenCalled()
-
- await act(async () => {
- scrollIntoView('metrics-catalog-card-queue.depth')
- })
-
- await waitFor(() => expect(metricsValuesCreate).toHaveBeenCalledTimes(1))
- expect(metricsValuesCreate).toHaveBeenCalledWith(expect.any(String), { names: ['queue.depth'] })
- })
-
- it('batches cards that enter view together', async () => {
- render(
- <Provider>
- <MetricsCatalog />
- </Provider>
- )
- expect(await screen.findByText('queue.depth')).toBeInTheDocument()
-
- await act(async () => {
- scrollIntoView('metrics-catalog-card-http.server.duration')
- scrollIntoView('metrics-catalog-card-queue.depth')
- })
-
- await waitFor(() => expect(metricsValuesCreate).toHaveBeenCalledTimes(1))
- expect(metricsValuesCreate).toHaveBeenCalledWith(expect.any(String), {
- names: ['http.server.duration', 'queue.depth'],
- })
- })
-})
diff --git a/products/metrics/frontend/components/MetricsCatalog.tsx b/products/metrics/frontend/components/MetricsCatalog.tsx
deleted file mode 100644
index ef50a32e083e..000000000000
--- a/products/metrics/frontend/components/MetricsCatalog.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { useActions, useMountedLogic, useValues } from 'kea'
-import { useEffect, useRef } from 'react'
-
-import { IconSearch } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
-
-import { Sparkline } from 'lib/components/Sparkline'
-import { TZLabel } from 'lib/components/TZLabel'
-
-import { metricNamePickerLogic } from './metricNamePickerLogic'
-import { MetricCatalogItem, metricsCatalogLogic } from './metricsCatalogLogic'
-
-// A metric's OTel type says how to read it before it is opened. The one-liner is
-// the catalog's main teaching surface: it turns a bare name into a sentence the
-// reader can scan, and it matches the recommended aggregation the viewer applies.
-const describeMetric = (item: MetricCatalogItem, unit?: string): string => {
- const unitLabel = unit ? ` (${unit})` : ''
- switch (item.metric_type) {
- case 'gauge':
- return `A current level, read at each scrape${unitLabel}.`
- case 'sum':
- return `A running total that grows over time${unitLabel}.`
- case 'histogram':
- case 'exponential_histogram':
- return `A distribution of values; chart a percentile${unitLabel}.`
- case 'summary':
- return `A distribution with precomputed percentiles${unitLabel}.`
- default:
- return `A metric${unitLabel}.`
- }
-}
-
-const typeTagLabel = (metricType: string): string =>
- metricType === 'sum' ? 'counter' : metricType === 'exponential_histogram' ? 'histogram' : metricType || 'unknown'
-
-const CatalogCard = ({ item }: { item: MetricCatalogItem }): JSX.Element => {
- const { openMetric, loadSparkline, retrySparkline } = useActions(metricsCatalogLogic)
- const { catalogItemDetails, catalogItemDetailsFailed, catalogItemDetailsLoading, catalogItemsLoading } =
- useValues(metricsCatalogLogic)
- const cardRef = useRef<HTMLButtonElement>(null)
- const detail = catalogItemDetails[item.name]
- const failed = catalogItemDetailsFailed[item.name]
- const loading = catalogItemDetailsLoading[item.name]
-
- useEffect(() => {
- const card = cardRef.current
- if (!card || detail || failed || loading || catalogItemsLoading) {
- return
- }
- // Browsers without IntersectionObserver still show a useful catalog;
- // they fall back to loading the card when it mounts.
- if (!window.IntersectionObserver) {
- loadSparkline(item)
- return
- }
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (entry?.isIntersecting) {
- loadSparkline(item)
- observer.disconnect()
- }
- },
- // Request just before the card enters view so the chart is normally
- // ready by the time a person reaches it.
- { rootMargin: '300px' }
- )
- observer.observe(card)
- return () => observer.disconnect()
- }, [catalogItemsLoading, detail, failed, item, loadSparkline, loading])
-
- return (
- <div className="relative border rounded bg-bg-3000 hover:border-accent-primary focus-within:border-accent-primary transition-colors">
- <button
- ref={cardRef}
- type="button"
- onClick={() => openMetric(item)}
- data-attr={`metrics-catalog-card-${item.name}`}
- aria-label={`Open ${item.name} chart`}
- className="absolute inset-0 rounded focus:outline-none"
- />
- <div className="relative z-10 flex flex-col gap-2 p-3 text-left pointer-events-none">
- <div className="flex items-start justify-between gap-2 min-w-0">
- <span className="font-mono text-sm truncate" title={item.name}>
- {item.name}
- </span>
- <span className="pointer-events-auto" onClick={(event) => event.stopPropagation()}>
- <Tooltip title={describeMetric(item, detail?.unit)} openOnClick>
- <LemonTag type="muted" size="small" forceClickable tabIndex={0}>
- {typeTagLabel(item.metric_type)}
- </LemonTag>
- </Tooltip>
- </span>
- </div>
- <div className="h-10 w-full">
- {detail?.sparkline && detail.sparkline.length > 1 ? (
- <Sparkline data={detail.sparkline} type="line" className="w-full h-full" />
- ) : loading || (!detail && !failed) ? (
- <LemonSkeleton className="h-full" />
- ) : failed ? (
- <div className="h-full flex items-center text-xs text-muted">Could not load recent data</div>
- ) : (
- <div className="h-full flex items-center text-xs text-muted">No recent data to draw</div>
- )}
- </div>
- {detail?.last_seen && (
- <span className="text-xs text-muted">
- Last seen <TZLabel time={detail.last_seen} />
- </span>
- )}
- </div>
- {failed && (
- <div className="relative z-10 px-3 pb-3">
- <LemonButton size="xsmall" type="secondary" onClick={() => retrySparkline(item)}>
- Retry
- </LemonButton>
- </div>
- )}
- </div>
- )
-}
-
-export const MetricsCatalog = (): JSX.Element => {
- // The catalog reads the picker's service scope, so mounting the picker keeps the
- // scope the overview/viewer set live and the cards consistent with the viewer.
- useMountedLogic(metricNamePickerLogic)
- const logic = useMountedLogic(metricsCatalogLogic)
- const { visibleItems, catalogItemsLoading, search } = useValues(logic)
- const { setSearch } = useActions(logic)
-
- return (
- <div className="@container flex flex-col gap-3 overflow-y-auto">
- <div className="flex justify-end">
- <LemonInput
- size="small"
- prefix={<IconSearch />}
- value={search}
- onChange={setSearch}
- placeholder="Filter metrics"
- data-attr="metrics-catalog-search"
- className="w-64"
- />
- </div>
- {catalogItemsLoading && visibleItems.length === 0 ? (
- <div className="grid grid-cols-1 @xl:grid-cols-2 @4xl:grid-cols-3 @6xl:grid-cols-4 gap-3">
- {Array.from({ length: 8 }).map((_, i) => (
- <LemonSkeleton key={i} className="h-32" />
- ))}
- </div>
- ) : visibleItems.length === 0 ? (
- <div className="border rounded p-6 text-center text-secondary">
- {search ? `No metrics match "${search}".` : 'No metrics reported in the current scope yet.'}
- </div>
- ) : (
- <div className="grid grid-cols-1 @xl:grid-cols-2 @4xl:grid-cols-3 @6xl:grid-cols-4 gap-3">
- {visibleItems.map((item) => (
- <CatalogCard key={item.name} item={item} />
- ))}
- </div>
- )}
- </div>
- )
-}
diff --git a/products/metrics/frontend/components/MetricsClauseRow.tsx b/products/metrics/frontend/components/MetricsClauseRow.tsx
index 606f1e9dc53d..72f9f8555662 100644
--- a/products/metrics/frontend/components/MetricsClauseRow.tsx
+++ b/products/metrics/frontend/components/MetricsClauseRow.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonMenu, LemonSelect, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonMenu, Tooltip } from '@posthog/lemon-ui'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
@@ -12,26 +12,10 @@ import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
import { MetricNameFilter } from './MetricNameFilter'
import { MetricsClauseFilterBar } from './MetricsClauseFilterBar'
import { MetricsGroupByButton } from './MetricsGroupByButton'
-import {
- MAX_CLAUSES,
- MetricAggregation,
- MetricsViewerClause,
- RECOMMENDED_AGGREGATION_BY_TYPE,
- metricsViewerLogic,
-} from './metricsViewerLogic'
+import { MetricsOperations } from './MetricsOperations'
+import { MAX_CLAUSES, MetricsViewerClause, metricsViewerLogic } from './metricsViewerLogic'
-const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
- { value: 'sum', label: 'Sum' },
- { value: 'avg', label: 'Average' },
- { value: 'count', label: 'Series count' },
- { value: 'min', label: 'Min' },
- { value: 'max', label: 'Max' },
- { value: 'p95', label: 'p95' },
- { value: 'rate', label: 'Rate (/s)' },
- { value: 'increase', label: 'Increase' },
-]
-
-/** One query line of the viewer: alias, metric picker, aggregation, filters, and group-by.
+/** One query line of the viewer: alias, metric picker, filters, operations, and group-by.
* Editing any control focuses the row — the samples panel, anomaly badge, and picker
* scoping follow the focused (active) clause. */
export function MetricsClauseRow({
@@ -53,6 +37,7 @@ export function MetricsClauseRow({
setActiveClauseIndex,
setMetricName,
setAggregation,
+ setRangeFunction,
setFilterGroup,
setGroupByKeys,
duplicateClause,
@@ -80,9 +65,6 @@ export function MetricsClauseRow({
setter(value)
}
- const recommendedAggregation = clause.selectedMetricType
- ? RECOMMENDED_AGGREGATION_BY_TYPE[clause.selectedMetricType]
- : undefined
return (
<div className="flex flex-wrap items-start gap-2" data-attr="metrics-clause-row">
{showAlias && (
@@ -104,33 +86,14 @@ export function MetricsClauseRow({
</LemonButton>
</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}
/>
- {clause.selectedMetricType &&
- recommendedAggregation &&
- (clause.aggregation !== recommendedAggregation ? (
- <span className="text-xs text-secondary">
- {clause.selectedMetricType}: {recommendedAggregation} recommended
- </span>
- ) : (
- <LemonTag type="muted" size="small" className="self-start">
- {clause.selectedMetricType} · {recommendedAggregation}
- </LemonTag>
- ))}
</div>
- <LemonSelect
- size="small"
- value={clause.aggregation}
- options={AGGREGATION_OPTIONS}
- onChange={withSelect(setAggregation)}
- data-attr="metrics-viewer-aggregation"
- disabledReason={disabledReason}
- />
<UniversalFilters
// Keyed by the stable alias — an index key would rebind another row's
// filter logic when a row above it is removed.
@@ -146,11 +109,19 @@ export function MetricsClauseRow({
>
<MetricsClauseFilterBar disabledReason={disabledReason} />
</UniversalFilters>
- <MetricsGroupByButton
- groupByKeys={clause.groupByKeys}
- onChange={withSelect(setGroupByKeys)}
+ <MetricsOperations
+ clause={clause}
+ onRangeFunctionChange={withSelect(setRangeFunction)}
+ onAggregationChange={withSelect(setAggregation)}
disabledReason={disabledReason}
/>
+ {clause.aggregation && (
+ <MetricsGroupByButton
+ groupByKeys={clause.groupByKeys}
+ onChange={withSelect(setGroupByKeys)}
+ disabledReason={disabledReason}
+ />
+ )}
<LemonMenu
items={[
{
diff --git a/products/metrics/frontend/components/MetricsOperations.tsx b/products/metrics/frontend/components/MetricsOperations.tsx
new file mode 100644
index 000000000000..d8b24088819f
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsOperations.tsx
@@ -0,0 +1,156 @@
+import { IconPlusSmall, IconX } from '@posthog/icons'
+import { LemonButton, LemonMenu, LemonMenuItem } from '@posthog/lemon-ui'
+
+import { MetricAggregation, MetricRangeFunction, MetricsViewerClause } from './metricsViewerLogic'
+
+interface OperationOption<T extends string> {
+ value: T
+ label: string
+ description: string
+}
+
+const RANGE_FUNCTION_OPTIONS: OperationOption<MetricRangeFunction>[] = [
+ {
+ value: 'rate',
+ label: 'Rate (/s)',
+ description: 'Per-second rate of increase of each series. Use it for counters.',
+ },
+ {
+ value: 'increase',
+ label: 'Increase',
+ description: 'Total increase of each series per time bucket. Use it for counters.',
+ },
+]
+
+const AGGREGATION_OPTIONS: OperationOption<MetricAggregation>[] = [
+ { value: 'sum', label: 'Sum', description: 'Add the series together.' },
+ { value: 'avg', label: 'Average', description: 'Average of the series.' },
+ { value: 'count', label: 'Series count', description: 'Number of series that reported.' },
+ { value: 'min', label: 'Min', description: 'Lowest value across the series.' },
+ { value: 'max', label: 'Max', description: 'Highest value across the series.' },
+ { value: 'p95', label: 'p95', description: '95th percentile across the series.' },
+]
+
+function operationMenuItems<T extends string>(
+ options: OperationOption<T>[],
+ current: T | null,
+ onPick: (value: T) => void
+): LemonMenuItem[] {
+ return options.map((option) => ({
+ label: option.label,
+ tooltip: option.description,
+ active: option.value === current,
+ onClick: () => onPick(option.value),
+ 'data-attr': `metrics-operation-option-${option.value}`,
+ }))
+}
+
+function OperationChip<T extends string>({
+ label,
+ options,
+ current,
+ onPick,
+ onRemove,
+ removeTooltip,
+ disabledReason,
+ dataAttr,
+}: {
+ label: string
+ options: OperationOption<T>[]
+ current: T
+ onPick: (value: T) => void
+ onRemove: () => void
+ removeTooltip: string
+ disabledReason: string | null
+ dataAttr: string
+}): JSX.Element {
+ return (
+ <LemonMenu items={operationMenuItems(options, current, onPick)}>
+ <LemonButton
+ size="small"
+ type="secondary"
+ active
+ disabledReason={disabledReason}
+ sideAction={{
+ icon: <IconX />,
+ onClick: onRemove,
+ tooltip: removeTooltip,
+ 'data-attr': `${dataAttr}-remove`,
+ }}
+ data-attr={dataAttr}
+ >
+ {label}
+ </LemonButton>
+ </LemonMenu>
+ )
+}
+
+/** The operations applied to a clause's series, in the order they run: a range function on each
+ * series first, then an aggregation across series. Mirrors the operation chips of a PromQL builder. */
+export function MetricsOperations({
+ clause,
+ onRangeFunctionChange,
+ onAggregationChange,
+ disabledReason,
+}: {
+ clause: Pick<MetricsViewerClause, 'rangeFunction' | 'aggregation'>
+ onRangeFunctionChange: (rangeFunction: MetricRangeFunction | null) => void
+ onAggregationChange: (aggregation: MetricAggregation | null) => void
+ disabledReason: string | null
+}): JSX.Element {
+ const { rangeFunction, aggregation } = clause
+ const rangeFunctionOption = RANGE_FUNCTION_OPTIONS.find((option) => option.value === rangeFunction)
+ const aggregationOption = AGGREGATION_OPTIONS.find((option) => option.value === aggregation)
+
+ return (
+ <div className="flex flex-wrap items-center gap-1" data-attr="metrics-operations">
+ {rangeFunctionOption && (
+ <OperationChip
+ label={rangeFunctionOption.label}
+ options={RANGE_FUNCTION_OPTIONS}
+ current={rangeFunctionOption.value}
+ onPick={onRangeFunctionChange}
+ onRemove={() => onRangeFunctionChange(null)}
+ removeTooltip="Remove range function"
+ disabledReason={disabledReason}
+ dataAttr="metrics-operation-range-function"
+ />
+ )}
+ {aggregationOption && (
+ <OperationChip
+ label={aggregationOption.label}
+ options={AGGREGATION_OPTIONS}
+ current={aggregationOption.value}
+ onPick={onAggregationChange}
+ onRemove={() => onAggregationChange(null)}
+ removeTooltip="Remove aggregation"
+ disabledReason={disabledReason}
+ dataAttr="metrics-operation-aggregation"
+ />
+ )}
+ <LemonMenu
+ items={[
+ {
+ title: 'Range functions',
+ items: operationMenuItems(RANGE_FUNCTION_OPTIONS, rangeFunction, onRangeFunctionChange),
+ },
+ {
+ title: 'Aggregations',
+ items: operationMenuItems(AGGREGATION_OPTIONS, aggregation, onAggregationChange),
+ },
+ ]}
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPlusSmall />}
+ disabledReason={disabledReason}
+ tooltip="Add an operation. Without an aggregation, each series gets its own line."
+ data-attr="metrics-operation-add"
+ >
+ Operation
+ </LemonButton>
+ </LemonMenu>
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx b/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx
index 2df8d5e02a45..73c701655691 100644
--- a/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx
+++ b/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx
@@ -25,7 +25,7 @@ export function MetricsStarterDashboardModal(): JSX.Element {
onClose={closeModal}
closable={!creating}
title="New service dashboard"
- description="One insight per metric, charted with its recommended aggregation."
+ description="One insight per metric, charted as one line per series."
footer={
<>
<LemonButton
@@ -81,7 +81,7 @@ export function MetricsStarterDashboardModal(): JSX.Element {
options={metricOptions.map((option) => ({
// Composite key: the same name can exist under two OTel types.
key: metricOptionKey(option.name, option.metric_type),
- label: `${option.name} (${option.metric_type})`,
+ label: option.name,
}))}
placeholder="Pick the metrics to chart"
data-attr="metrics-starter-dashboard-metrics"
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 85eeb55b2a4c..508c4cf3a844 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -45,7 +45,13 @@ import { MetricsSamplesPanel } from './MetricsSamplesPanel'
import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'
import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'
import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
-import { LIVE_REFRESH_MS, MAX_CLAUSES, metricsViewerLogic, sanitizeFormulaInput } from './metricsViewerLogic'
+import {
+ LIVE_REFRESH_MS,
+ MAX_CLAUSES,
+ MAX_UNAGGREGATED_SERIES,
+ metricsViewerLogic,
+ sanitizeFormulaInput,
+} from './metricsViewerLogic'
const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']
const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table', 'heatmap']
@@ -111,6 +117,7 @@ export const MetricsViewer = (): JSX.Element => {
isAddToDashboardModalOpen,
hasMetricName,
hasResults,
+ seriesCapReached,
displayType,
metricsDisplay,
heatmapEligible,
@@ -381,7 +388,7 @@ export const MetricsViewer = (): JSX.Element => {
size="small"
type="secondary"
onClick={openStarterDashboardModal}
- tooltip="Create a dashboard with one insight per metric, using each metric's recommended aggregation"
+ tooltip="Create a dashboard with one insight per metric, charted as one line per series"
data-attr="metrics-viewer-starter-dashboard"
disabledReason={insightEditorDisabledReason}
>
@@ -407,6 +414,12 @@ export const MetricsViewer = (): JSX.Element => {
)}
<div className="flex flex-col xl:flex-row gap-3 items-stretch">
<div className="flex-1 min-w-0">
+ {seriesCapReached && (
+ <LemonBanner type="info" className="mb-2" data-attr="metrics-series-cap-banner">
+ Showing the {MAX_UNAGGREGATED_SERIES} most recently active series. Add a filter or an
+ operation to narrow the chart.
+ </LemonBanner>
+ )}
<div className="relative h-[360px] border rounded p-3">
{!hasMetricName ? (
<div className="h-full flex items-center justify-center text-secondary text-sm">
diff --git a/products/metrics/frontend/components/metricsCatalogLogic.test.ts b/products/metrics/frontend/components/metricsCatalogLogic.test.ts
deleted file mode 100644
index 75d834b296a1..000000000000
--- a/products/metrics/frontend/components/metricsCatalogLogic.test.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-import { initKeaTests } from '~/test/init'
-import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
-
-import { metricsNamesRetrieve, metricsValuesCreate } from '../generated/api'
-import { metricsSceneLogic } from '../metricsSceneLogic'
-import { metricNamePickerLogic } from './metricNamePickerLogic'
-import { SPARKLINE_BATCH_SIZE, metricsCatalogLogic } from './metricsCatalogLogic'
-import { metricsViewerLogic } from './metricsViewerLogic'
-
-jest.mock('../generated/api', () => ({
- ...jest.requireActual('../generated/api'),
- metricsNamesRetrieve: jest.fn(),
- metricsValuesCreate: jest.fn(),
- metricsQueryCreate: jest.fn(),
-}))
-
-const CATALOG_ITEMS = [
- {
- name: 'http.server.duration',
- metric_type: 'histogram',
- },
- {
- name: 'queue.depth',
- metric_type: 'gauge',
- },
- { name: 'jobs.processed', metric_type: 'sum' },
-]
-
-const SPARKLINE_ITEM = {
- ...CATALOG_ITEMS[0],
- unit: 'ms',
- last_seen: '2026-09-03T10:00:00+00:00',
- sparkline: [1, 2, 3],
-}
-
-describe('metricsCatalogLogic', () => {
- let logic: ReturnType<typeof metricsCatalogLogic.build>
-
- beforeEach(() => {
- window.POSTHOG_APP_CONTEXT = {
- ...window.POSTHOG_APP_CONTEXT,
- resource_access_control: {
- ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
- [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
- },
- } as AppContext
- initKeaTests()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS]: true })
- jest.mocked(metricsValuesCreate).mockReset()
- jest.mocked(metricsValuesCreate).mockResolvedValue({ results: [SPARKLINE_ITEM] } as any)
- jest.mocked(metricsNamesRetrieve).mockReset()
- jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- it('loads catalog names without requesting sparklines', async () => {
- logic = metricsCatalogLogic()
- logic.mount()
-
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess']).toMatchValues({
- catalogItems: CATALOG_ITEMS,
- })
- expect(metricsValuesCreate).not.toHaveBeenCalled()
- })
-
- it('batches visible cards and maps each result by name', async () => {
- const queueDetail = { ...CATALOG_ITEMS[1], sparkline: [3, 2, 1] }
- jest.mocked(metricsValuesCreate).mockResolvedValueOnce({ results: [queueDetail, SPARKLINE_ITEM] } as any)
- logic = metricsCatalogLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- await expectLogic(logic, () => {
- logic.actions.loadSparkline(CATALOG_ITEMS[0])
- logic.actions.loadSparkline(CATALOG_ITEMS[1])
- logic.actions.loadSparkline(CATALOG_ITEMS[0])
- }).toDispatchActions(['loadSparklineSuccess'])
-
- expect(jest.mocked(metricsValuesCreate)).toHaveBeenCalledWith(expect.any(String), {
- names: ['http.server.duration', 'queue.depth'],
- })
- expect(metricsValuesCreate).toHaveBeenCalledTimes(1)
- expect(logic.values.catalogItemDetails['http.server.duration']).toEqual(SPARKLINE_ITEM)
- expect(logic.values.catalogItemDetails['queue.depth']).toEqual(queueDetail)
- expect(logic.values.catalogItemDetailsLoading).toEqual({ 'http.server.duration': false, 'queue.depth': false })
- })
-
- it('bounds batches and queues cards that enter view during a request', async () => {
- const items = Array.from({ length: SPARKLINE_BATCH_SIZE + 2 }, (_, index) => ({
- name: `metric.${index}`,
- metric_type: 'gauge',
- }))
- let completeBatch!: (response: any) => void
- jest.mocked(metricsValuesCreate).mockImplementationOnce(
- () => new Promise((resolve) => (completeBatch = resolve))
- )
- logic = metricsCatalogLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- await expectLogic(logic, () => {
- items.slice(0, -1).forEach(logic.actions.loadSparkline)
- }).toDispatchActions(['dequeueSparklines'])
- logic.actions.loadSparkline(items[items.length - 1])
- expect(metricsValuesCreate).toHaveBeenCalledTimes(1)
- expect(jest.mocked(metricsValuesCreate).mock.calls[0][1]?.names).toHaveLength(SPARKLINE_BATCH_SIZE)
-
- await expectLogic(logic, () => completeBatch({ results: [] })).toFinishAllListeners()
-
- expect(metricsValuesCreate).toHaveBeenCalledTimes(2)
- expect(jest.mocked(metricsValuesCreate).mock.calls[1][1]?.names).toEqual(
- items.slice(SPARKLINE_BATCH_SIZE).map((item) => item.name)
- )
- expect(Object.keys(logic.values.catalogItemDetails)).toHaveLength(items.length)
- expect(Object.values(logic.values.catalogItemDetailsLoading)).not.toContain(true)
- })
-
- it.each(['success', 'failure'])('discards an old scope batch %s', async (outcome) => {
- let finishBatch!: () => void
- jest.mocked(metricsValuesCreate).mockImplementationOnce(
- () =>
- new Promise((resolve, reject) => {
- finishBatch = () =>
- outcome === 'success'
- ? resolve({ results: [SPARKLINE_ITEM] } as any)
- : reject(new Error('old scope'))
- })
- )
- logic = metricsCatalogLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
- await expectLogic(logic, () => logic.actions.loadSparkline(CATALOG_ITEMS[0])).toDispatchActions([
- 'dequeueSparklines',
- ])
- await expectLogic(logic, () => logic.actions.setServices(['worker'])).toDispatchActions(['loadCatalogSuccess'])
- await expectLogic(logic, finishBatch).toFinishAllListeners()
-
- expect(logic.values.catalogItemDetails).toEqual({})
- expect(logic.values.catalogItemDetailsFailed).toEqual({})
- await expectLogic(logic, () => logic.actions.loadSparkline(CATALOG_ITEMS[0])).toDispatchActions([
- 'loadSparklineSuccess',
- ])
- expect(metricsValuesCreate).toHaveBeenLastCalledWith(expect.any(String), {
- names: [CATALOG_ITEMS[0].name],
- service: 'worker',
- })
- })
-
- it('retries a sparkline after a transient failure', async () => {
- jest.mocked(metricsValuesCreate)
- .mockRejectedValueOnce(new Error('temporary error'))
- .mockResolvedValueOnce({ results: [SPARKLINE_ITEM] } as any)
- logic = metricsCatalogLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- await expectLogic(logic, () => {
- logic.actions.loadSparkline(CATALOG_ITEMS[0])
- }).toDispatchActions(['loadSparklineFailure'])
- expect(logic.values.catalogItemDetailsFailed['http.server.duration']).toBe(true)
-
- await expectLogic(logic, () => {
- logic.actions.retrySparkline(CATALOG_ITEMS[0])
- }).toDispatchActions(['loadSparklineSuccess'])
-
- expect(logic.values.catalogItemDetailsFailed['http.server.duration']).toBe(false)
- expect(jest.mocked(metricsValuesCreate)).toHaveBeenCalledTimes(2)
- })
-
- it('narrows the visible cards by a search substring', async () => {
- logic = metricsCatalogLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- await expectLogic(logic, () => {
- logic.actions.setSearch('queue')
- }).toMatchValues({
- visibleItems: [CATALOG_ITEMS[1]],
- })
- })
-
- it('fetches the catalog scoped to the services the picker is pinned to', async () => {
- // The catalog follows the same picker scoping the overview drives, so a
- // service clicked on the overview only draws that service's cards.
- metricNamePickerLogic.mount()
- metricNamePickerLogic.actions.setServices(['api'])
- logic = metricsCatalogLogic()
- logic.mount()
-
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- expect(jest.mocked(metricsNamesRetrieve)).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ service: 'api' })
- )
- })
-
- it('fetches the whole catalog when no service scope is set', async () => {
- logic = metricsCatalogLogic()
- logic.mount()
-
- await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
-
- const call = jest.mocked(metricsNamesRetrieve).mock.calls[0][1]
- expect(call).not.toHaveProperty('service')
- })
-
- it('openMetric lands the metric in the viewer and switches tab', async () => {
- metricNamePickerLogic.mount()
- await expectLogic(metricNamePickerLogic).toDispatchActions(['loadItemsSuccess'])
- logic = metricsCatalogLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.openMetric(CATALOG_ITEMS[2]) // jobs.processed, a sum
- }).toDispatchActions([metricsViewerLogic.actionTypes.setMetricName, metricsSceneLogic.actionTypes.setActiveTab])
-
- expect(metricsSceneLogic.values.activeTab).toBe('viewer')
- expect(metricsViewerLogic.values.metricName).toBe('jobs.processed')
- })
-
- it('openMetric pins the picked metric type so a reused name charts only that type', async () => {
- metricNamePickerLogic.mount()
- await expectLogic(metricNamePickerLogic).toDispatchActions(['loadItemsSuccess'])
- logic = metricsCatalogLogic()
- logic.mount()
-
- logic.actions.openMetric(CATALOG_ITEMS[0]) // a histogram
-
- expect(metricsViewerLogic.values.activeClause.selectedMetricType).toBe('histogram')
- // The type drives the default aggregation: a histogram charts as a percentile.
- expect(metricsViewerLogic.values.activeClause.aggregation).toBe('p95')
- })
-})
diff --git a/products/metrics/frontend/components/metricsCatalogLogic.tsx b/products/metrics/frontend/components/metricsCatalogLogic.tsx
deleted file mode 100644
index e1480ac1bc72..000000000000
--- a/products/metrics/frontend/components/metricsCatalogLogic.tsx
+++ /dev/null
@@ -1,290 +0,0 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { teamLogic } from 'scenes/teamLogic'
-
-import { metricsNamesRetrieve, metricsValuesCreate } from '../generated/api'
-import type { _MetricNameApi, _MetricPickerNameApi } from '../generated/api.schemas'
-import { canViewMetrics } from '../metricsAccess'
-import { metricsSceneLogic } from '../metricsSceneLogic'
-import { metricNamePickerLogic } from './metricNamePickerLogic'
-import { metricsViewerLogic, toKnownMetricType } from './metricsViewerLogic'
-
-/** One catalog card: a metric name plus what makes it scannable before opening it. */
-export type MetricCatalogItem = _MetricPickerNameApi
-
-export const SPARKLINE_BATCH_SIZE = 20
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsCatalogLogicValues {
- pickerServices: string[] // metricNamePickerLogic
- currentTeamId: number | null // teamLogic
- catalogGeneration: number
- catalogItemDetails: Record<string, _MetricNameApi>
- catalogItemDetailsFailed: Record<string, boolean>
- catalogItemDetailsLoading: Record<string, boolean>
- catalogItems: MetricCatalogItem[]
- catalogItemsLoading: boolean
- pendingSparklines: Record<string, MetricCatalogItem>
- search: string
- visibleItems: MetricCatalogItem[]
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsCatalogLogicActions {
- setServices: (services: string[]) => {
- services: string[]
- } // metricNamePickerLogic
- setActiveTab: (activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab) => {
- activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab
- } // metricsSceneLogic
- setMetricName: (metricName: string) => {
- metricName: string
- } // metricsViewerLogic
- setSelectedMetricType: (metricType: null | import('../generated/api.schemas').OtelMetricTypeEnumApi) => {
- metricType: null | import('../generated/api.schemas').OtelMetricTypeEnumApi
- } // metricsViewerLogic
- dequeueSparklines: (names: string[]) => {
- names: string[]
- }
- loadCatalog: (_: void) => void
- loadCatalogFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadCatalogSuccess: (
- catalogItems: _MetricPickerNameApi[],
- payload?: void
- ) => {
- catalogItems: _MetricPickerNameApi[]
- payload?: void
- }
- loadSparkline: (item: MetricCatalogItem) => {
- item: _MetricPickerNameApi
- }
- loadSparklineBatch: () => {}
- loadSparklineFailure: (name: string) => {
- name: string
- }
- loadSparklineSuccess: (
- name: string,
- item: _MetricNameApi
- ) => {
- item: _MetricNameApi
- name: string
- }
- openMetric: (item: MetricCatalogItem) => {
- item: _MetricPickerNameApi
- }
- queueSparkline: (item: MetricCatalogItem) => {
- item: _MetricPickerNameApi
- }
- retrySparkline: (item: MetricCatalogItem) => {
- item: _MetricPickerNameApi
- }
- setSearch: (search: string) => {
- search: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsCatalogLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- visibleItems: (catalogItems: _MetricPickerNameApi[], search: string) => MetricCatalogItem[]
- }
-}
-
-export type metricsCatalogLogicType = MakeLogicType<
- metricsCatalogLogicValues,
- metricsCatalogLogicActions,
- Record<string, any>,
- metricsCatalogLogicMeta
->
-
-export const metricsCatalogLogic = kea<metricsCatalogLogicType>([
- path(['products', 'metrics', 'frontend', 'components', 'metricsCatalogLogic']),
- connect(() => ({
- values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['services as pickerServices']],
- actions: [
- metricsViewerLogic,
- ['setMetricName', 'setSelectedMetricType'],
- metricsSceneLogic,
- ['setActiveTab'],
- metricNamePickerLogic,
- ['setServices'],
- ],
- })),
- actions({
- setSearch: (search: string) => ({ search }),
- loadSparkline: (item: MetricCatalogItem) => ({ item }),
- queueSparkline: (item: MetricCatalogItem) => ({ item }),
- loadSparklineBatch: () => ({}),
- dequeueSparklines: (names: string[]) => ({ names }),
- loadSparklineSuccess: (name: string, item: _MetricNameApi) => ({ name, item }),
- loadSparklineFailure: (name: string) => ({ name }),
- retrySparkline: (item: MetricCatalogItem) => ({ item }),
- // A card click hands the metric to the viewer and switches to it.
- openMetric: (item: MetricCatalogItem) => ({ item }),
- }),
- reducers({
- search: ['' as string, { setSearch: (_, { search }) => search }],
- catalogGeneration: [0, { loadCatalog: (state) => state + 1 }],
- pendingSparklines: [
- {} as Record<string, MetricCatalogItem>,
- {
- loadCatalog: () => ({}),
- queueSparkline: (state, { item }) => ({ ...state, [item.name]: item }),
- dequeueSparklines: (state, { names }) =>
- Object.fromEntries(Object.entries(state).filter(([name]) => !names.includes(name))),
- },
- ],
- // Details depend on the service scope. Drop the old scope as soon as a
- // replacement name list starts loading, so a late card can never show a
- // sparkline from the service the person just left.
- catalogItemDetails: [
- {} as Record<string, _MetricNameApi>,
- {
- loadCatalog: () => ({}),
- loadSparklineSuccess: (state, { name, item }) => ({ ...state, [name]: item }),
- },
- ],
- catalogItemDetailsFailed: [
- {} as Record<string, boolean>,
- {
- loadCatalog: () => ({}),
- loadSparklineFailure: (state, { name }) => ({ ...state, [name]: true }),
- retrySparkline: (state, { item }) => ({ ...state, [item.name]: false }),
- },
- ],
- catalogItemDetailsLoading: [
- {} as Record<string, boolean>,
- {
- loadCatalog: () => ({}),
- queueSparkline: (state, { item }) => ({ ...state, [item.name]: true }),
- loadSparklineSuccess: (state, { name }) => ({ ...state, [name]: false }),
- loadSparklineFailure: (state, { name }) => ({ ...state, [name]: false }),
- },
- ],
- }),
- loaders(({ values }) => ({
- catalogItems: [
- [] as MetricCatalogItem[],
- {
- loadCatalog: async (_: void, breakpoint): Promise<MetricCatalogItem[]> => {
- if (!canViewMetrics()) {
- return []
- }
- // The catalog is scoped to whatever services the picker is
- // currently pinned to (a service entered from the overview, or
- // the viewer's own scope), so the cards match what the user
- // clicked into. It returns only names; visible cards load their
- // own sparkline later instead of one query sampling every metric.
- const response = await metricsNamesRetrieve(String(values.currentTeamId), {
- limit: 500,
- ...(values.pickerServices.length ? { service: values.pickerServices.join(',') } : {}),
- })
- breakpoint()
- return response.results
- },
- },
- ],
- })),
- selectors({
- visibleItems: [
- (s) => [s.catalogItems, s.search],
- (catalogItems: MetricCatalogItem[], search: string): MetricCatalogItem[] => {
- const needle = search.trim().toLowerCase()
- if (!needle) {
- return catalogItems
- }
- return catalogItems.filter((item) => item.name.toLowerCase().includes(needle))
- },
- ],
- }),
- listeners(({ actions, values, cache }) => ({
- // Re-scope: entering a service from the overview or a viewer filter change
- // re-reads the cards for that scope.
- setServices: () => {
- actions.loadCatalog()
- },
- loadSparkline: ({ item }) => {
- // An IntersectionObserver can notify more than once while a card is
- // near the viewport. Keep one request per name and retry only after a
- // failed request or after the catalog scope changes.
- if (
- values.catalogItemsLoading ||
- values.catalogItemDetails[item.name] ||
- values.catalogItemDetailsLoading[item.name] ||
- values.catalogItemDetailsFailed[item.name]
- ) {
- return
- }
- actions.queueSparkline(item)
- if (!cache.loadingBatch) {
- actions.loadSparklineBatch()
- }
- },
- loadSparklineBatch: async (_, breakpoint) => {
- if (cache.loadingBatch) {
- return
- }
- cache.loadingBatch = true
- try {
- await breakpoint(50)
- while (Object.keys(values.pendingSparklines).length > 0) {
- const items = Object.values(values.pendingSparklines).slice(0, SPARKLINE_BATCH_SIZE)
- const names = items.map((item) => item.name)
- const generation = values.catalogGeneration
- const teamId = values.currentTeamId
- actions.dequeueSparklines(names)
- let results: _MetricNameApi[] | undefined
- try {
- const response = await metricsValuesCreate(String(teamId), {
- names,
- ...(values.pickerServices.length ? { service: values.pickerServices.join(',') } : {}),
- })
- results = response.results
- } catch {
- results = undefined
- }
- breakpoint()
- if (generation !== values.catalogGeneration || teamId !== values.currentTeamId) {
- continue
- }
- const details = new Map(results?.map((item) => [item.name, item]))
- for (const item of items) {
- if (results) {
- actions.loadSparklineSuccess(
- item.name,
- details.get(item.name) ?? { ...item, sparkline: [] }
- )
- } else {
- actions.loadSparklineFailure(item.name)
- }
- }
- }
- } finally {
- cache.loadingBatch = false
- }
- },
- retrySparkline: ({ item }) => {
- actions.loadSparkline(item)
- },
- openMetric: ({ item }) => {
- // Set the type first so it latches: a metric name reused across OTel
- // types (a counter and a gauge) charts only the picked type, and the
- // viewer's recommended-aggregation backfill keys off the latched type.
- actions.setSelectedMetricType(toKnownMetricType(item.metric_type))
- actions.setMetricName(item.name)
- actions.setActiveTab('viewer')
- },
- })),
- afterMount(({ actions }) => {
- if (canViewMetrics()) {
- actions.loadCatalog()
- }
- }),
-])
diff --git a/products/metrics/frontend/components/metricsHandoff.test.ts b/products/metrics/frontend/components/metricsHandoff.test.ts
deleted file mode 100644
index 66d788767cd3..000000000000
--- a/products/metrics/frontend/components/metricsHandoff.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { initKeaTests } from '~/test/init'
-import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
-
-import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'
-import { metricsCatalogLogic } from './metricsCatalogLogic'
-
-jest.mock('../generated/api', () => ({
- ...jest.requireActual('../generated/api'),
- metricsNamesRetrieve: jest.fn(),
- metricsValuesRetrieve: jest.fn(),
- metricsQueryCreate: jest.fn(),
-}))
-
-// 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(() => {
- window.POSTHOG_APP_CONTEXT = {
- current_project: { id: 997 },
- resource_access_control: {
- [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
- },
- } as unknown as AppContext
- initKeaTests()
- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)
- jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] } as any)
- })
-
- 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)
-
- const sceneHold = metricsCatalogLogic()
- sceneHold.mount()
- await expectLogic(sceneHold).toDispatchActions(['loadCatalogSuccess'])
- const tabHold = metricsCatalogLogic()
- tabHold.mount()
-
- tabHold.unmount()
-
- expect(sceneHold.values.catalogItems).toEqual(items)
- sceneHold.unmount()
- })
-})
diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
index 1c781850ca41..7be87736f96e 100644
--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
@@ -71,7 +71,7 @@ describe('metricsStarterDashboardLogic', () => {
expect(logic.values.metricOptions).toHaveLength(3)
})
- it('creates the dashboard, then one insight per metric with the recommended aggregation and service filter', async () => {
+ it('creates the dashboard, then one unaggregated insight per metric with the service filter', async () => {
logic.actions.openModal()
await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])
logic.actions.setDashboardName('Billing service')
@@ -97,16 +97,16 @@ describe('metricsStarterDashboardLogic', () => {
{
name: 'a',
metricName: 'billing.invoices.processed',
- aggregation: 'increase', // recommended for counters
metricType: 'sum',
filters: [{ key: 'service.name', op: 'eq', value: 'billing-worker' }],
},
],
})
- // The node schema has no 'p95' — the recommended shorthand maps to quantile + 0.95.
+ expect((countInsight.query as any).clauses[0]).not.toHaveProperty('aggregation')
expect(histogramInsight.query).toMatchObject({
- clauses: [expect.objectContaining({ aggregation: 'quantile', quantile: 0.95, metricType: 'histogram' })],
+ clauses: [expect.objectContaining({ metricType: 'histogram' })],
})
+ expect((histogramInsight.query as any).clauses[0]).not.toHaveProperty('aggregation')
})
it('navigates to the partially built dashboard when an insight create fails mid-loop', async () => {
@@ -151,12 +151,11 @@ describe('metricsStarterDashboardLogic', () => {
logic.actions.createDashboard()
}).toDispatchActions(['createDashboardSuccess'])
- // Name-keyed lookup would collapse to the last-listed type (gauge/avg).
+ // Name-keyed lookup would collapse to the last-listed type (gauge).
const [insight] = mockInsightCreate.mock.calls[0]
expect((insight.query as any).clauses[0]).toMatchObject({
metricName: 'billing.throughput',
metricType: 'sum',
- aggregation: 'increase',
})
})
diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
index ae632bb1d12f..e9ee1ad4628f 100644
--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
@@ -15,7 +15,7 @@ import type { DashboardType } from '~/types'
import { metricsAttributeValuesRetrieve, metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'
import type { _MetricPickerNameApi } from 'products/metrics/frontend/generated/api.schemas'
-import { RECOMMENDED_AGGREGATION_BY_TYPE, nodeAggregationFields, toKnownMetricType } from './metricsViewerLogic'
+import { toKnownMetricType } from './metricsViewerLogic'
// A metric name can appear under more than one OTel type, so option identity
// must include both. \0 can't occur in ingest strings, so the key is collision-free.
@@ -102,9 +102,9 @@ export type metricsStarterDashboardLogicType = MakeLogicType<
metricsStarterDashboardLogicActions
>
-// One dashboard, one insight per picked metric, each charted with the
-// aggregation its type recommends and scoped to the picked service — the
-// onboarding doc's starter set, productized.
+// One dashboard, one insight per picked metric, each charted as one line per
+// series and scoped to the picked service — the onboarding doc's starter set,
+// productized.
export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType>([
path(['products', 'metrics', 'frontend', 'components', 'metricsStarterDashboardLogic']),
connect(() => ({
@@ -214,11 +214,9 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType
// The names endpoint reports raw ingest strings; only enum members
// may reach the API — mirrors the viewer's metricsQueryNode.
const metricType = toKnownMetricType(rawType)
- const recommended = (rawType && RECOMMENDED_AGGREGATION_BY_TYPE[rawType]) || 'avg'
const clause: MetricsQueryClause = {
name: 'a',
metricName,
- ...nodeAggregationFields(recommended),
...(metricType ? { metricType } : {}),
...(serviceName
? { filters: [{ key: 'service.name', op: 'eq' as const, value: serviceName }] }
@@ -226,7 +224,7 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType
}
const query: MetricsQuery = { kind: NodeKind.MetricsQuery, clauses: [clause] }
await insightsApi.create({
- name: `${metricName} (${recommended})`,
+ name: metricName,
saved: true,
dashboards: [dashboard.id],
query,
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
index 644f031cdd6b..6d87e81d5dbf 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
@@ -13,7 +13,6 @@ import { metricsQueryCreate, metricsSamplesCreate, metricsNamesRetrieve } from '
import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'
import { metricsSceneLogic } from '../metricsSceneLogic'
-import { metricNamePickerLogic } from './metricNamePickerLogic'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
import { metricsViewerLogic } from './metricsViewerLogic'
@@ -90,6 +89,11 @@ describe('metricsUsageTrackingLogic', () => {
() => metricsViewerLogic.actions.setAggregation('p95'),
{ aggregation: 'p95' },
],
+ [
+ 'metrics viewer range function changed',
+ () => metricsViewerLogic.actions.setRangeFunction('rate'),
+ { range_function: 'rate' },
+ ],
['metrics viewer live toggled', () => metricsViewerLogic.actions.setLiveRefresh(true), { enabled: true }],
[
'metrics viewer date range changed',
@@ -109,12 +113,12 @@ describe('metricsUsageTrackingLogic', () => {
[
'metrics add to dashboard clicked',
() => metricsViewerLogic.actions.addToDashboard(),
- { aggregation: 'sum', clause_count: 1, has_formula: false },
+ { aggregation: null, range_function: null, clause_count: 1, has_formula: false },
],
[
// Reports the aggregation persisted on the insight, not the viewer's
// current one — those diverge when the user changes the aggregation
- // while the save request is in flight (viewer state here is 'sum').
+ // while the save request is in flight (viewer state here has none).
'metrics insight saved',
() =>
metricsViewerLogic.actions.saveAsInsightSuccess(
@@ -124,7 +128,7 @@ describe('metricsUsageTrackingLogic', () => {
} as any,
{} as any
),
- { aggregation: 'p95', clause_count: 1, has_formula: false },
+ { aggregation: 'p95', range_function: null, clause_count: 1, has_formula: false },
],
])('%s fires with enum/count properties only', (event, dispatch, expectedProperties) => {
dispatch()
@@ -165,6 +169,7 @@ describe('metricsUsageTrackingLogic', () => {
router.actions.push('/metrics', {
metricName: SECRET_METRIC,
aggregation: 'p95',
+ rangeFunction: 'rate',
dateFrom: '-24h',
groupBy: '["env"]',
})
@@ -172,19 +177,11 @@ describe('metricsUsageTrackingLogic', () => {
expect(captures('metrics viewer metric selected')).toHaveLength(0)
expect(captures('metrics viewer aggregation changed')).toHaveLength(0)
+ expect(captures('metrics viewer range function changed')).toHaveLength(0)
expect(captures('metrics viewer date range changed')).toHaveLength(0)
expect(captures('metrics viewer group by changed')).toHaveLength(0)
})
- // Selecting a metric auto-applies its recommended aggregation; counting that dispatch as a
- // user action would inflate the feature-adoption tile on every metric switch.
- it('the auto-applied recommended aggregation is not an aggregation change', () => {
- metricNamePickerLogic.actions.loadItemsSuccess([{ name: SECRET_METRIC, metric_type: 'sum' }] as any)
- metricsViewerLogic.actions.setMetricName(SECRET_METRIC)
- expect(metricsViewerLogic.values.aggregation).toBe('increase')
- expect(captures('metrics viewer aggregation changed')).toHaveLength(0)
- })
-
it('query completed reports shape counts and timing, never series labels', async () => {
jest.mocked(metricsQueryCreate).mockResolvedValue({
results: [
@@ -209,7 +206,8 @@ describe('metricsUsageTrackingLogic', () => {
series_count: 2,
point_count: 3,
load_ms: expect.any(Number),
- aggregation: 'sum',
+ aggregation: null,
+ range_function: null,
has_group_by: false,
has_filters: false,
},
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
index 426374735396..44f635d06b47 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
@@ -17,16 +17,17 @@ import type { MetricsSceneActiveTab } from '../metricsSceneLogic'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import type { MetricsPanelTab } from './metricsSamplesLogic'
import { metricsViewerLogic, viewerAggregationFromNode } from './metricsViewerLogic'
-import type { MetricAggregation, MetricsViewerClause } from './metricsViewerLogic'
+import type { MetricAggregation, MetricRangeFunction, MetricsViewerClause } from './metricsViewerLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicValues {
isRestoringFromUrl: boolean // metricsSceneLogic
- aggregation: MetricAggregation // metricsViewerLogic
+ aggregation: MetricAggregation | null // metricsViewerLogic
formula: string // metricsViewerLogic
groupByKeys: string[] // metricsViewerLogic
hasMetricName: boolean // metricsViewerLogic
queryFilters: _MetricFilterApi[] // metricsViewerLogic
+ rangeFunction: MetricRangeFunction | null // metricsViewerLogic
viewerClauses: MetricsViewerClause[] // metricsViewerLogic
}
@@ -73,8 +74,8 @@ export interface metricsUsageTrackingLogicActions {
payload?: any
savedInsight: InsightModel<Node<Record<string, any>>> | null
} // metricsViewerLogic
- setAggregation: (aggregation: MetricAggregation) => {
- aggregation: MetricAggregation
+ setAggregation: (aggregation: MetricAggregation | null) => {
+ aggregation: MetricAggregation | null
} // metricsViewerLogic
setDateFrom: (dateFrom: string | null) => {
dateFrom: string | null
@@ -94,6 +95,9 @@ export interface metricsUsageTrackingLogicActions {
setMetricName: (metricName: string) => {
metricName: string
} // metricsViewerLogic
+ setRangeFunction: (rangeFunction: MetricRangeFunction | null) => {
+ rangeFunction: MetricRangeFunction | null
+ } // metricsViewerLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
exemplarDotClicked: (hasSpanId: boolean) => {
hasSpanId: boolean
@@ -127,6 +131,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
[
'setMetricName',
'setAggregation',
+ 'setRangeFunction',
'setDateFrom',
'setLiveRefresh',
'setGroupByKeys',
@@ -146,7 +151,15 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
],
values: [
metricsViewerLogic,
- ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters', 'viewerClauses', 'formula'],
+ [
+ 'hasMetricName',
+ 'aggregation',
+ 'rangeFunction',
+ 'groupByKeys',
+ 'queryFilters',
+ 'viewerClauses',
+ 'formula',
+ ],
metricsSceneLogic,
['isRestoringFromUrl'],
],
@@ -173,6 +186,11 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
posthog.capture('metrics viewer aggregation changed', { aggregation })
}
},
+ setRangeFunction: ({ rangeFunction }) => {
+ if (!values.isRestoringFromUrl) {
+ posthog.capture('metrics viewer range function changed', { range_function: rangeFunction })
+ }
+ },
// The DateFilter dispatches setDateFrom and setDateTo together on every change,
// so listening to setDateFrom alone captures each range change exactly once.
setDateFrom: ({ dateFrom }) => {
@@ -211,6 +229,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
addToDashboard: () => {
posthog.capture('metrics add to dashboard clicked', {
aggregation: values.aggregation,
+ range_function: values.rangeFunction,
clause_count: values.viewerClauses.length,
has_formula: !!values.formula,
})
@@ -224,6 +243,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
const savedQuery = savedInsight.query as MetricsQuery | undefined
posthog.capture('metrics insight saved', {
aggregation: viewerAggregationFromNode(savedQuery?.clauses?.[0]?.aggregation),
+ range_function: savedQuery?.clauses?.[0]?.rangeFunction ?? null,
clause_count: savedQuery?.clauses?.length ?? null,
has_formula: !!savedQuery?.formula,
})
@@ -245,6 +265,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
point_count: queryResults.reduce((sum: number, series) => sum + series.points.length, 0),
load_ms: loadMs,
aggregation: values.aggregation,
+ range_function: values.rangeFunction,
has_group_by: values.groupByKeys.length > 0,
has_filters: values.queryFilters.length > 0,
})
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index ca2b24b3874c..3876ff75afb5 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -94,36 +94,52 @@ describe('metricsViewerLogic', () => {
logic?.unmount()
})
- // Regression: the viewer defaulted every metric to `sum`, so selecting a
- // cumulative counter summed raw monotonic readings across pods and buckets —
- // a huge meaningless total instead of the actual increase.
- it.each([
- ['requests_total', 'increase'],
- ['queue_depth', 'avg'],
- ['request_duration', 'p95'],
- ])('selecting %s applies the type-appropriate aggregation %s', (metricName, expected) => {
- logic.actions.setMetricName(metricName)
- expect(logic.values.aggregation).toBe(expected)
- })
+ // Regression: the builder used to pick an aggregation from the metric type. An unaggregated
+ // clause must stay one line per series, whatever the metric is.
+ it.each(['requests_total', 'queue_depth', 'request_duration'])(
+ 'selecting %s leaves the clause without operations',
+ (metricName) => {
+ logic.actions.setMetricName(metricName)
+ expect(logic.values.aggregation).toBeNull()
+ expect(logic.values.rangeFunction).toBeNull()
+ expect(logic.values.queryPayload?.clauses?.[0]).toMatchObject({ aggregation: 'none' })
+ }
+ )
- it('keeps a manual aggregation pick until the metric changes', () => {
+ it('keeps the operations when the metric changes', () => {
logic.actions.setMetricName('requests_total')
- logic.actions.setAggregation('rate')
- expect(logic.values.aggregation).toBe('rate')
+ logic.actions.setRangeFunction('rate')
+ logic.actions.setAggregation('max')
logic.actions.setMetricName('queue_depth')
- expect(logic.values.aggregation).toBe('avg')
+ expect(logic.values.rangeFunction).toBe('rate')
+ expect(logic.values.aggregation).toBe('max')
})
- it('leaves aggregation untouched for unknown metric types', () => {
+ it('sends a range function without an aggregation as per-series rates', () => {
logic.actions.setMetricName('requests_total')
- logic.actions.setMetricName('mystery_metric')
- expect(logic.values.aggregation).toBe('increase')
+ logic.actions.setRangeFunction('rate')
+ expect(logic.values.queryPayload?.clauses?.[0]).toMatchObject({ aggregation: 'none', rangeFunction: 'rate' })
+ expect(logic.values.metricsQueryNode?.clauses[0]).toEqual({
+ name: 'a',
+ metricName: 'requests_total',
+ metricType: 'sum',
+ rangeFunction: 'rate',
+ })
+ })
+
+ it('clears group-by when the aggregation is removed', () => {
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setAggregation('avg')
+ logic.actions.setGroupByKeys(['container'])
+ logic.actions.setAggregation(null)
+ expect(logic.values.groupByKeys).toEqual([])
})
// metricsQueryNode is what "Save as insight" persists: a wrong mapping here
// silently saves insights that re-run a different query than the viewer showed.
it('maps viewer state to a MetricsQuery node, translating p95 to quantile', () => {
logic.actions.setMetricName('request_duration')
+ logic.actions.setAggregation('p95')
logic.actions.setGroupByKeys(['container'])
logic.actions.setFilterGroup(
filterGroupWith([{ key: 'namespace', operator: PropertyOperator.Exact, value: ['posthog'] }])
@@ -264,14 +280,23 @@ describe('metricsViewerLogic', () => {
// different query than the viewer showed.
it('maps multiple clauses and a formula into the MetricsQuery node', () => {
logic.actions.setMetricName('requests_total')
+ logic.actions.setRangeFunction('increase')
+ logic.actions.setAggregation('sum')
logic.actions.addClause()
logic.actions.setMetricName('queue_depth')
+ logic.actions.setAggregation('avg')
logic.actions.setFormula('A / b!')
expect(logic.values.metricsQueryNode).toEqual({
kind: NodeKind.MetricsQuery,
clauses: [
- { name: 'a', metricName: 'requests_total', aggregation: 'increase', metricType: 'sum' },
+ {
+ name: 'a',
+ metricName: 'requests_total',
+ rangeFunction: 'increase',
+ aggregation: 'sum',
+ metricType: 'sum',
+ },
{ name: 'b', metricName: 'queue_depth', aggregation: 'avg', metricType: 'gauge' },
],
formula: 'a / b',
@@ -284,6 +309,7 @@ describe('metricsViewerLogic', () => {
// shows one series' samples under another series' chart line.
it('single-clause setters and selectors follow the active clause', () => {
logic.actions.setMetricName('requests_total')
+ logic.actions.setAggregation('sum')
logic.actions.addClause()
expect(logic.values.activeClauseIndex).toBe(1)
@@ -292,7 +318,7 @@ describe('metricsViewerLogic', () => {
logic.actions.setActiveClauseIndex(0)
expect(logic.values.metricName).toBe('requests_total')
- expect(logic.values.aggregation).toBe('increase')
+ expect(logic.values.aggregation).toBe('sum')
})
// A formula referencing a removed clause's alias can only 400 — a routine remove
@@ -422,15 +448,13 @@ describe('metricsViewerLogic', () => {
expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
})
- it('backfills the metric type and recommended aggregation when the picker loads after the metric was set', () => {
+ it('backfills the metric type when the picker loads after the metric was set', () => {
metricNamePickerLogic.actions.loadItemsSuccess([])
logic.actions.setMetricName('queue_depth')
expect(logic.values.metricsQueryNode?.clauses[0]).not.toHaveProperty('metricType')
metricNamePickerLogic.actions.loadItemsSuccess(PICKER_ITEMS)
expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
- // A cold URL restore sets the name before the list arrives, so without the late
- // recommendation a gauge/counter link would silently chart as a raw sum.
- expect(logic.values.aggregation).toBe('avg')
+ expect(logic.values.aggregation).toBeNull()
})
it('the late backfill leaves an explicitly chosen aggregation alone', () => {
@@ -474,7 +498,7 @@ describe('metricsViewerLogic', () => {
await expectLogic(logic).toDispatchActions(['openAddToDashboardModal'])
logic.actions.closeAddToDashboardModal()
- logic.actions.setAggregation('rate')
+ logic.actions.setRangeFunction('rate')
logic.actions.addToDashboard()
await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess', 'openAddToDashboardModal'])
expect(insightsApi.create).toHaveBeenCalledTimes(2)
@@ -607,7 +631,7 @@ describe('metricsViewerLogic', () => {
logic.actions.createAlert()
await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])
- logic.actions.setAggregation('rate')
+ logic.actions.setRangeFunction('rate')
logic.actions.createAlert()
await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])
expect(insightsApi.create).toHaveBeenCalledTimes(2)
@@ -629,7 +653,7 @@ describe('metricsViewerLogic', () => {
expect(logic.values.pendingAlert).toBe(false)
push.mockClear()
- logic.actions.setAggregation('rate')
+ logic.actions.setRangeFunction('rate')
logic.actions.saveAsInsight()
await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])
expect(push).not.toHaveBeenCalled()
@@ -877,7 +901,7 @@ describe('metricsViewerLogic', () => {
filters: [{ key: 'namespace', op: 'eq', value: 'posthog' }],
groupBy: [{ key: 'container' }],
},
- { name: 'b', metricName: 'requests_total', aggregation: 'rate', metricType: 'sum' },
+ { name: 'b', metricName: 'requests_total', rangeFunction: 'rate', metricType: 'sum' },
],
formula: 'a / b',
dateRange: { date_from: '-6h' },
@@ -919,6 +943,20 @@ describe('metricsViewerLogic', () => {
})
})
+ it('reads a saved query with a legacy rate aggregation as a rate range function over a sum', () => {
+ const editor = metricsViewerLogic({
+ key: 'legacy-test',
+ initialQuery: {
+ kind: NodeKind.MetricsQuery,
+ clauses: [{ name: 'a', metricName: 'requests_total', aggregation: 'rate' }],
+ },
+ })
+ editor.mount()
+ expect(editor.values.rangeFunction).toBe('rate')
+ expect(editor.values.aggregation).toBe('sum')
+ editor.unmount()
+ })
+
it('sends the picked interval to the viewer query', () => {
logic.actions.setMetricName('queue_depth')
logic.actions.setInterval('minute')
@@ -936,7 +974,10 @@ describe('isBuilderCompatibleQuery', () => {
})
it.each([
- ['a viewer aggregation', queryWith({ aggregation: 'rate' }), true],
+ ['a viewer aggregation', queryWith({ aggregation: 'max' }), true],
+ ['no aggregation', queryWith({ aggregation: undefined }), true],
+ ['a legacy rate aggregation', queryWith({ aggregation: 'rate' }), true],
+ ['a range function', queryWith({ aggregation: undefined, rangeFunction: 'rate' }), true],
['p95', queryWith({ aggregation: 'quantile', quantile: 0.95 }), true],
['another quantile', queryWith({ aggregation: 'quantile', quantile: 0.99 }), false],
['histogram_quantile', queryWith({ aggregation: 'histogram_quantile', quantile: 0.95 }), false],
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index fca5fca8755a..6031a6c0fabf 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -66,13 +66,30 @@ import type { MetricsChartSeries } from './metricsSeries'
// A derived type ((typeof METRIC_AGGREGATIONS)[number]) would keep these in sync, but
// kea-typegen inlines derived unions into every consumer's generated block — keep the
// named alias so those blocks stay stable.
-export type MetricAggregation = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'p95' | 'rate' | 'increase'
-export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count', 'min', 'max', 'p95', 'rate', 'increase']
+export type MetricAggregation = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'p95'
+export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count', 'min', 'max', 'p95']
+
+/** Applied to each series before any aggregation, like `rate()` and `increase()` in PromQL. */
+export type MetricRangeFunction = 'rate' | 'increase'
+export const METRIC_RANGE_FUNCTIONS: MetricRangeFunction[] = ['rate', 'increase']
/** Narrows an untrusted value (a URL param, a saved link) to an aggregation the backend accepts. */
export const isMetricAggregation = (value: unknown): value is MetricAggregation =>
typeof value === 'string' && METRIC_AGGREGATIONS.includes(value as MetricAggregation)
+export const isMetricRangeFunction = (value: unknown): value is MetricRangeFunction =>
+ typeof value === 'string' && METRIC_RANGE_FUNCTIONS.includes(value as MetricRangeFunction)
+
+/** The old single `aggregation` field held a range function as one of its values: `rate` meant rate, then sum. */
+export const splitLegacyAggregation = (
+ value: unknown
+): { rangeFunction: MetricRangeFunction | null; aggregation: MetricAggregation | null } => {
+ if (isMetricRangeFunction(value)) {
+ return { rangeFunction: value, aggregation: 'sum' }
+ }
+ return { rangeFunction: null, aggregation: isMetricAggregation(value) ? value : null }
+}
+
export { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY }
export type MetricsViewerSeries = _MetricSeriesApi
@@ -82,9 +99,12 @@ export interface MetricsViewerClause {
/** Alias a formula refers to; unique within the query (a, b, c…). */
name: string
metricName: string
+ /** Latched from the picker for heatmap eligibility and series pinning. Never shown. */
selectedMetricType: OtelMetricTypeEnumApi | null
- aggregation: MetricAggregation
- aggregationExplicitlySet: boolean
+ /** Applied to each series first. Null means the raw samples. */
+ rangeFunction: MetricRangeFunction | null
+ /** Combines series, split by `groupByKeys`. Null means one line per series. */
+ aggregation: MetricAggregation | null
filterGroup: UniversalFiltersGroup
groupByKeys: string[]
}
@@ -97,11 +117,10 @@ export interface MetricsViewerQueryState {
formula: string
}
-/** One clause's share of the picker's late type/aggregation backfill. */
+/** One clause's share of the picker's late type backfill. */
export interface MetricsViewerClauseBackfill {
index: number
- metricType?: OtelMetricTypeEnumApi
- aggregation?: MetricAggregation
+ metricType: OtelMetricTypeEnumApi
}
// Request-body slices the viewer assembles; the window fields are added at fetch time.
@@ -110,6 +129,8 @@ export type MetricsAnomalyRequestBody = Pick<_MetricAnomalyBodyApi, 'metricName'
// Mirrors the backend's MAX_CLAUSES_PER_QUERY.
export const MAX_CLAUSES = 10
+// Mirrors the backend's MAX_RAW_SERIES: a clause without an aggregation returns at most this many series.
+export const MAX_UNAGGREGATED_SERIES = 100
// More letters than MAX_CLAUSES, so the cap is the only thing that limits adding
// a series — a shorter alias supply would make "Add series" silently no-op.
const CLAUSE_ALIASES = alphabet.map((letter) => letter.toLowerCase())
@@ -118,8 +139,8 @@ export const createViewerClause = (name: string): MetricsViewerClause => ({
name,
metricName: '',
selectedMetricType: null,
- aggregation: DEFAULT_AGGREGATION,
- aggregationExplicitlySet: false,
+ rangeFunction: null,
+ aggregation: null,
filterGroup: DEFAULT_UNIVERSAL_GROUP_FILTER,
groupByKeys: [],
})
@@ -155,20 +176,6 @@ export interface MetricsAnomalyBadge {
onsetTime: string | null
}
-export const DEFAULT_AGGREGATION: MetricAggregation = 'sum'
-
-// Aggregation applied automatically when a metric of this type is selected.
-// Cumulative counters (OTel type 'sum') summed raw give meaningless ever-growing
-// totals — 'increase' is the honest default and is temporality-aware server-side
-// (delta samples are summed as-is), so it's correct for delta producers too.
-export const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation> = {
- gauge: 'avg',
- sum: 'increase',
- counter: 'increase',
- histogram: 'p95',
- summary: 'p95',
- exponential_histogram: 'p95',
-}
export const DEFAULT_DATE_FROM = '-1h'
// Kept off the persisted node: a saved query with no `display` renders as a line chart anyway.
export const DEFAULT_DISPLAY_TYPE: MetricsDisplayType = 'line'
@@ -276,20 +283,24 @@ export const toKnownMetricType = (metricType: string | undefined): OtelMetricTyp
/** The REST viewer's 'p95' shorthand maps to the schema node's quantile aggregation. */
export const nodeAggregationFields = (
- aggregation: MetricAggregation
-): Pick<MetricsQueryClause, 'aggregation' | 'quantile'> =>
- aggregation === 'p95' ? { aggregation: 'quantile', quantile: 0.95 } : { aggregation }
+ aggregation: MetricAggregation | null
+): Pick<MetricsQueryClause, 'aggregation' | 'quantile'> => {
+ if (!aggregation) {
+ return {}
+ }
+ return aggregation === 'p95' ? { aggregation: 'quantile', quantile: 0.95 } : { aggregation }
+}
/** Inverse of `nodeAggregationFields`, for reading a saved node back in viewer vocabulary. */
export const viewerAggregationFromNode = (aggregation: MetricsQueryClause['aggregation'] | undefined): string | null =>
aggregation === 'quantile' ? 'p95' : (aggregation ?? null)
-const clauseToApiClause = (clause: MetricsViewerClause): _MetricClauseApi => {
+const clauseWithoutAggregation = (clause: MetricsViewerClause): Omit<_MetricClauseApi, 'aggregation'> => {
const filters = metricFiltersForGroup(clause.filterGroup)
return {
name: clause.name,
metricName: clause.metricName.trim(),
- aggregation: clause.aggregation,
+ ...(clause.rangeFunction ? { rangeFunction: clause.rangeFunction } : {}),
// Pins the OTel type so a name that exists as several types (e.g. a counter
// and a gauge) charts only the picked one instead of blending them.
...(clause.selectedMetricType ? { metricType: clause.selectedMetricType } : {}),
@@ -298,14 +309,31 @@ const clauseToApiClause = (clause: MetricsViewerClause): _MetricClauseApi => {
}
}
-// Derived from the API clause so a new clause field cannot reach one payload and
+// The REST API defaults a missing aggregation to 'sum', so a clause without one sends 'none' explicitly.
+const clauseToApiClause = (clause: MetricsViewerClause): _MetricClauseApi => ({
+ ...clauseWithoutAggregation(clause),
+ aggregation: clause.aggregation ?? 'none',
+})
+
+// Built from the same base as the API clause so a new clause field cannot reach one payload and
// miss the other — the two shapes differ only in the aggregation vocabulary.
const clauseToNodeClause = (clause: MetricsViewerClause): MetricsQueryClause =>
({
- ...clauseToApiClause(clause),
+ ...clauseWithoutAggregation(clause),
...nodeAggregationFields(clause.aggregation),
}) as MetricsQueryClause
+/** The single aggregation the anomaly endpoint takes, where `rate` and `increase` imply a sum over series.
+ * Null for a combination they cannot express. */
+export const singleAggregationForClause = (
+ clause: Pick<MetricsViewerClause, 'rangeFunction' | 'aggregation'>
+): MetricAggregation | MetricRangeFunction | null => {
+ if (!clause.rangeFunction) {
+ return clause.aggregation ?? 'sum'
+ }
+ return !clause.aggregation || clause.aggregation === 'sum' ? clause.rangeFunction : null
+}
+
const insightNameForViewerQuery = (clauses: MetricsViewerClause[], formula: string): string => {
const names = clauses.map((clause) => clause.metricName.trim())
let name: string
@@ -314,7 +342,9 @@ const insightNameForViewerQuery = (clauses: MetricsViewerClause[], formula: stri
} else if (clauses.length > 1) {
name = `${names.join(', ')} (${clauses.length} series)`
} else {
- name = `${names[0]} (${clauses[0].aggregation})`
+ const { rangeFunction, aggregation } = clauses[0]
+ const operations = [rangeFunction, aggregation].filter(Boolean).join(', ')
+ name = operations ? `${names[0]} (${operations})` : names[0]
}
return truncate(name, 120)
}
@@ -355,21 +385,24 @@ const isAutoScope = (scope: MetricsAttributeScope | undefined): boolean => !scop
export const isBuilderCompatibleQuery = (query: MetricsQuery): boolean =>
query.clauses.every(
(clause) =>
- (isMetricAggregation(clause.aggregation) ||
+ (!clause.aggregation ||
+ isMetricAggregation(clause.aggregation) ||
+ isMetricRangeFunction(clause.aggregation) ||
(clause.aggregation === 'quantile' && clause.quantile === 0.95)) &&
(clause.filters ?? []).every((filter) => isAutoScope(filter.scope)) &&
(clause.groupBy ?? []).every((groupBy) => isAutoScope(groupBy.scope))
)
const viewerClauseFromNode = (clause: MetricsQueryClause): MetricsViewerClause => {
- const aggregation = viewerAggregationFromNode(clause.aggregation)
+ // Saved queries predating range functions hold `rate` or `increase` as the aggregation.
+ const legacy = splitLegacyAggregation(clause.aggregation)
+ const aggregation = legacy.aggregation ?? viewerAggregationFromNode(clause.aggregation)
return {
name: clause.name,
metricName: clause.metricName,
selectedMetricType: toKnownMetricType(clause.metricType),
- aggregation: isMetricAggregation(aggregation) ? aggregation : DEFAULT_AGGREGATION,
- // A saved aggregation is a choice, so the type backfill must not replace it.
- aggregationExplicitlySet: true,
+ rangeFunction: legacy.rangeFunction ?? clause.rangeFunction ?? null,
+ aggregation: isMetricAggregation(aggregation) ? aggregation : null,
filterGroup: filterGroupFromMetricFilters(clause.filters ?? []),
groupByKeys: (clause.groupBy ?? []).map((groupBy) => groupBy.key),
}
@@ -413,7 +446,7 @@ export interface metricsViewerLogicValues {
timezone: string // teamLogic
activeClause: MetricsViewerClause
activeClauseIndex: number
- aggregation: MetricAggregation
+ aggregation: MetricAggregation | null
anomalyAbortController: AbortController | null
anomalyBadge: MetricsAnomalyBadge | null
anomalyFingerprint: string
@@ -461,11 +494,13 @@ export interface metricsViewerLogicValues {
queryResults: MetricsViewerSeries[]
queryResultsLoading: boolean
queryState: MetricsViewerQueryState
+ rangeFunction: MetricRangeFunction | null
savedInsight: InsightModel | null
savedInsightLoading: boolean
savedQueryNode: MetricsHistogramQuery | MetricsQuery | null
selectedMetricType: OtelMetricTypeEnumApi | null
selectedServices: string[]
+ seriesCapReached: boolean
viewerClauses: MetricsViewerClause[]
yAxisSettings: MetricsYAxisSettings
}
@@ -620,8 +655,8 @@ export interface metricsViewerLogicActions {
setActiveClauseIndex: (index: number) => {
index: number
}
- setAggregation: (aggregation: MetricAggregation) => {
- aggregation: MetricAggregation
+ setAggregation: (aggregation: MetricAggregation | null) => {
+ aggregation: MetricAggregation | null
}
setAnomalyAbortController: (controller: AbortController | null) => {
controller: AbortController | null
@@ -669,8 +704,8 @@ export interface metricsViewerLogicActions {
setQueryAbortController: (controller: AbortController | null) => {
controller: AbortController | null
}
- setRecommendedAggregation: (aggregation: MetricAggregation) => {
- aggregation: MetricAggregation
+ setRangeFunction: (rangeFunction: MetricRangeFunction | null) => {
+ rangeFunction: MetricRangeFunction | null
}
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
metricType: OtelMetricTypeEnumApi | null
@@ -703,7 +738,8 @@ export interface metricsViewerLogicMeta {
activeClause: (viewerClauses: MetricsViewerClause[], activeClauseIndex: number) => MetricsViewerClause
metricName: (activeClause: MetricsViewerClause) => string
selectedMetricType: (activeClause: MetricsViewerClause) => OtelMetricTypeEnumApi | null
- aggregation: (activeClause: MetricsViewerClause) => MetricAggregation
+ rangeFunction: (activeClause: MetricsViewerClause) => MetricRangeFunction | null
+ aggregation: (activeClause: MetricsViewerClause) => MetricAggregation | null
groupByKeys: (activeClause: MetricsViewerClause) => string[]
filterGroup: (activeClause: MetricsViewerClause) => UniversalFiltersGroup
namedClauses: (viewerClauses: MetricsViewerClause[]) => MetricsViewerClause[]
@@ -751,6 +787,7 @@ export interface metricsViewerLogicMeta {
) => Record<string, string>
chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
hasResults: (queryResults: _MetricSeriesApi[]) => boolean
+ seriesCapReached: (viewerClauses: MetricsViewerClause[], queryResults: _MetricSeriesApi[]) => boolean
anomalyTopMovers: (anomalyReport: _MetricAnomalyReportApi | null) => MetricTopMoverRow[]
anomalyBadge: (anomalyReport: _MetricAnomalyReportApi | null) => MetricsAnomalyBadge | null
}
@@ -782,10 +819,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
// keeps working unchanged with several clauses on screen.
setMetricName: (metricName: string) => ({ metricName }),
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => ({ metricType }),
- setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
- // Auto-applied on metric switch — a separate action so usage tracking can
- // tell it apart from the user picking an aggregation themselves.
- setRecommendedAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
+ // Null removes the aggregation, so each series gets its own line.
+ setAggregation: (aggregation: MetricAggregation | null) => ({ aggregation }),
+ setRangeFunction: (rangeFunction: MetricRangeFunction | null) => ({ rangeFunction }),
setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
addClause: true,
@@ -795,7 +831,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setFormula: (formula: string) => ({ formula }),
// Bulk replace, used by the scene's URL restore.
setClauses: (clauses: MetricsViewerClause[], formula: string) => ({ clauses, formula }),
- // The picker's late type/aggregation backfill, applied to every clause in one
+ // The picker's late type backfill, applied to every clause in one
// pass so a 10-clause deep link costs one reducer run and one URL write.
backfillClauses: (updates: MetricsViewerClauseBackfill[]) => ({ updates }),
setDateFrom: (dateFrom: string | null) => ({ dateFrom }),
@@ -853,9 +889,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
: DEFAULT_QUERY_STATE) as MetricsViewerQueryState,
{
setMetricName: (state, { metricName }) =>
- // A metric switch drops the previous deliberate aggregation pick,
- // matching what picking a metric always did.
- withActiveClause(state, (clause) => ({ ...clause, metricName, aggregationExplicitlySet: false })),
+ withActiveClause(state, (clause) => ({ ...clause, metricName })),
// The picked metric's type, latched at pick time (and backfilled if the
// picker list arrives later). Not derived from the picker's `items` —
// those are live search results, so typing a new search would wipe a
@@ -863,9 +897,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setSelectedMetricType: (state, { metricType }) =>
withActiveClause(state, (clause) => ({ ...clause, selectedMetricType: metricType })),
setAggregation: (state, { aggregation }) =>
- withActiveClause(state, (clause) => ({ ...clause, aggregation, aggregationExplicitlySet: true })),
- setRecommendedAggregation: (state, { aggregation }) =>
- withActiveClause(state, (clause) => ({ ...clause, aggregation, aggregationExplicitlySet: false })),
+ // Without an aggregation there is nothing to split by.
+ withActiveClause(state, (clause) => ({
+ ...clause,
+ aggregation,
+ groupByKeys: aggregation ? clause.groupByKeys : [],
+ })),
+ setRangeFunction: (state, { rangeFunction }) =>
+ withActiveClause(state, (clause) => ({ ...clause, rangeFunction })),
// Attribute keys to split the clause into one series each (e.g. ['service.name', 'env']).
setGroupByKeys: (state, { groupByKeys }) =>
withActiveClause(state, (clause) => ({ ...clause, groupByKeys })),
@@ -881,13 +920,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}
return {
...clause,
- // A backfill never overrides a latched type or a deliberate pick.
- ...(update.metricType && clause.selectedMetricType === null
- ? { selectedMetricType: update.metricType }
- : {}),
- ...(update.aggregation && !clause.aggregationExplicitlySet
- ? { aggregation: update.aggregation }
- : {}),
+ // A backfill never overrides a latched type.
+ ...(clause.selectedMetricType === null ? { selectedMetricType: update.metricType } : {}),
}
}),
}),
@@ -1052,11 +1086,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
queryLoading: [false as boolean, abortResilientLoading('fetchQueryResults')],
})),
listeners(({ actions, values, cache }) => {
- // Recovers each clause's type, and the aggregation that follows from it, when the metric
- // names were set before the picker's list arrived — the shape of a deep link on a cold
- // load. An already-latched type and an explicitly chosen aggregation are left alone.
- // Without the aggregation half, a link to a cumulative counter charts the raw running
- // total rather than its rate: nothing recommended an aggregation while the list was empty.
+ // Recovers each clause's type when the metric names were set before the picker's list
+ // arrived — the shape of a deep link on a cold load. An already-latched type is left alone.
const backfillClauseTypes = (): void => {
const updates: MetricsViewerClauseBackfill[] = []
values.viewerClauses.forEach((clause, index) => {
@@ -1064,20 +1095,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
if (!trimmedName) {
return
}
- const metricType = values.items.find((item) => item.name === trimmedName)?.metric_type
- const known = toKnownMetricType(metricType)
- const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
- const update: MetricsViewerClauseBackfill = { index }
+ const known = toKnownMetricType(values.items.find((item) => item.name === trimmedName)?.metric_type)
if (known && clause.selectedMetricType === null) {
- update.metricType = known
- }
- // The explicit-pick flag, not a compare against the default, is what holds a
- // deliberate choice — picking the default value is still a choice.
- if (recommended && !clause.aggregationExplicitlySet && recommended !== clause.aggregation) {
- update.aggregation = recommended
- }
- if (update.metricType || update.aggregation) {
- updates.push(update)
+ updates.push({ index, metricType: known })
}
})
if (updates.length) {
@@ -1173,12 +1193,6 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type
const knownType = toKnownMetricType(metricType)
actions.setSelectedMetricType(knownType)
- // Each metric type has one sensible default; a manual aggregation pick
- // holds only until the next metric switch.
- const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
- if (recommended && recommended !== values.aggregation) {
- actions.setRecommendedAggregation(recommended)
- }
// A distribution metric leaving the chart can't keep the heatmap display —
// fall back rather than render it against a metric with no histogram.
if (values.displayType === 'heatmap' && (!knownType || !HISTOGRAM_METRIC_TYPES.includes(knownType))) {
@@ -1430,6 +1444,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
(s) => [s.activeClause],
(activeClause: MetricsViewerClause) => activeClause.selectedMetricType,
],
+ rangeFunction: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.rangeFunction],
aggregation: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.aggregation],
groupByKeys: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.groupByKeys],
filterGroup: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.filterGroup],
@@ -1476,10 +1491,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
return null
}
const clause = namedClauses[0]
+ const aggregation = singleAggregationForClause(clause)
+ if (!aggregation) {
+ return null
+ }
const filters = metricFiltersForGroup(clause.filterGroup)
return {
metricName: clause.metricName.trim(),
- aggregation: clause.aggregation,
+ aggregation,
...(filters.length ? { filters } : {}),
}
},
@@ -1645,6 +1664,16 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
(s) => [s.queryResults],
(results: MetricsViewerSeries[]): boolean => results.some((series) => series.points.length > 0),
],
+ // Whether a clause without an aggregation hit the series cap, so the chart is missing series.
+ seriesCapReached: [
+ (s) => [s.viewerClauses, s.queryResults],
+ (clauses: MetricsViewerClause[], results: MetricsViewerSeries[]): boolean =>
+ clauses.some(
+ (clause) =>
+ !clause.aggregation &&
+ results.filter((series) => series.clause === clause.name).length >= MAX_UNAGGREGATED_SERIES
+ ),
+ ],
// The label values behind the current anomaly, ranked. Empty for an ungrouped metric or
// when nothing stood out, which the panel reports rather than hiding.
anomalyTopMovers: [
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index ed3cbfdab3e9..d716f49f47be 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -356,6 +356,45 @@ export const OtelMetricTypeEnumApi = {
Summary: 'summary',
} as const
+/**
+ * * `none` - none
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `min` - min
+ * * `max` - max
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile
+ */
+export type MetricQueryAggregationEnumApi =
+ (typeof MetricQueryAggregationEnumApi)[keyof typeof MetricQueryAggregationEnumApi]
+
+export const MetricQueryAggregationEnumApi = {
+ None: 'none',
+ Sum: 'sum',
+ Avg: 'avg',
+ Count: 'count',
+ Min: 'min',
+ Max: 'max',
+ P95: 'p95',
+ Rate: 'rate',
+ Increase: 'increase',
+ HistogramQuantile: 'histogram_quantile',
+} as const
+
+/**
+ * * `rate` - rate
+ * * `increase` - increase
+ */
+export type MetricRangeFunctionEnumApi = (typeof MetricRangeFunctionEnumApi)[keyof typeof MetricRangeFunctionEnumApi]
+
+export const MetricRangeFunctionEnumApi = {
+ Rate: 'rate',
+ Increase: 'increase',
+} as const
+
export interface _MetricGroupByApi {
/**
* Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
@@ -418,6 +457,7 @@ export interface _MetricClauseApi {
metricType?: OtelMetricTypeEnumApi | null
/** Aggregation applied per time bucket; same semantics as the top-level aggregation.
*
+ * * `none` - none
* * `sum` - sum
* * `avg` - avg
* * `count` - count
@@ -427,7 +467,12 @@ export interface _MetricClauseApi {
* * `rate` - rate
* * `increase` - increase
* * `histogram_quantile` - histogram_quantile */
- aggregation?: AggregationEnumApi
+ aggregation?: MetricQueryAggregationEnumApi
+ /** Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.
+ *
+ * * `rate` - rate
+ * * `increase` - increase */
+ rangeFunction?: MetricRangeFunctionEnumApi | null
/**
* Quantile in (0, 1) for 'histogram_quantile'.
* @minimum 0
@@ -455,8 +500,9 @@ export interface _MetricQueryBodyApi {
* * `exponential_histogram` - exponential_histogram
* * `summary` - summary */
metricType?: OtelMetricTypeEnumApi | null
- /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.
+ /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'. 'none' skips the aggregation and returns one series per label set, at most 100, using each series' last sample per bucket; it cannot be combined with 'groupBy'.
*
+ * * `none` - none
* * `sum` - sum
* * `avg` - avg
* * `count` - count
@@ -466,7 +512,12 @@ export interface _MetricQueryBodyApi {
* * `rate` - rate
* * `increase` - increase
* * `histogram_quantile` - histogram_quantile */
- aggregation?: AggregationEnumApi
+ aggregation?: MetricQueryAggregationEnumApi
+ /** Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.
+ *
+ * * `rate` - rate
+ * * `increase` - increase */
+ rangeFunction?: MetricRangeFunctionEnumApi | null
/**
* Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations.
* @minimum 0
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index cceaa08bb811..051d23ea1b75 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -172,13 +172,22 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
"Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary"
),
aggregation: zod
- .enum(['sum', 'avg', 'count', 'min', 'max', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .enum(['none', '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'
+ '\* `none` - none\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'
)
.default(metricsQueryCreateBodyQueryOneAggregationDefault)
.describe(
- "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `min` - min\n\* `max` - max\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
+ "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'. 'none' skips the aggregation and returns one series per label set, at most 100, using each series' last sample per bucket; it cannot be combined with 'groupBy'.\n\n\* `none` - none\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"
+ ),
+ rangeFunction: zod
+ .union([
+ zod.enum(['rate', 'increase']).describe('\* `rate` - rate\n\* `increase` - increase'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.\n\n\* `rate` - rate\n\* `increase` - increase"
),
quantile: zod
.number()
@@ -287,6 +296,7 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
),
aggregation: zod
.enum([
+ 'none',
'sum',
'avg',
'count',
@@ -298,11 +308,20 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
'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'
+ '\* `none` - none\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'
)
.default(metricsQueryCreateBodyQueryOneClausesItemAggregationDefault)
.describe(
- 'Aggregation applied per time bucket; same semantics as the top-level aggregation.\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'
+ 'Aggregation applied per time bucket; same semantics as the top-level aggregation.\n\n\* `none` - none\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'
+ ),
+ rangeFunction: zod
+ .union([
+ zod.enum(['rate', 'increase']).describe('\* `rate` - rate\n\* `increase` - increase'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.\n\n\* `rate` - rate\n\* `increase` - increase"
),
quantile: zod
.number()
diff --git a/products/metrics/frontend/metricsSceneLogic.test.ts b/products/metrics/frontend/metricsSceneLogic.test.ts
index 3cd7556b7830..338b6d3480a5 100644
--- a/products/metrics/frontend/metricsSceneLogic.test.ts
+++ b/products/metrics/frontend/metricsSceneLogic.test.ts
@@ -108,8 +108,6 @@ describe('metricsSceneLogic', () => {
expect(logic.values.activeTab).toEqual('viewer')
expect(logic.values.metricName).toEqual('queue_depth')
expect(logic.values.selectedMetricType).toEqual('gauge')
- // The shared link's own aggregation survives the recommendation cascade that
- // picking queue_depth (a gauge, recommending 'avg') triggers.
expect(logic.values.aggregation).toEqual('p95')
expect(logic.values.dateFrom).toEqual('-24h')
expect(logic.values.dateTo).toEqual('2026-08-25T00:00:00.000Z')
@@ -120,17 +118,36 @@ describe('metricsSceneLogic', () => {
expect(router.values.searchParams).toMatchObject({ metricName: 'queue_depth', aggregation: 'p95' })
})
- it('keeps the recommended aggregation for a link that has a metric but no aggregation param', async () => {
+ it('leaves a link that has a metric but no aggregation param without operations', async () => {
await expectLogic(logic, () => {
router.actions.push('/metrics', { metricName: 'queue_depth' })
}).toFinishAllListeners()
- expect(logic.values.aggregation).toEqual('avg')
+ expect(logic.values.aggregation).toBeNull()
+ expect(logic.values.rangeFunction).toBeNull()
+ })
+
+ it('reads a legacy rate link as a rate range function over a sum', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { metricName: 'requests_total', aggregation: 'rate' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.rangeFunction).toEqual('rate')
+ expect(logic.values.aggregation).toEqual('sum')
+ })
+
+ it('restores a range function link without an aggregation', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { metricName: 'requests_total', rangeFunction: 'increase' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.rangeFunction).toEqual('increase')
+ expect(logic.values.aggregation).toBeNull()
})
it.each([
['activeTab', 'nonsense', 'activeTab', 'overview'],
- ['aggregation', 'not-an-aggregation', 'aggregation', 'sum'],
+ ['aggregation', 'not-an-aggregation', 'aggregation', null],
['metricType', 'not-a-type', 'selectedMetricType', null],
])('falls back to the default for an invalid %s param', async (param, urlValue, valueKey, expected) => {
await expectLogic(logic, () => {
@@ -159,7 +176,12 @@ describe('metricsSceneLogic', () => {
}).toFinishAllListeners()
expect(logic.values.viewerClauses).toEqual([
- expect.objectContaining({ name: 'a', metricName: 'requests_total', aggregation: 'rate' }),
+ expect.objectContaining({
+ name: 'a',
+ metricName: 'requests_total',
+ rangeFunction: 'rate',
+ aggregation: 'sum',
+ }),
expect.objectContaining({
name: 'b',
metricName: 'queue_depth',
@@ -268,13 +290,8 @@ describe('metricsSceneLogic', () => {
logic.actions.setDateFrom('-7d')
}).toFinishAllListeners()
- // aggregation is written even when recommended ('increase' for this counter), so
- // restoring the link never has to re-derive it.
- expect(router.values.searchParams).toMatchObject({
- metricName: 'requests_total',
- aggregation: 'increase',
- dateFrom: '-7d',
- })
+ expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total', dateFrom: '-7d' })
+ expect(router.values.searchParams).not.toHaveProperty('aggregation')
await expectLogic(logic, () => {
logic.actions.setDateFrom('-1h')
@@ -323,16 +340,17 @@ describe('metricsSceneLogic', () => {
it('keeps the named clause in the URL while a blank added row is focused', async () => {
await expectLogic(logic, () => {
logic.actions.setMetricName('requests_total')
+ logic.actions.setRangeFunction('rate')
}).toFinishAllListeners()
metricsViewerLogic.actions.addClause()
await expectLogic(logic, () => {
- logic.actions.setAggregation('rate')
+ logic.actions.setAggregation('max')
}).toFinishAllListeners()
expect(router.values.searchParams).toMatchObject({
metricName: 'requests_total',
- aggregation: 'increase',
+ rangeFunction: 'rate',
})
})
diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsx
index ef34f5050753..1c42a0f3f879 100644
--- a/products/metrics/frontend/metricsSceneLogic.tsx
+++ b/products/metrics/frontend/metricsSceneLogic.tsx
@@ -20,22 +20,24 @@ import { UniversalFiltersGroup } from '~/types'
import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'
import {
- DEFAULT_AGGREGATION,
DEFAULT_DATE_FROM,
MAX_CLAUSES,
MetricAggregation,
+ MetricRangeFunction,
MetricsViewerClause,
createViewerClause,
isMetricAggregation,
+ isMetricRangeFunction,
metricsViewerLogic,
sanitizeFormulaInput,
+ splitLegacyAggregation,
toKnownMetricType,
} from './components/metricsViewerLogic'
export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'
-export type MetricsSceneActiveTab = 'overview' | 'explore' | 'viewer' | 'sql'
-const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'explore', 'viewer', 'sql']
+export type MetricsSceneActiveTab = 'overview' | 'viewer' | 'sql'
+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', '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
@@ -53,18 +55,26 @@ const isValidFilterGroup = (group: any): group is UniversalFiltersGroup =>
// Legacy single-clause params, written for one plain clause so old links stay short
// and other products' link builders (metricsLinks.ts) keep working unchanged.
-const LEGACY_VIEWER_PARAMS = ['metricName', 'metricType', 'aggregation', 'groupBy', 'filterGroup'] as const
+const LEGACY_VIEWER_PARAMS = [
+ 'metricName',
+ 'metricType',
+ 'rangeFunction',
+ 'aggregation',
+ 'groupBy',
+ 'filterGroup',
+] as const
// A clause's alias must satisfy the backend's identifier rules (formulas reference it).
const CLAUSE_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
-// The URL codec's clause shape: only the fields a link needs — no active index, no
-// explicit-pick flag, defaults omitted. Parse and serialize both speak this type, so a
+// The URL codec's clause shape: only the fields a link needs — no active index,
+// defaults omitted. Parse and serialize both speak this type, so a
// field added to one direction fails to compile until the other carries it too.
interface UrlViewerClause {
name: string
metricName: string
- aggregation: MetricAggregation
+ rangeFunction?: MetricRangeFunction
+ aggregation?: MetricAggregation
metricType?: OtelMetricTypeEnumApi
groupBy?: string[]
filterGroup?: UniversalFiltersGroup
@@ -73,7 +83,8 @@ interface UrlViewerClause {
const serializeViewerClause = (clause: MetricsViewerClause): UrlViewerClause => ({
name: clause.name,
metricName: clause.metricName.trim(),
- aggregation: clause.aggregation,
+ ...(clause.rangeFunction ? { rangeFunction: clause.rangeFunction } : {}),
+ ...(clause.aggregation ? { aggregation: clause.aggregation } : {}),
...(clause.selectedMetricType ? { metricType: clause.selectedMetricType } : {}),
...(clause.groupByKeys.length ? { groupBy: clause.groupByKeys } : {}),
...(objectsEqual(clause.filterGroup, DEFAULT_UNIVERSAL_GROUP_FILTER) ? {} : { filterGroup: clause.filterGroup }),
@@ -100,21 +111,29 @@ const parseClausesParam = (raw: unknown): MetricsViewerClause[] | null => {
return null
}
seenNames.add(name)
- if (!isMetricAggregation(item.aggregation)) {
+ if (
+ item.aggregation != null &&
+ !isMetricAggregation(item.aggregation) &&
+ !isMetricRangeFunction(item.aggregation)
+ ) {
return null
}
+ if (item.rangeFunction != null && !isMetricRangeFunction(item.rangeFunction)) {
+ return null
+ }
+ const legacy = splitLegacyAggregation(item.aggregation)
+ const aggregation = legacy.aggregation
+ // A split needs an aggregation to combine each group's series.
const groupByKeys =
- Array.isArray(item.groupBy) && item.groupBy.every((key: unknown) => typeof key === 'string')
+ aggregation && Array.isArray(item.groupBy) && item.groupBy.every((key: unknown) => typeof key === 'string')
? (item.groupBy as string[])
: []
clauses.push({
name,
metricName,
selectedMetricType: toKnownMetricType(typeof item.metricType === 'string' ? item.metricType : undefined),
- aggregation: item.aggregation,
- // An aggregation named in a link is a deliberate choice — the picker's
- // late type backfill must not override it with the recommendation.
- aggregationExplicitlySet: true,
+ rangeFunction: item.rangeFunction ?? legacy.rangeFunction,
+ aggregation,
filterGroup: isValidFilterGroup(item.filterGroup) ? item.filterGroup : DEFAULT_UNIVERSAL_GROUP_FILTER,
groupByKeys,
})
@@ -124,7 +143,7 @@ const parseClausesParam = (raw: unknown): MetricsViewerClause[] | null => {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSceneLogicValues {
- aggregation: MetricAggregation // metricsViewerLogic
+ aggregation: MetricAggregation | null // metricsViewerLogic
dateFrom: string | null // metricsViewerLogic
dateTo: string | null // metricsViewerLogic
filterGroup: UniversalFiltersGroup // metricsViewerLogic
@@ -132,6 +151,7 @@ export interface metricsSceneLogicValues {
groupByKeys: string[] // metricsViewerLogic
metricName: string // metricsViewerLogic
namedClauses: MetricsViewerClause[] // metricsViewerLogic
+ rangeFunction: MetricRangeFunction | null // metricsViewerLogic
selectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogic
viewerClauses: MetricsViewerClause[] // metricsViewerLogic
activeTab: MetricsSceneActiveTab
@@ -149,8 +169,8 @@ export interface metricsSceneLogicActions {
removeClause: (index: number) => {
index: number
} // metricsViewerLogic
- setAggregation: (aggregation: MetricAggregation) => {
- aggregation: MetricAggregation
+ setAggregation: (aggregation: MetricAggregation | null) => {
+ aggregation: MetricAggregation | null
} // metricsViewerLogic
setClauses: (
clauses: MetricsViewerClause[],
@@ -177,8 +197,8 @@ export interface metricsSceneLogicActions {
setMetricName: (metricName: string) => {
metricName: string
} // metricsViewerLogic
- setRecommendedAggregation: (aggregation: MetricAggregation) => {
- aggregation: MetricAggregation
+ setRangeFunction: (rangeFunction: MetricRangeFunction | null) => {
+ rangeFunction: MetricRangeFunction | null
} // metricsViewerLogic
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
metricType: OtelMetricTypeEnumApi | null
@@ -208,6 +228,7 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
'metricName',
'selectedMetricType',
'aggregation',
+ 'rangeFunction',
'dateFrom',
'dateTo',
'groupByKeys',
@@ -223,7 +244,7 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
'setMetricName',
'setSelectedMetricType',
'setAggregation',
- 'setRecommendedAggregation',
+ 'setRangeFunction',
'setDateFrom',
'setDateTo',
'setGroupByKeys',
@@ -302,8 +323,7 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
} else if (values.formula) {
actions.setFormula('')
}
- // metricName first: its listener latches the metric type and a recommended
- // aggregation, which the explicit URL params below then override.
+ // metricName first: its listener latches the metric type.
const metricName = params.metricName != null ? String(params.metricName) : ''
if (metricName !== values.metricName) {
actions.setMetricName(metricName)
@@ -314,16 +334,19 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
if (metricType && metricType !== values.selectedMetricType) {
actions.setSelectedMetricType(metricType)
}
- const aggregation = isMetricAggregation(params.aggregation) ? params.aggregation : null
- if (aggregation && aggregation !== values.aggregation) {
+ // Links written before range functions carry `rate` or `increase` as the aggregation.
+ const legacy = splitLegacyAggregation(params.aggregation)
+ const rangeFunction = isMetricRangeFunction(params.rangeFunction)
+ ? params.rangeFunction
+ : legacy.rangeFunction
+ if (rangeFunction !== values.rangeFunction) {
+ actions.setRangeFunction(rangeFunction)
+ }
+ const aggregation = legacy.aggregation
+ if (aggregation !== values.aggregation) {
actions.setAggregation(aggregation)
- } else if (!aggregation && !metricName && values.aggregation !== DEFAULT_AGGREGATION) {
- // A bare URL resets to the clean-slate default. With a metric but no
- // aggregation param (a hand-written link), the recommended aggregation
- // latched by setMetricName stays.
- actions.setAggregation(DEFAULT_AGGREGATION)
}
- const groupByKeys = parseTagsFilter(params.groupBy) ?? []
+ const groupByKeys = aggregation ? (parseTagsFilter(params.groupBy) ?? []) : []
if (!objectsEqual(groupByKeys, values.groupByKeys)) {
actions.setGroupByKeys(groupByKeys)
}
@@ -390,14 +413,8 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
values.namedClauses[0] ?? (values.viewerClauses.length === 1 ? values.viewerClauses[0] : null)
updateSearchParams(params, 'metricName', clause?.metricName.trim() ?? '', '')
updateSearchParams(params, 'metricType', clause?.selectedMetricType ?? null, null)
- if (clause?.metricName.trim()) {
- // Never dropped while a metric is picked: 'sum' is both the default and a
- // valid explicit choice, so a link that omitted it would restore with the
- // metric type's recommended aggregation instead of the one on screen.
- params.aggregation = clause.aggregation
- } else {
- delete params.aggregation
- }
+ updateSearchParams(params, 'rangeFunction', clause?.rangeFunction ?? null, null)
+ updateSearchParams(params, 'aggregation', clause?.aggregation ?? null, null)
updateSearchParams(params, 'groupBy', clause?.groupByKeys ?? [], [] as string[])
updateSearchParams(
params,
@@ -420,7 +437,7 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
setMetricName: () => syncUrl(),
setSelectedMetricType: () => syncUrl(),
setAggregation: () => syncUrl(),
- setRecommendedAggregation: () => syncUrl(),
+ setRangeFunction: () => syncUrl(),
setDateFrom: () => syncUrl(),
setDateTo: () => syncUrl(),
setGroupByKeys: () => syncUrl(),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 45db5875527d..042ed5ebe8c6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55904,8 +55904,17 @@ export namespace Schemas {
Summary: 'summary',
} as const;
+ export type MetricsRangeFunction = typeof MetricsRangeFunction[keyof typeof MetricsRangeFunction];
+
+
+ export const MetricsRangeFunction = {
+ Rate: 'rate',
+ Increase: 'increase',
+ } as const;
+
export interface MetricsQueryClause {
- aggregation: MetricsAggregation;
+ /** Omit to get one line per series (at most 100), without combining them */
+ aggregation?: MetricsAggregation | null;
filters?: MetricsQueryFilter[] | null;
groupBy?: MetricsQueryGroupBy[] | null;
metricName: string;
@@ -55915,6 +55924,8 @@ export namespace Schemas {
name: string;
/** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
quantile?: number | null;
+ /** Applied to each series before `aggregation`, like `rate()` in PromQL */
+ rangeFunction?: MetricsRangeFunction | null;
}
export type MetricsReducer = typeof MetricsReducer[keyof typeof MetricsReducer];
@@ -65088,6 +65099,34 @@ export namespace Schemas {
Partial: 'partial',
} as const;
+ /**
+ * * `none` - none
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `min` - min
+ * * `max` - max
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile
+ */
+ export type MetricQueryAggregationEnum = typeof MetricQueryAggregationEnum[keyof typeof MetricQueryAggregationEnum];
+
+
+ export const MetricQueryAggregationEnum = {
+ None: 'none',
+ Sum: 'sum',
+ Avg: 'avg',
+ Count: 'count',
+ Min: 'min',
+ Max: 'max',
+ P95: 'p95',
+ Rate: 'rate',
+ Increase: 'increase',
+ HistogramQuantile: 'histogram_quantile',
+ } as const;
+
/**
* * `second_15` - second_15
* * `second_30` - second_30
@@ -65116,6 +65155,18 @@ export namespace Schemas {
Week: 'week',
} as const;
+ /**
+ * * `rate` - rate
+ * * `increase` - increase
+ */
+ export type MetricRangeFunctionEnum = typeof MetricRangeFunctionEnum[keyof typeof MetricRangeFunctionEnum];
+
+
+ export const MetricRangeFunctionEnum = {
+ Rate: 'rate',
+ Increase: 'increase',
+ } as const;
+
/**
* * `funnel` - funnel
* * `mean_count` - mean_count
@@ -112529,6 +112580,7 @@ export namespace Schemas {
metricType?: OtelMetricTypeEnum | null;
/** Aggregation applied per time bucket; same semantics as the top-level aggregation.
*
+ * * `none` - none
* * `sum` - sum
* * `avg` - avg
* * `count` - count
@@ -112538,7 +112590,12 @@ export namespace Schemas {
* * `rate` - rate
* * `increase` - increase
* * `histogram_quantile` - histogram_quantile */
- aggregation?: AggregationEnum;
+ aggregation?: MetricQueryAggregationEnum;
+ /** Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.
+ *
+ * * `rate` - rate
+ * * `increase` - increase */
+ rangeFunction?: MetricRangeFunctionEnum | null;
/**
* Quantile in (0, 1) for 'histogram_quantile'.
* @minimum 0
@@ -112655,8 +112712,9 @@ export namespace Schemas {
* * `exponential_histogram` - exponential_histogram
* * `summary` - summary */
metricType?: OtelMetricTypeEnum | null;
- /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.
+ /** Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'. 'none' skips the aggregation and returns one series per label set, at most 100, using each series' last sample per bucket; it cannot be combined with 'groupBy'.
*
+ * * `none` - none
* * `sum` - sum
* * `avg` - avg
* * `count` - count
@@ -112666,7 +112724,12 @@ export namespace Schemas {
* * `rate` - rate
* * `increase` - increase
* * `histogram_quantile` - histogram_quantile */
- aggregation?: AggregationEnum;
+ aggregation?: MetricQueryAggregationEnum;
+ /** Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.
+ *
+ * * `rate` - rate
+ * * `increase` - increase */
+ rangeFunction?: MetricRangeFunctionEnum | null;
/**
* Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations.
* @minimum 0
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index 14cabbcf45ea..6d642ffef062 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -187,13 +187,22 @@ export const MetricsQueryCreateBody = () => zod.object({
"Constrain the query to one metric type. A name can exist as several types (e.g. a counter and a gauge); without this, rows of every type sharing the name are blended into one aggregate. Get the type from 'metric-names-list'.\n\n\* `gauge` - gauge\n\* `sum` - sum\n\* `histogram` - histogram\n\* `exponential_histogram` - exponential_histogram\n\* `summary` - summary"
),
aggregation: zod
- .enum(['sum', 'avg', 'count', 'min', 'max', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .enum(['none', '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'
+ '\* `none` - none\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'
)
.default(metricsQueryCreateBodyQueryOneAggregationDefault)
.describe(
- "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `min` - min\n\* `max` - max\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
+ "Aggregation applied per time bucket, always across series rather than across raw samples. 'sum', 'avg', 'min', 'max' and 'p95' reduce each series to its last sample in the bucket and then combine those, so the result does not scale with the scrape rate; 'count' is the number of series that reported. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'. 'none' skips the aggregation and returns one series per label set, at most 100, using each series' last sample per bucket; it cannot be combined with 'groupBy'.\n\n\* `none` - none\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"
+ ),
+ rangeFunction: zod
+ .union([
+ zod.enum(['rate', 'increase']).describe('\* `rate` - rate\n\* `increase` - increase'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.\n\n\* `rate` - rate\n\* `increase` - increase"
),
quantile: zod
.number()
@@ -302,6 +311,7 @@ export const MetricsQueryCreateBody = () => zod.object({
),
aggregation: zod
.enum([
+ 'none',
'sum',
'avg',
'count',
@@ -313,11 +323,20 @@ export const MetricsQueryCreateBody = () => zod.object({
'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'
+ '\* `none` - none\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'
)
.default(metricsQueryCreateBodyQueryOneClausesItemAggregationDefault)
.describe(
- 'Aggregation applied per time bucket; same semantics as the top-level aggregation.\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'
+ 'Aggregation applied per time bucket; same semantics as the top-level aggregation.\n\n\* `none` - none\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'
+ ),
+ rangeFunction: zod
+ .union([
+ zod.enum(['rate', 'increase']).describe('\* `rate` - rate\n\* `increase` - increase'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Counter-aware transform applied to each series before the aggregation: 'rate' (per-second) or 'increase'. Combine with 'none' to get one rate line per series. Do not combine with the 'rate' or 'increase' aggregations.\n\n\* `rate` - rate\n\* `increase` - increase"
),
quantile: zod
.number()