Skip to content

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

feat(metrics): add dashboard panel foundation (schema, reduce, units, thresholds) (#99302)

Daniel Viscad968388d8722
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 37ceaf709ec8..c3c6e7dccd72 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -37972,15 +37972,44 @@
},
"type": "array"
},
+ "legendCalcs": {
+ "description": "Time-series panels only: which reducers the legend table shows. Empty means no legend calcs.",
+ "items": {
+ "$ref": "#/definitions/MetricsReducer"
+ },
+ "type": "array"
+ },
+ "nullMode": {
+ "$ref": "#/definitions/MetricsNullMode",
+ "default": "gap",
+ "description": "How a null bucket renders on a time-series chart."
+ },
+ "reduce": {
+ "$ref": "#/definitions/MetricsReducer",
+ "default": "last",
+ "description": "How scalar panels and legend calcs collapse a series to one number."
+ },
"statSummary": {
"$ref": "#/definitions/MetricsStatSummary",
"default": "latest",
+ "deprecated": "Use `reduce`.",
"description": "`stat` display only: which summary the headline value shows."
},
+ "thresholds": {
+ "description": "Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter.",
+ "items": {
+ "$ref": "#/definitions/MetricsThreshold"
+ },
+ "type": "array"
+ },
"type": {
"$ref": "#/definitions/MetricsDisplayType",
"default": "line"
},
+ "unit": {
+ "description": "UCUM unit string as OTel writes it, e.g. \"By\", \"ms\", \"%\". Defaults from the response unit.",
+ "type": "string"
+ },
"yAxis": {
"$ref": "#/definitions/MetricsYAxisSettings"
}
@@ -37989,13 +38018,18 @@
},
"MetricsDisplayType": {
"description": "How a metrics result is charted. `stat` is a single headline value plus sparkline, not a time series.",
- "enum": ["line", "area", "bar", "stat"],
+ "enum": ["line", "area", "bar", "stat", "gauge", "bargauge", "table", "heatmap"],
"type": "string"
},
"MetricsFilterOp": {
"enum": ["eq", "neq", "regex", "not_regex"],
"type": "string"
},
+ "MetricsNullMode": {
+ "description": "How a null bucket renders on a time-series chart.",
+ "enum": ["gap", "zero", "connect"],
+ "type": "string"
+ },
"MetricsOtelType": {
"description": "OTel metric type; matches what ingest writes to `metric_type`",
"enum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],
@@ -38125,7 +38159,8 @@
"type": "string"
},
"value": {
- "type": "number"
+ "description": "The bucket's aggregate; null when it isn't representable (a gap).",
+ "type": ["number", "null"]
}
},
"required": ["time", "value"],
@@ -38218,16 +38253,42 @@
"$ref": "#/definitions/MetricsQueryPoint"
},
"type": "array"
+ },
+ "unit": {
+ "description": "UCUM unit of the metric as ingested, e.g. \"By\", \"ms\", \"1\". Empty when the SDK did not set one.",
+ "type": "string"
}
},
"required": ["labels", "points"],
"type": "object"
},
+ "MetricsReducer": {
+ "description": "How a series collapses to one number for the scalar panels and legend calcs.",
+ "enum": ["last", "mean", "min", "max", "sum", "delta"],
+ "type": "string"
+ },
"MetricsStatSummary": {
+ "deprecated": "Use `MetricsDisplaySettings.reduce`. Kept so saved insights keep working.",
"description": "Which summary the `stat` display's headline value shows.",
"enum": ["latest", "average", "total"],
"type": "string"
},
+ "MetricsThreshold": {
+ "additionalProperties": false,
+ "description": "A threshold band: `color` applies from `value` up to the next step.",
+ "properties": {
+ "color": {
+ "description": "A named color token (e.g. \"green\", \"red\"), never raw hex, so light and dark themes both work.",
+ "type": "string"
+ },
+ "value": {
+ "description": "Lower bound of this band. The lowest step is the base color below every other step.",
+ "type": "number"
+ }
+ },
+ "required": ["value", "color"],
+ "type": "object"
+ },
"MetricsYAxisSettings": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 9315bfe104a1..0cd31dbd73a9 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4656,7 +4656,8 @@ export interface MetricsQueryClause {
export interface MetricsQueryPoint {
/** Bucket start, ISO 8601 */
time: string
- value: number
+ /** The bucket's aggregate; null when it isn't representable (a gap). */
+ value: number | null
}
export interface MetricsQuerySeries {
@@ -4666,6 +4667,8 @@ export interface MetricsQuerySeries {
metricName?: string
/** Clause alias that produced this series (`formula` for the formula result) */
clause?: string
+ /** UCUM unit of the metric as ingested, e.g. "By", "ms", "1". Empty when the SDK did not set one. */
+ unit?: string
}
export interface MetricsQueryResponse extends AnalyticsQueryResponseBase {
@@ -4674,15 +4677,30 @@ export interface MetricsQueryResponse extends AnalyticsQueryResponseBase {
export type CachedMetricsQueryResponse = CachedQueryResponse<MetricsQueryResponse>
/** How a metrics result is charted. `stat` is a single headline value plus sparkline, not a time series. */
-export type MetricsDisplayType = 'line' | 'area' | 'bar' | 'stat'
+export type MetricsDisplayType = 'line' | 'area' | 'bar' | 'stat' | 'gauge' | 'bargauge' | 'table' | 'heatmap'
/** Matches quill's `YAxisConfig.scale` verbatim, so no vocabulary translation is needed.
* Deliberately not `YAxisSettings['scale']` ('logarithmic') or `TrendsFilter['yAxisScaleType']` ('log10'). */
export type MetricsAxisScale = 'linear' | 'log'
-/** Which summary the `stat` display's headline value shows. */
+/** Which summary the `stat` display's headline value shows.
+ * @deprecated Use `MetricsDisplaySettings.reduce`. Kept so saved insights keep working. */
export type MetricsStatSummary = 'latest' | 'average' | 'total'
+/** How a series collapses to one number for the scalar panels and legend calcs. */
+export type MetricsReducer = 'last' | 'mean' | 'min' | 'max' | 'sum' | 'delta'
+
+/** A threshold band: `color` applies from `value` up to the next step. */
+export interface MetricsThreshold {
+ /** Lower bound of this band. The lowest step is the base color below every other step. */
+ value: number
+ /** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
+ color: string
+}
+
+/** How a null bucket renders on a time-series chart. */
+export type MetricsNullMode = 'gap' | 'zero' | 'connect'
+
export interface MetricsYAxisSettings {
/** @default linear */
scale?: MetricsAxisScale
@@ -4705,8 +4723,21 @@ export interface MetricsDisplaySettings {
goalLines?: GoalLine[]
yAxis?: MetricsYAxisSettings
/** `stat` display only: which summary the headline value shows.
- * @default latest */
+ * @default latest
+ * @deprecated Use `reduce`. */
statSummary?: MetricsStatSummary
+ /** How scalar panels and legend calcs collapse a series to one number.
+ * @default last */
+ reduce?: MetricsReducer
+ /** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
+ unit?: string
+ /** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
+ thresholds?: MetricsThreshold[]
+ /** How a null bucket renders on a time-series chart.
+ * @default gap */
+ nullMode?: MetricsNullMode
+ /** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
+ legendCalcs?: MetricsReducer[]
}
export interface MetricsQuery extends DataNode<MetricsQueryResponse> {
diff --git a/posthog/schema.py b/posthog/schema.py
index 72ac035a14a3..80b61b575bd4 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -194,7 +194,9 @@ from posthog.schema_enums import (
MetricsAxisScale as MetricsAxisScale,
MetricsDisplayType as MetricsDisplayType,
MetricsFilterOp as MetricsFilterOp,
+ MetricsNullMode as MetricsNullMode,
MetricsOtelType as MetricsOtelType,
+ MetricsReducer as MetricsReducer,
MetricsStatSummary as MetricsStatSummary,
MetricSummary as MetricSummary,
MultipleBreakdownType as MultipleBreakdownType,
@@ -2343,7 +2345,10 @@ class MetricsQueryPoint(BaseModel):
extra="forbid",
)
time: str = Field(..., description="Bucket start, ISO 8601")
- value: float
+ value: float | None = Field(
+ ...,
+ description="The bucket's aggregate; null when it isn't representable (a gap).",
+ )
class MetricsQuerySeries(BaseModel):
@@ -2360,6 +2365,24 @@ class MetricsQuerySeries(BaseModel):
)
metricName: str | None = None
points: list[MetricsQueryPoint]
+ unit: str | None = Field(
+ default=None,
+ description=('UCUM unit of the metric as ingested, e.g. "By", "ms", "1". Empty when the SDK did not set one.'),
+ )
+
+
+class MetricsThreshold(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ color: str = Field(
+ ...,
+ description=('A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work.'),
+ )
+ value: float = Field(
+ ...,
+ description=("Lower bound of this band. The lowest step is the base color below every other step."),
+ )
class MetricsYAxisSettings(BaseModel):
@@ -6247,11 +6270,33 @@ class MetricsDisplaySettings(BaseModel):
extra="forbid",
)
goalLines: list[GoalLine] | None = None
+ legendCalcs: list[MetricsReducer] | None = Field(
+ default=None,
+ description=("Time-series panels only: which reducers the legend table shows. Empty means no legend calcs."),
+ )
+ nullMode: MetricsNullMode | None = Field(
+ default=MetricsNullMode.GAP,
+ description="How a null bucket renders on a time-series chart.",
+ )
+ reduce: MetricsReducer | None = Field(
+ default=MetricsReducer.LAST,
+ description=("How scalar panels and legend calcs collapse a series to one number."),
+ )
statSummary: MetricsStatSummary | None = Field(
default=MetricsStatSummary.LATEST,
description="`stat` display only: which summary the headline value shows.",
)
+ thresholds: list[MetricsThreshold] | None = Field(
+ default=None,
+ description=(
+ "Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter."
+ ),
+ )
type: MetricsDisplayType | None = MetricsDisplayType.LINE
+ unit: str | None = Field(
+ default=None,
+ description=('UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit.'),
+ )
yAxis: MetricsYAxisSettings | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 3d4689a97fdf..92c24ea2f9aa 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3347,6 +3347,10 @@ class MetricsDisplayType(StrEnum):
AREA = "area"
BAR = "bar"
STAT = "stat"
+ GAUGE = "gauge"
+ BARGAUGE = "bargauge"
+ TABLE = "table"
+ HEATMAP = "heatmap"
class MetricsFilterOp(StrEnum):
@@ -3356,6 +3360,12 @@ class MetricsFilterOp(StrEnum):
NOT_REGEX = "not_regex"
+class MetricsNullMode(StrEnum):
+ GAP = "gap"
+ ZERO = "zero"
+ CONNECT = "connect"
+
+
class MetricsOtelType(StrEnum):
GAUGE = "gauge"
SUM = "sum"
@@ -3364,6 +3374,15 @@ class MetricsOtelType(StrEnum):
SUMMARY = "summary"
+class MetricsReducer(StrEnum):
+ LAST = "last"
+ MEAN = "mean"
+ MIN = "min"
+ MAX = "max"
+ SUM = "sum"
+ DELTA = "delta"
+
+
class MetricsStatSummary(StrEnum):
LATEST = "latest"
AVERAGE = "average"
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 01ab5706cf0e..9a45e9c394ae 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -10,6 +10,13 @@ import datetime as dt
from collections.abc import Sequence
from typing import Any
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
from products.error_tracking.backend.facade.api import list_spike_events
@@ -61,21 +68,77 @@ def team_has_metrics(team: Team) -> bool:
return _team_has_metrics(team)
+def _units_by_fingerprint(team: Team, metric_names: set[str]) -> dict[int, str]:
+ """One ClickHouse lookup of the ingested UCUM unit per physical series,
+ keyed by `series_fingerprint` and read from `metric_series` (the same table
+ the catalog reads). Per-fingerprint rather than per-name so a metric whose
+ series disagree on the unit never lends one series' unit to another.
+ Returns only series with a non-empty unit; a series with no unit is simply
+ absent, so callers use `.get(fingerprint)`. Kept separate from the
+ per-series data query so the unit costs one small grouped scan regardless
+ of how many series a query returns."""
+ if not metric_names:
+ return {}
+ names = sorted(metric_names)
+ query = parse_select(
+ """
+ SELECT series_fingerprint, any(unit) AS unit
+ FROM posthog.metric_series
+ WHERE metric_name IN {names}
+ GROUP BY series_fingerprint
+ """,
+ placeholders={"names": ast.Tuple(exprs=[ast.Constant(value=n) for n in names])},
+ )
+ response = execute_hogql_query(
+ query_type="MetricUnitsLookup",
+ query=query,
+ team=team,
+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ # Same byte cap as the data queries: without it a high-cardinality name set
+ # would make this metadata scan the most expensive read of the request.
+ 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(row[1]) for row in (response.results or []) if row[1]}
+
+
+def _unit_for_fingerprints(fingerprints: set[int], units_by_fingerprint: dict[int, str]) -> str | None:
+ """The unit of one output series, resolved from the physical series it
+ aggregated. The unit only applies when every contributing series carries
+ the same one — a disagreement, or a series with no unit at all, means the
+ merge has no correct single unit, so it carries none."""
+ units = {units_by_fingerprint.get(fp) for fp in fingerprints}
+ if len(units) != 1:
+ return None
+ (unit,) = units
+ return unit
+
+
# 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
def _assemble_series(
- rows: list[dict[str, Any]], *, metric_name: str, clause_name: str, grid: list[str]
+ rows: list[dict[str, Any]],
+ *,
+ metric_name: str,
+ clause_name: str,
+ grid: list[str],
+ units_by_fingerprint: dict[int, str],
) -> 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]] = {}
for row in rows:
key = tuple(sorted(row["labels"].items()))
by_labels.setdefault(key, {})[row["time"]] = row["value"]
+ fingerprints_by_labels.setdefault(key, set()).update(row["series_fingerprints"])
# Rank and truncate on the sparse values BEFORE zero-filling, so a
# high-cardinality group-by never materializes label_sets x grid points
@@ -90,6 +153,7 @@ def _assemble_series(
points=tuple(MetricPoint(time=time, value=values.get(time, 0.0)) for time in grid),
metric_name=metric_name,
clause=clause_name,
+ unit=_unit_for_fingerprints(fingerprints_by_labels[key], units_by_fingerprint),
)
for key, values in ranked[:MAX_SERIES_PER_CLAUSE]
]
@@ -204,9 +268,21 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
metric_name = None if formula_node_checked is not None else request.clauses[0].metric_name
return [MetricSeries(labels={}, points=(), metric_name=metric_name, clause=empty_clause)]
+ # A formula combines clauses (possibly of different units), so its series
+ # carry no unit and the unit lookup is skipped entirely.
+ units_by_fingerprint = (
+ {}
+ if formula_node_checked is not None
+ else _units_by_fingerprint(team, {clause.metric_name for clause in request.clauses})
+ )
+
series_by_clause = {
clause.name: _assemble_series(
- rows_by_clause[clause.name], metric_name=clause.metric_name, clause_name=clause.name, grid=grid
+ rows_by_clause[clause.name],
+ metric_name=clause.metric_name,
+ clause_name=clause.name,
+ grid=grid,
+ units_by_fingerprint=units_by_fingerprint,
)
for clause in request.clauses
}
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index e773f15763ef..38967707adde 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -138,6 +138,9 @@ class MetricSeries:
points: tuple[MetricPoint, ...]
metric_name: str | None = None
clause: str | None = None
+ # UCUM unit of the metric as ingested (e.g. "By", "ms"). Empty when the SDK
+ # did not set one. Set by `run_metric_query`, not by callers.
+ unit: str | None = None
@dataclass(frozen=True, slots=True)
diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.py
index 602f6c9353bc..590d05475125 100644
--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py
+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py
@@ -158,6 +158,7 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):
points=[MetricsQueryPoint(time=p.time, value=p.value) for p in s.points],
metricName=s.metric_name,
clause=s.clause,
+ unit=s.unit or None,
)
for s in series
]
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 47dc7c186c2d..108a04e157b2 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -430,7 +430,11 @@ class MetricQueryRunner:
self.metric_type = metric_type
def run(self) -> list[dict[str, Any]]:
- """Return bucketed rows with time, value, and group labels."""
+ """Bucketed rows: `{"time", "value", "labels", "series_fingerprints"}`.
+ `labels` carries one entry per group_by key (always `{}` without
+ group_by). `series_fingerprints` lists the physical series the bucket
+ aggregated, so the facade can resolve per-series attributes (unit)
+ honestly even when the bucket merged several series."""
if self.aggregation == "histogram_quantile":
return self._run_histogram_quantile()
if self.aggregation in ("rate", "increase"):
@@ -455,6 +459,7 @@ class MetricQueryRunner:
"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],
"value": _finite_or_none(row[1 + group_count]),
"labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},
+ "series_fingerprints": row[2 + group_count],
}
)
return rows
@@ -492,6 +497,7 @@ class MetricQueryRunner:
"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],
"value": _finite_or_none(_histogram_quantile(self.quantile, bounds, counts)),
"labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},
+ "series_fingerprints": row[4 + group_count],
}
)
return rows
@@ -546,7 +552,8 @@ class MetricQueryRunner:
"""
SELECT
time AS time,
- {aggregation} AS value
+ {aggregation} AS value,
+ groupUniqArray(s.series_fingerprint) AS series_fingerprints
FROM (
SELECT
toStartOfInterval(timestamp, {interval}) AS time,
@@ -591,7 +598,8 @@ class MetricQueryRunner:
"""
SELECT
toStartOfInterval(sample_timestamp, {interval}) AS time,
- sum(contribution) / {divisor} AS value
+ sum(contribution) / {divisor} AS value,
+ groupUniqArray(s.series_fingerprint) AS series_fingerprints
FROM (
SELECT
timestamp AS sample_timestamp,
@@ -650,7 +658,8 @@ class MetricQueryRunner:
toStartOfInterval(sample_timestamp, {interval}) AS time,
any(histogram_bounds) AS bounds,
groupUniqArray(histogram_bounds) AS bounds_variants,
- sumForEach(contribution_counts) AS counts
+ sumForEach(contribution_counts) AS counts,
+ groupUniqArray(s.series_fingerprint) AS series_fingerprints
FROM (
SELECT
timestamp AS sample_timestamp,
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 76aa13fb6a45..d59db705c736 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -580,6 +580,171 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(series[0].clause, "a")
self.assertEqual(sum(p.value for p in series[0].points), 4.0)
+ def test_attaches_ingested_unit_to_series(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertEqual(series[0].unit, "ms")
+
+ def test_inconsistent_units_across_merged_series_leave_unit_unset(self):
+ """An ungrouped query merges series; if they disagree on the unit there
+ is no correct single unit, so the series carries none rather than an
+ arbitrary one."""
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ service_name="svc-a",
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="s",
+ points=[(anchor - dt.timedelta(minutes=10), 2.5)],
+ service_name="svc-b",
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertIsNone(series[0].unit)
+
+ def test_mixed_unit_and_unitless_merge_leaves_unit_unset(self):
+ """A unitless series merged with a unit-carrying one is still a mixed
+ result: the unit only applies when every contributing series agrees."""
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ service_name="svc-a",
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=10), 2.5)],
+ service_name="svc-b",
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertIsNone(series[0].unit)
+
+ def test_consistent_units_across_merged_series_attach(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ service_name="svc-a",
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 2.5)],
+ service_name="svc-b",
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertEqual(series[0].unit, "ms")
+
+ def test_grouped_series_attach_their_own_unit(self):
+ """Grouped series each get the unit of their underlying series, so two
+ groups of one metric can carry different units."""
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ labels={"pod": "a"},
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="s",
+ points=[(anchor - dt.timedelta(minutes=10), 2.5)],
+ labels={"pod": "b"},
+ )
+
+ series = run_metric_query(
+ team=self.team,
+ request=self._request(
+ clauses=(
+ MetricQueryClause(
+ name="a",
+ metric_name="m1",
+ aggregation=MetricAggregation.SUM,
+ group_by=(MetricGroupBy(key="pod"),),
+ ),
+ )
+ ),
+ )
+
+ self.assertEqual(len(series), 2)
+ by_pod = {s.labels["pod"]: s for s in series}
+ self.assertEqual(by_pod["a"].unit, "ms")
+ self.assertEqual(by_pod["b"].unit, "s")
+
+ def test_series_without_unit_has_none(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5)],
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertIsNone(series[0].unit)
+
+ def test_formula_series_carries_no_unit(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ unit="ms",
+ points=[(anchor - dt.timedelta(minutes=10), 2.0)],
+ )
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m2",
+ unit="s",
+ points=[(anchor - dt.timedelta(minutes=10), 4.0)],
+ )
+
+ series = run_metric_query(
+ team=self.team,
+ request=self._request(
+ clauses=(
+ MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.SUM),
+ MetricQueryClause(name="b", metric_name="m2", aggregation=MetricAggregation.SUM),
+ ),
+ formula="a / b",
+ ),
+ )
+
+ self.assertEqual(len(series), 1)
+ self.assertEqual(series[0].clause, "formula")
+ self.assertIsNone(series[0].unit)
+
def test_quantile_095_maps_to_p95(self):
anchor = timezone.now().replace(microsecond=0)
seed_metric(team_id=self.team.id, metric_name="m1", points=[(anchor - dt.timedelta(minutes=10), 5.0)])
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index 35f8f05c3dbe..db7a71372fe0 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -107,8 +107,8 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
by_container = {series.labels.get("container"): series for series in response.results}
assert set(by_container) == {"capture", "ingestion"}
- assert max(point.value for point in by_container["capture"].points) == 5.0
- assert max(point.value for point in by_container["ingestion"].points) == 7.0
+ assert max(point.value for point in by_container["capture"].points if point.value is not None) == 5.0
+ assert max(point.value for point in by_container["ingestion"].points if point.value is not None) == 7.0
def test_generic_query_endpoint_accepts_metrics_query(self) -> None:
response = self.client.post(
diff --git a/products/metrics/frontend/panels/metricsReduce.test.ts b/products/metrics/frontend/panels/metricsReduce.test.ts
new file mode 100644
index 000000000000..580d8ef7cace
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsReduce.test.ts
@@ -0,0 +1,89 @@
+import type { MetricsQueryPoint, MetricsQuerySeries } from '~/queries/schema/schema-general'
+
+import { flattenSeriesRows, reduceSeries } from './metricsReduce'
+
+// The schema types `value` as `number`, but the backend sends `null` for a
+// non-representable bucket (the facade's `MetricPoint.value` is `float | None`).
+// PR for null gaps widens the schema type; until then the tests cast to the
+// declared shape while exercising the null path the runtime actually produces.
+const points = (values: (number | null)[]): MetricsQueryPoint[] =>
+ values.map((value, i) => ({ time: `2026-09-10T00:0${i}:00Z`, value }) as MetricsQueryPoint)
+
+describe('metricsReduce', () => {
+ describe('reduceSeries', () => {
+ it('returns null for an empty series', () => {
+ expect(reduceSeries([], 'last')).toBeNull()
+ expect(reduceSeries([], 'mean')).toBeNull()
+ })
+
+ it('returns null when every point is null', () => {
+ expect(reduceSeries(points([null, null, null]), 'last')).toBeNull()
+ expect(reduceSeries(points([null, null]), 'sum')).toBeNull()
+ })
+
+ it('last ignores trailing nulls', () => {
+ expect(reduceSeries(points([1, 2, null]), 'last')).toBe(2)
+ })
+
+ it('mean skips nulls rather than counting them as zero', () => {
+ expect(reduceSeries(points([1, null, 3]), 'mean')).toBe(2)
+ })
+
+ it('min and max ignore nulls', () => {
+ expect(reduceSeries(points([5, null, 2, 8]), 'min')).toBe(2)
+ expect(reduceSeries(points([5, null, 2, 8]), 'max')).toBe(8)
+ })
+
+ it('sum ignores nulls', () => {
+ expect(reduceSeries(points([1, null, 2, 3]), 'sum')).toBe(6)
+ })
+
+ it('delta is last non-null minus first non-null', () => {
+ expect(reduceSeries(points([null, 2, 5, 9, null]), 'delta')).toBe(7)
+ })
+
+ it('delta of a single point is zero', () => {
+ expect(reduceSeries(points([null, 4, null]), 'delta')).toBe(0)
+ })
+ })
+
+ describe('flattenSeriesRows', () => {
+ const series = (
+ labels: Record<string, string>,
+ values: (number | null)[],
+ metricName?: string
+ ): MetricsQuerySeries => ({
+ labels,
+ points: points(values),
+ metricName,
+ })
+
+ it('flattens labels into the row and computes each reducer', () => {
+ const rows = flattenSeriesRows([series({ service: 'api' }, [1, 2, 3], 'cpu')], ['last', 'max', 'sum'])
+ expect(rows).toHaveLength(1)
+ expect(rows[0].labels).toEqual({ service: 'api' })
+ expect(rows[0].metricName).toBe('cpu')
+ expect(rows[0].values).toEqual({ last: 3, max: 3, sum: 6 })
+ })
+
+ it('keeps a null value for a reducer with no data', () => {
+ const rows = flattenSeriesRows([series({}, [null])], ['last'])
+ expect(rows[0].values.last).toBeNull()
+ })
+
+ it('handles zero label keys (ungrouped)', () => {
+ const rows = flattenSeriesRows([series({}, [7])], ['last'])
+ expect(rows[0].labels).toEqual({})
+ })
+
+ it('preserves the source series for drill-down', () => {
+ const s = series({ pod: 'p1' }, [1, 2])
+ expect(flattenSeriesRows([s], ['last'])[0].series).toBe(s)
+ })
+
+ it('produces one row per series', () => {
+ const rows = flattenSeriesRows([series({ a: '1' }, [1]), series({ a: '2' }, [2])], ['last'])
+ expect(rows).toHaveLength(2)
+ })
+ })
+})
diff --git a/products/metrics/frontend/panels/metricsReduce.ts b/products/metrics/frontend/panels/metricsReduce.ts
new file mode 100644
index 000000000000..f4841063609e
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsReduce.ts
@@ -0,0 +1,47 @@
+import type { MetricsQueryPoint, MetricsQuerySeries, MetricsReducer } from '~/queries/schema/schema-general'
+
+/** The reducers a caller may ask for. `reduceSeries` returns `null` when a series has no
+ * non-null point, so a panel can show "No data" instead of a misleading 0. */
+export function reduceSeries(points: MetricsQueryPoint[], reducer: MetricsReducer): number | null {
+ const values = points.map((p) => p.value).filter((v): v is number => v !== null && v !== undefined)
+ if (values.length === 0) {
+ return null
+ }
+ switch (reducer) {
+ case 'last':
+ return values[values.length - 1]
+ case 'mean':
+ return values.reduce((a, b) => a + b, 0) / values.length
+ case 'min':
+ return Math.min(...values)
+ case 'max':
+ return Math.max(...values)
+ case 'sum':
+ return values.reduce((a, b) => a + b, 0)
+ case 'delta':
+ return values[values.length - 1] - values[0]
+ }
+}
+
+/** One row of a flattened series: the label columns plus one column per reducer.
+ * The table panel, the bar gauge, and the time-series legend table all read this shape. */
+export interface MetricsSeriesRow {
+ /** The series' label set, e.g. { service: "api", pod: "api-1" }. Empty for an ungrouped series. */
+ labels: Record<string, string>
+ /** The series' metric name, used as the row title for ungrouped single-series results. */
+ metricName?: string
+ /** The reduced value per requested reducer, keyed by reducer name. `null` means no
+ * data; a reducer the caller did not ask for is absent, so the type stays Partial. */
+ values: Partial<Record<MetricsReducer, number | null>>
+ /** The raw series, kept so a row can link back to its points (sparkline, drill-down). */
+ series: MetricsQuerySeries
+}
+
+export function flattenSeriesRows(series: MetricsQuerySeries[], reducers: MetricsReducer[]): MetricsSeriesRow[] {
+ return series.map((s) => ({
+ labels: s.labels,
+ metricName: s.metricName ?? undefined,
+ values: Object.fromEntries(reducers.map((r) => [r, reduceSeries(s.points, r)])),
+ series: s,
+ }))
+}
diff --git a/products/metrics/frontend/panels/metricsThresholds.test.ts b/products/metrics/frontend/panels/metricsThresholds.test.ts
new file mode 100644
index 000000000000..fd5a36e4a716
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsThresholds.test.ts
@@ -0,0 +1,41 @@
+import { thresholdColor } from './metricsThresholds'
+
+const FALLBACK = 'data-color-1'
+
+describe('thresholdColor', () => {
+ it('returns fallback when value is null', () => {
+ expect(thresholdColor(null, [{ value: 0, color: 'green' }], FALLBACK)).toBe(FALLBACK)
+ })
+
+ it('returns fallback when there are no thresholds', () => {
+ expect(thresholdColor(5, undefined, FALLBACK)).toBe(FALLBACK)
+ expect(thresholdColor(5, [], FALLBACK)).toBe(FALLBACK)
+ })
+
+ it('uses the base color below the first step', () => {
+ const t = [{ value: 80, color: 'red' }]
+ expect(thresholdColor(50, t, FALLBACK)).toBe('red')
+ })
+
+ it('picks the highest step the value meets or exceeds', () => {
+ const t = [
+ { value: 0, color: 'green' },
+ { value: 70, color: 'warning' },
+ { value: 90, color: 'danger' },
+ ]
+ expect(thresholdColor(10, t, FALLBACK)).toBe('green')
+ expect(thresholdColor(70, t, FALLBACK)).toBe('warning')
+ expect(thresholdColor(85, t, FALLBACK)).toBe('warning')
+ expect(thresholdColor(95, t, FALLBACK)).toBe('danger')
+ })
+
+ it('does not depend on entry order', () => {
+ const t = [
+ { value: 90, color: 'danger' },
+ { value: 0, color: 'green' },
+ { value: 70, color: 'warning' },
+ ]
+ expect(thresholdColor(85, t, FALLBACK)).toBe('warning')
+ expect(thresholdColor(10, t, FALLBACK)).toBe('green')
+ })
+})
diff --git a/products/metrics/frontend/panels/metricsThresholds.ts b/products/metrics/frontend/panels/metricsThresholds.ts
new file mode 100644
index 000000000000..4a6880ea3289
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsThresholds.ts
@@ -0,0 +1,24 @@
+import type { MetricsThreshold } from '~/queries/schema/schema-general'
+
+/** Resolve the threshold color for a value. Thresholds are sorted by `value` at read
+ * time, so the order a user enters them does not matter. The lowest step is the base
+ * color below every other step; `null` (no data) returns `fallback`. */
+export function thresholdColor(
+ value: number | null,
+ thresholds: MetricsThreshold[] | undefined,
+ fallback: string
+): string {
+ if (value === null || !thresholds || thresholds.length === 0) {
+ return fallback
+ }
+ const sorted = [...thresholds].sort((a, b) => a.value - b.value)
+ let color = sorted[0].color
+ for (const step of sorted) {
+ if (value >= step.value) {
+ color = step.color
+ } else {
+ break
+ }
+ }
+ return color
+}
diff --git a/products/metrics/frontend/panels/metricsUnits.test.ts b/products/metrics/frontend/panels/metricsUnits.test.ts
new file mode 100644
index 000000000000..18aaa30e8a8e
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsUnits.test.ts
@@ -0,0 +1,60 @@
+import { formatMetricValue, unitAxisFormatter } from './metricsUnits'
+
+describe('metricsUnits', () => {
+ describe('formatMetricValue', () => {
+ it.each([
+ // no unit
+ [1234, undefined, '1.23K'],
+ [0, undefined, '0'],
+ // bytes (binary)
+ [0, 'By', '0 B'],
+ [512, 'By', '512 B'],
+ [1024, 'By', '1 KiB'],
+ [1536, 'By', '1.5 KiB'],
+ [1024 ** 2, 'By', '1 MiB'],
+ [2.5 * 1024 ** 3, 'By', '2.5 GiB'],
+ // binary-prefixed UCUM
+ [2, 'KiBy', '2 KiB'],
+ [3, 'MiBy', '3 MiB'],
+ // seconds
+ [2.5, 's', '2.5 s'],
+ [0.34, 's', '340 ms'],
+ [0.0005, 's', '500 µs'],
+ [0.0000002, 's', '200 ns'],
+ [340, 'ms', '340 ms'],
+ [1500, 'ms', '1.5 s'],
+ [250000, 'us', '250 ms'],
+ // percent
+ [42.5, '%', '42.5%'],
+ // UCUM "1" is dimensionless, not necessarily a ratio: keep the value
+ [0.12, '1', '0.12'],
+ [1, '1', '1'],
+ [12, '1', '12'],
+ // rates
+ [88, '1/s', '88/s'],
+ [88, '{request}/s', '88 request/s'],
+ [1500, '{message}/s', '1.5K message/s'],
+ // unknown unit falls back to compact + suffix
+ [1234, 'widgets', '1.23K widgets'],
+ ])('formats %s with unit %s as %s', (value, unit, expected) => {
+ expect(formatMetricValue(value, unit)).toBe(expected)
+ })
+
+ it('handles negative values', () => {
+ expect(formatMetricValue(-1024, 'By')).toBe('-1 KiB')
+ expect(formatMetricValue(-0.5, '1')).toBe('-0.5')
+ })
+ })
+
+ describe('unitAxisFormatter', () => {
+ it('binds the unit into a reusable formatter', () => {
+ const fmt = unitAxisFormatter('ms')
+ expect(fmt(340)).toBe('340 ms')
+ expect(fmt(2000)).toBe('2 s')
+ })
+
+ it('falls back to compact with no unit', () => {
+ expect(unitAxisFormatter(undefined)(1500)).toBe('1.5K')
+ })
+ })
+})
diff --git a/products/metrics/frontend/panels/metricsUnits.ts b/products/metrics/frontend/panels/metricsUnits.ts
new file mode 100644
index 000000000000..7cc23e89b31f
--- /dev/null
+++ b/products/metrics/frontend/panels/metricsUnits.ts
@@ -0,0 +1,83 @@
+/** UCUM unit formatting for metric values, as OTel writes the `unit` field.
+ *
+ * The mapping covers the units the OTel semantic conventions emit. An unknown
+ * unit falls back to a compact number with the unit string appended, so a new
+ * unit never breaks rendering — it just reads less cleanly until it is added here. */
+
+const compact = (value: number, fractionDigits = 2): string =>
+ new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: fractionDigits }).format(value)
+
+const bytes = (value: number, base: 1000 | 1024): string => {
+ const units = base === 1024 ? ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'] : ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
+ if (value === 0) {
+ return '0 ' + units[0]
+ }
+ const magnitude = Math.min(Math.floor(Math.log(Math.abs(value)) / Math.log(base)), units.length - 1)
+ const scaled = value / Math.pow(base, Math.max(magnitude, 0))
+ return `${compact(scaled)} ${units[Math.max(magnitude, 0)]}`
+}
+
+const seconds = (value: number): string => {
+ const abs = Math.abs(value)
+ if (abs >= 1) {
+ return `${compact(value)} s`
+ }
+ if (abs >= 1e-3) {
+ return `${compact(value * 1e3)} ms`
+ }
+ if (abs >= 1e-6) {
+ return `${compact(value * 1e6)} µs`
+ }
+ return `${compact(value * 1e9)} ns`
+}
+
+/** Format one metric value with a UCUM unit. `unit` is the raw OTel string; `undefined`
+ * or an unknown unit falls back to a compact number. */
+export function formatMetricValue(value: number, unit: string | undefined): string {
+ if (!unit) {
+ return compact(value)
+ }
+ if (unit === 'By') {
+ return bytes(value, 1024)
+ }
+ if (unit === 'KiBy' || unit === 'MiBy' || unit === 'GiBy') {
+ // OTel sometimes prefixes a binary unit directly; normalise through bytes.
+ const factor = unit === 'KiBy' ? 1024 : unit === 'MiBy' ? 1024 ** 2 : 1024 ** 3
+ return bytes(value * factor, 1024)
+ }
+ if (unit === 's') {
+ return seconds(value)
+ }
+ if (unit === 'ms') {
+ return seconds(value / 1e3)
+ }
+ if (unit === 'us') {
+ return seconds(value / 1e6)
+ }
+ if (unit === 'ns') {
+ return seconds(value / 1e9)
+ }
+ if (unit === '%') {
+ return `${compact(value)}%`
+ }
+ if (unit === '1') {
+ // UCUM "one" means dimensionless, not necessarily a ratio — ingestion
+ // carries nothing that tells a ratio from any other unitless value,
+ // so multiplying by 100 would mislabel a legitimate measurement.
+ return compact(value)
+ }
+ if (unit === '1/s') {
+ return `${compact(value)}/s`
+ }
+ if (unit.endsWith('/s')) {
+ // "{request}/s", "{message}/s", etc. Show the count rate with the noun.
+ const noun = unit.slice(0, -2).replace(/[{}]/g, '')
+ return noun ? `${compact(value)} ${noun}/s` : `${compact(value)}/s`
+ }
+ return `${compact(value)} ${unit}`
+}
+
+/** An axis/tooltip formatter bound to a unit. */
+export function unitAxisFormatter(unit: string | undefined): (value: number) => string {
+ return (value: number) => formatMetricValue(value, unit)
+}
diff --git a/products/metrics/frontend/panels/registry.test.ts b/products/metrics/frontend/panels/registry.test.ts
new file mode 100644
index 000000000000..a6462ffaae1f
--- /dev/null
+++ b/products/metrics/frontend/panels/registry.test.ts
@@ -0,0 +1,60 @@
+import { METRICS_PANELS, resolvePanelType, resolveReducer, statSummaryToReduce } from './registry'
+
+describe('resolvePanelType', () => {
+ it('defaults to line when no display is set', () => {
+ expect(resolvePanelType(undefined)).toBe('line')
+ expect(resolvePanelType({})).toBe('line')
+ })
+
+ it('passes through a known type', () => {
+ expect(resolvePanelType({ type: 'stat' })).toBe('stat')
+ expect(resolvePanelType({ type: 'table' })).toBe('table')
+ expect(resolvePanelType({ type: 'heatmap' })).toBe('heatmap')
+ })
+
+ it('falls back to line for an unknown type', () => {
+ expect(resolvePanelType({ type: 'pie' as never })).toBe('line')
+ })
+
+ it('has a definition for every display type', () => {
+ for (const type of ['line', 'area', 'bar', 'stat', 'gauge', 'bargauge', 'table', 'heatmap'] as const) {
+ expect(METRICS_PANELS[type].label).toBeTruthy()
+ }
+ })
+
+ it('marks group-by-only panels', () => {
+ expect(METRICS_PANELS.bargauge.needsGroupBy).toBe(true)
+ expect(METRICS_PANELS.stat.needsGroupBy).toBeUndefined()
+ })
+
+ it('marks the histogram-only panel', () => {
+ expect(METRICS_PANELS.heatmap.needsHistogram).toBe(true)
+ })
+})
+
+describe('statSummaryToReduce', () => {
+ it('maps the deprecated values', () => {
+ expect(statSummaryToReduce('latest')).toBe('last')
+ expect(statSummaryToReduce('average')).toBe('mean')
+ expect(statSummaryToReduce('total')).toBe('sum')
+ })
+
+ it('defaults to last', () => {
+ expect(statSummaryToReduce(undefined)).toBe('last')
+ })
+})
+
+describe('resolveReducer', () => {
+ it('prefers reduce over statSummary', () => {
+ expect(resolveReducer({ reduce: 'max', statSummary: 'total' })).toBe('max')
+ })
+
+ it('falls back to statSummary', () => {
+ expect(resolveReducer({ statSummary: 'average' })).toBe('mean')
+ })
+
+ it('defaults to last', () => {
+ expect(resolveReducer({})).toBe('last')
+ expect(resolveReducer(undefined)).toBe('last')
+ })
+})
diff --git a/products/metrics/frontend/panels/registry.ts b/products/metrics/frontend/panels/registry.ts
new file mode 100644
index 000000000000..95fa5ac5ac7f
--- /dev/null
+++ b/products/metrics/frontend/panels/registry.ts
@@ -0,0 +1,63 @@
+import type { MetricsDisplaySettings, MetricsDisplayType } from '~/queries/schema/schema-general'
+
+import type { MetricsChartSeries } from '../components/metricsSeries'
+
+/** The props every metrics panel receives. `unit` is the resolved unit (display override,
+ * else the first series' ingested unit). A panel is a pure function of these props. */
+export interface MetricsPanelProps {
+ series: MetricsChartSeries[]
+ display: MetricsDisplaySettings
+ unit: string | undefined
+ fallbackName: string
+}
+
+export interface MetricsPanelDefinition {
+ /** Human label for the chart-type picker. */
+ label: string
+ /** The panel needs a `groupBy` to be meaningful; the picker disables it otherwise. */
+ needsGroupBy?: boolean
+ /** The panel needs a histogram metric; the picker disables it otherwise. */
+ needsHistogram?: boolean
+}
+
+/** Static metadata per panel type. The render components register themselves in
+ * `panelComponents.tsx` (kept separate so this module stays React-free and cheap to
+ * import from logic). The picker and the dispatcher both read this list, so adding a
+ * panel is one component file plus one entry here. */
+export const METRICS_PANELS: Record<MetricsDisplayType, MetricsPanelDefinition> = {
+ line: { label: 'Line' },
+ area: { label: 'Area' },
+ bar: { label: 'Bar' },
+ stat: { label: 'Stat' },
+ gauge: { label: 'Gauge' },
+ bargauge: { label: 'Bar gauge', needsGroupBy: true },
+ table: { label: 'Table' },
+ heatmap: { label: 'Heatmap', needsHistogram: true },
+}
+
+/** The display type to render for a query, falling back to `line` for an unknown or
+ * unrenderable type so an older or newer client never blanks a tile. */
+export function resolvePanelType(display: MetricsDisplaySettings | undefined): MetricsDisplayType {
+ const type = display?.type ?? 'line'
+ return type in METRICS_PANELS ? type : 'line'
+}
+
+/** Map the deprecated `statSummary` onto `reduce`. Saved insights keep working. */
+export function statSummaryToReduce(summary: 'latest' | 'average' | 'total' | undefined): 'last' | 'mean' | 'sum' {
+ switch (summary) {
+ case 'average':
+ return 'mean'
+ case 'total':
+ return 'sum'
+ default:
+ return 'last'
+ }
+}
+
+/** The reducer a panel should use: the explicit `reduce`, else the deprecated
+ * `statSummary`, else `last`. */
+export function resolveReducer(
+ display: MetricsDisplaySettings | undefined
+): 'last' | 'mean' | 'min' | 'max' | 'sum' | 'delta' {
+ return display?.reduce ?? statSummaryToReduce(display?.statSummary)
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dca799eac752..bf040cd4a33b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -46581,6 +46581,27 @@ export namespace Schemas {
quantile?: number | null;
}
+ export type MetricsReducer = typeof MetricsReducer[keyof typeof MetricsReducer];
+
+
+ export const MetricsReducer = {
+ Last: 'last',
+ Mean: 'mean',
+ Min: 'min',
+ Max: 'max',
+ Sum: 'sum',
+ Delta: 'delta',
+ } as const;
+
+ export type MetricsNullMode = typeof MetricsNullMode[keyof typeof MetricsNullMode];
+
+
+ export const MetricsNullMode = {
+ Gap: 'gap',
+ Zero: 'zero',
+ Connect: 'connect',
+ } as const;
+
export type MetricsStatSummary = typeof MetricsStatSummary[keyof typeof MetricsStatSummary];
@@ -46590,6 +46611,13 @@ export namespace Schemas {
Total: 'total',
} as const;
+ export interface MetricsThreshold {
+ /** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
+ color: string;
+ /** Lower bound of this band. The lowest step is the base color below every other step. */
+ value: number;
+ }
+
export type MetricsDisplayType = typeof MetricsDisplayType[keyof typeof MetricsDisplayType];
@@ -46598,6 +46626,10 @@ export namespace Schemas {
Area: 'area',
Bar: 'bar',
Stat: 'stat',
+ Gauge: 'gauge',
+ Bargauge: 'bargauge',
+ Table: 'table',
+ Heatmap: 'heatmap',
} as const;
export type MetricsAxisScale = typeof MetricsAxisScale[keyof typeof MetricsAxisScale];
@@ -46620,16 +46652,27 @@ export namespace Schemas {
export interface MetricsDisplaySettings {
goalLines?: GoalLine[] | null;
+ /** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
+ legendCalcs?: MetricsReducer[] | null;
+ /** How a null bucket renders on a time-series chart. */
+ nullMode?: MetricsNullMode | null;
+ /** How scalar panels and legend calcs collapse a series to one number. */
+ reduce?: MetricsReducer | null;
/** `stat` display only: which summary the headline value shows. */
statSummary?: MetricsStatSummary | null;
+ /** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
+ thresholds?: MetricsThreshold[] | null;
type?: MetricsDisplayType | null;
+ /** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
+ unit?: string | null;
yAxis?: MetricsYAxisSettings | null;
}
export interface MetricsQueryPoint {
/** Bucket start, ISO 8601 */
time: string;
- value: number;
+ /** The bucket's aggregate; null when it isn't representable (a gap). */
+ value: number | null;
}
/**
@@ -46644,6 +46687,8 @@ export namespace Schemas {
labels: MetricsQuerySeriesLabels;
metricName?: string | null;
points: MetricsQueryPoint[];
+ /** UCUM unit of the metric as ingested, e.g. "By", "ms", "1". Empty when the SDK did not set one. */
+ unit?: string | null;
}
export interface MetricsQueryResponse {