Skip to content

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

fix(metrics): show units on time series charts (#116669)

Daniel Viscaff445ec92a4e
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 55c8344bda93..11ae76534bce 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -39939,7 +39939,7 @@
"type": "array"
},
"unit": {
- "description": "UCUM unit of the metric as ingested, e.g. \"By\", \"ms\", \"1\". Empty when the SDK did not set one.",
+ "description": "UCUM unit of the returned values, e.g. \"By\", \"ms\", \"1/s\". It is the ingested unit, except that a count of series has no unit and a rate is per second. Empty when the values have no unit.",
"type": "string"
}
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a4111621b37e..4d341b76cc8d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4923,7 +4923,7 @@ 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. */
+ /** UCUM unit of the returned values, e.g. "By", "ms", "1/s". It is the ingested unit, except that a count of series has no unit and a rate is per second. Empty when the values have no unit. */
unit?: string
}
diff --git a/posthog/schema.py b/posthog/schema.py
index f84cbaebd265..f83615b15b5d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2734,7 +2734,11 @@ class MetricsQuerySeries(BaseModel):
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.'),
+ description=(
+ 'UCUM unit of the returned values, e.g. "By", "ms", "1/s". It is the'
+ " ingested unit, except that a count of series has no unit and a rate is"
+ " per second. Empty when the values have no unit."
+ ),
)
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index baca705697a2..068c85e87edd 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -44,7 +44,13 @@ from products.metrics.backend.facade.contracts import (
PanelQueryCheckResult,
SuggestedDashboard,
)
-from products.metrics.backend.facade.enums import DashboardTemplateStatus, FilterOp, MetricAggregation, MetricType
+from products.metrics.backend.facade.enums import (
+ DashboardTemplateStatus,
+ FilterOp,
+ MetricAggregation,
+ MetricRangeFunction,
+ MetricType,
+)
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
from products.metrics.backend.investigation import investigate as _investigate
@@ -117,17 +123,33 @@ def _units_by_fingerprint(team: Team, metric_names: set[str]) -> dict[int, str]:
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
+ """The ingested unit shared by the physical series one output series
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}
+ the same one. A disagreement, or a mix of unit and no unit, means the
+ merge has no correct single unit, so it returns None. Series that all
+ carry no unit return "", which `_output_unit` needs to tell a unitless
+ counter (whose rate is still per second) apart from a disagreement."""
+ units = {units_by_fingerprint.get(fp, "") for fp in fingerprints}
if len(units) != 1:
return None
(unit,) = units
return unit
+def _output_unit(ingested: str | None, clause: MetricQueryClause) -> str | None:
+ """The unit of the values a clause returns, which differs from the
+ ingested unit when the clause transforms the values. COUNT returns a
+ number of series, so it has no unit, even after a range function. RATE
+ divides by the bucket length in seconds, so it returns the ingested unit
+ per second, as a UCUM string the frontend formatter reads. Every other
+ aggregation keeps the ingested unit."""
+ if ingested is None or clause.aggregation is MetricAggregation.COUNT:
+ return None
+ if clause.aggregation is MetricAggregation.RATE or clause.range_function is MetricRangeFunction.RATE:
+ return f"{ingested or '1'}/s"
+ return ingested or None
+
+
# Hard cap on series returned per clause; the largest series (by summed
# absolute value) win so the most significant groups survive truncation.
# A clause without an aggregation is capped earlier, in the query, at the same number.
@@ -137,8 +159,7 @@ MAX_SERIES_PER_CLAUSE = MAX_RAW_SERIES
def _assemble_series(
rows: list[dict[str, Any]],
*,
- metric_name: str,
- clause_name: str,
+ clause: MetricQueryClause,
grid: list[str],
units_by_fingerprint: dict[int, str],
) -> list[MetricSeries]:
@@ -166,9 +187,9 @@ def _assemble_series(
MetricSeries(
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,
- unit=_unit_for_fingerprints(fingerprints_by_labels[key], units_by_fingerprint),
+ metric_name=clause.metric_name,
+ clause=clause.name,
+ unit=_output_unit(_unit_for_fingerprints(fingerprints_by_labels[key], units_by_fingerprint), clause),
)
for key, values in ranked[:MAX_SERIES_PER_CLAUSE]
]
@@ -357,8 +378,7 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricS
series_by_clause = {
clause.name: _assemble_series(
rows_by_clause[clause.name],
- metric_name=clause.metric_name,
- clause_name=clause.name,
+ clause=clause,
grid=grid,
units_by_fingerprint=units_by_fingerprint,
)
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 103d27b97fbb..2092075deae9 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -159,8 +159,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.
+ # UCUM unit of the values in `points` (e.g. "By", "ms", "ms/s"). It differs
+ # from the ingested unit when the clause transforms the values: COUNT has no
+ # unit and RATE is per second. Set by `run_metric_query`, not by callers.
unit: str | None = None
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index adea7ecdc372..837b892e679b 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -361,6 +361,11 @@ class _MetricSeriesSerializer(serializers.Serializer):
allow_null=True,
help_text="Name of the query clause that produced this series.",
)
+ unit = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text='UCUM unit of the returned values, e.g. "By", "ms", "{request}/s". It is the ingested unit, except that a count of series has no unit and a rate is per second ("ms/s", or "1/s" for a counter without a unit). Null when the values have no unit, when merged series disagree on the unit, and for formula results.',
+ )
class _MetricQueryResponseSerializer(serializers.Serializer):
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 56e4d3156fbd..01751a283a03 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.hogql.query import execute_hogql_query
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
-from products.metrics.backend.facade.api import run_metric_query
+from products.metrics.backend.facade.api import _output_unit, run_metric_query
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricRangeFunction
from products.metrics.backend.metric_query_runner import (
@@ -801,6 +801,40 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(series[0].clause, "formula")
self.assertIsNone(series[0].unit)
+ @parameterized.expand(
+ [
+ ("count_counts_series", MetricAggregation.COUNT, None, None),
+ ("rate_is_per_second", MetricAggregation.SUM, MetricRangeFunction.RATE, "ms/s"),
+ ]
+ )
+ def test_series_unit_is_the_unit_of_the_output(self, _name, aggregation, range_function, expected_unit):
+ anchor = timezone.now().replace(second=0, microsecond=0) - dt.timedelta(minutes=30)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ metric_type="sum",
+ is_monotonic=True,
+ unit="ms",
+ points=[(anchor, 0.0), (anchor + dt.timedelta(seconds=30), 30.0)],
+ )
+
+ series = run_metric_query(
+ team=self.team,
+ request=self._request(
+ clauses=(
+ MetricQueryClause(
+ name="a", metric_name="m1", aggregation=aggregation, range_function=range_function
+ ),
+ ),
+ date_from=anchor - dt.timedelta(minutes=1),
+ date_to=anchor + dt.timedelta(minutes=2),
+ interval="minute",
+ ),
+ )
+
+ self.assertEqual(len(series), 1)
+ self.assertEqual(series[0].unit, expected_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)])
@@ -836,6 +870,33 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
run_metric_query(team=self.team, request=self._request(**overrides))
+class TestOutputUnit(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("sum_keeps_unit", "ms", MetricAggregation.SUM, None, "ms"),
+ ("max_keeps_unit", "By", MetricAggregation.MAX, None, "By"),
+ ("increase_keeps_unit", "ms", MetricAggregation.INCREASE, None, "ms"),
+ ("increase_range_keeps_unit", "ms", MetricAggregation.SUM, MetricRangeFunction.INCREASE, "ms"),
+ ("histogram_quantile_keeps_unit", "s", MetricAggregation.HISTOGRAM_QUANTILE, None, "s"),
+ ("count_drops_unit", "ms", MetricAggregation.COUNT, None, None),
+ ("count_after_rate_drops_unit", "ms", MetricAggregation.COUNT, MetricRangeFunction.RATE, None),
+ ("rate_aggregation_per_second", "ms", MetricAggregation.RATE, None, "ms/s"),
+ ("rate_range_per_second", "By", MetricAggregation.AVG, MetricRangeFunction.RATE, "By/s"),
+ ("rate_of_annotation", "{request}", MetricAggregation.RATE, None, "{request}/s"),
+ ("rate_of_one", "1", MetricAggregation.RATE, None, "1/s"),
+ ("rate_of_unitless", "", MetricAggregation.RATE, None, "1/s"),
+ ("unitless_without_rate", "", MetricAggregation.SUM, None, None),
+ ("rate_of_disagreeing_units", None, MetricAggregation.RATE, None, None),
+ ]
+ )
+ def test_output_unit(self, _name, ingested, aggregation, range_function, expected):
+ quantile = 0.5 if aggregation.needs_quantile else None
+ clause = MetricQueryClause(
+ name="a", metric_name="m1", aggregation=aggregation, range_function=range_function, quantile=quantile
+ )
+ self.assertEqual(_output_unit(ingested, clause), expected)
+
+
class TestMetricFilters(ClickhouseTestMixin, APIBaseTest):
runner_class: type[MetricQueryRunner] = MetricQueryRunner
diff --git a/products/metrics/frontend/components/metricsChartConfig.test.ts b/products/metrics/frontend/components/metricsChartConfig.test.ts
index bcab87362376..fe6460e7e002 100644
--- a/products/metrics/frontend/components/metricsChartConfig.test.ts
+++ b/products/metrics/frontend/components/metricsChartConfig.test.ts
@@ -1,4 +1,4 @@
-import type { XAxisConfig } from '@posthog/quill-charts'
+import type { XAxisConfig, YAxisConfig } from '@posthog/quill-charts'
import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'
@@ -8,9 +8,11 @@ const X_AXIS: XAxisConfig = {}
const build = (
display: MetricsDisplaySettings | undefined,
- seriesCount = 1
+ seriesCount = 1,
+ unit?: string,
+ values?: number[]
): ReturnType<typeof buildMetricsChartConfig> =>
- buildMetricsChartConfig({ display, xAxis: X_AXIS, seriesCount, labelFormatter: (l) => l })
+ buildMetricsChartConfig({ display, xAxis: X_AXIS, seriesCount, labelFormatter: (l) => l, unit, values })
describe('metricsChartConfig', () => {
it('omits the settings keys entirely when a query carries no display', () => {
@@ -45,6 +47,25 @@ describe('metricsChartConfig', () => {
expect(config.yAxis).toEqual({ scale: 'log', startAtZero: false, max: 100 })
})
+ it('formats axis ticks and tooltip values with the unit and keeps the y-axis settings', () => {
+ const config = build({ yAxis: { scale: 'log' } }, 1, 'ms')
+ const yAxis = config.yAxis as YAxisConfig
+
+ expect(yAxis.scale).toBe('log')
+ expect(yAxis.tickFormatter?.(250)).toBe('250 ms')
+ expect(config.tooltip?.valueFormatter?.(1500, {} as never)).toBe('1.5 s')
+ })
+
+ it.each([
+ ['bare numbers when a plotted value exceeds 1', [0.2, 1.5, 2], '0.5', '1'],
+ ['percents when every plotted value is within 1', [0.2, 0.8], '50%', '100%'],
+ ])('formats every ratio tick and tooltip value on one scale: %s', (_name, values, tick, tooltipValue) => {
+ const config = build(undefined, 1, '1', values)
+
+ expect((config.yAxis as YAxisConfig).tickFormatter?.(0.5)).toBe(tick)
+ expect(config.tooltip?.valueFormatter?.(1, {} as never)).toBe(tooltipValue)
+ })
+
it('only shows the legend once there is more than one series', () => {
expect(build(undefined, 1).legend).toMatchObject({ show: false })
expect(build(undefined, 2).legend).toMatchObject({ show: true })
diff --git a/products/metrics/frontend/components/metricsChartConfig.ts b/products/metrics/frontend/components/metricsChartConfig.ts
index 1757aeda13d8..24257d0a7949 100644
--- a/products/metrics/frontend/components/metricsChartConfig.ts
+++ b/products/metrics/frontend/components/metricsChartConfig.ts
@@ -8,6 +8,8 @@ import type {
import type { GoalLine, MetricsDisplaySettings, MetricsYAxisSettings } from '~/queries/schema/schema-general'
+import { metricValuesFormatter } from '../panels/metricsUnits'
+
/** The config keys metrics sets. `TimeSeriesLineChartConfig` and `TimeSeriesBarChartConfig` declare
* these identically, so one builder serves both charts. */
export type MetricsChartConfig = Pick<
@@ -59,13 +61,21 @@ export function buildMetricsChartConfig({
xAxis,
seriesCount,
labelFormatter,
+ unit,
+ values = [],
}: {
display: MetricsDisplaySettings | undefined
xAxis: XAxisConfig
seriesCount: number
labelFormatter: (label: string) => string
+ /** The unit every series shares, as `MetricsPanel` resolves it. Undefined leaves quill's number formatting. */
+ unit?: string
+ /** Every plotted value. A ratio unit picks one scale for the whole chart from them. */
+ values?: readonly number[]
}): MetricsChartConfig {
- const yAxis = yAxisToConfig(display?.yAxis)
+ const valueFormatter = unit ? metricValuesFormatter(unit, values) : undefined
+ const yAxisSettings = yAxisToConfig(display?.yAxis)
+ const yAxis = valueFormatter ? { ...yAxisSettings, tickFormatter: valueFormatter } : yAxisSettings
const goalLines = goalLinesToConfigs(display?.goalLines)
return {
xAxis,
@@ -74,6 +84,6 @@ export function buildMetricsChartConfig({
...(yAxis ? { yAxis } : {}),
...(goalLines ? { goalLines } : {}),
legend: { show: seriesCount > 1, interactive: true },
- tooltip: { placement: 'cursor', pinnable: true, labelFormatter },
+ tooltip: { placement: 'cursor', pinnable: true, labelFormatter, ...(valueFormatter ? { valueFormatter } : {}) },
}
}
diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.ts
index 158526e8fa03..2a93f86b8b4c 100644
--- a/products/metrics/frontend/components/metricsSeries.ts
+++ b/products/metrics/frontend/components/metricsSeries.ts
@@ -8,7 +8,7 @@ export interface MetricsChartSeries {
metricName?: string | null
/** Alias of the query clause that produced this series (`formula` for a formula result). */
clause?: string | null
- /** UCUM unit as ingested, e.g. "By", "ms". Absent when the SDK did not set one. */
+ /** UCUM unit of the values, as the query resolves it, e.g. "By", "ms", "1/s". Absent when the values have no unit. */
unit?: string | null
}
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 7f9d83ce1ba1..9792dee2d166 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -452,7 +452,14 @@ describe('metricsViewerLogic', () => {
it('runs a PromQL query through the query runner and charts its series', async () => {
jest.mocked(performQuery).mockResolvedValue({
- results: [{ labels: { job: 'api' }, points: [{ time: '2026-01-01T00:00:00Z', value: 1 }], clause: 'a' }],
+ results: [
+ {
+ labels: { job: 'api' },
+ points: [{ time: '2026-01-01T00:00:00Z', value: 1 }],
+ clause: 'a',
+ unit: 's',
+ },
+ ],
})
logic.actions.applyQuery({ kind: NodeKind.MetricsQuery, clauses: [], language: 'promql', promql: 'sum(up)' })
@@ -468,6 +475,7 @@ describe('metricsViewerLogic', () => {
points: [{ time: '2026-01-01T00:00:00Z', value: 1 }],
metricName: null,
clause: 'a',
+ unit: 's',
},
])
})
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 2e8393b1ac42..b24507c4dde8 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -1525,6 +1525,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
points: series.points,
metric_name: series.metricName ?? null,
clause: series.clause ?? null,
+ unit: series.unit ?? null,
}))
}
const queryPayload = values.queryPayload
@@ -1913,7 +1914,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
},
],
// All series rendered as chart lines (a group-by query returns one series per label combination).
- // `MetricsSeriesChart` owns naming and colors; this only bridges the API's snake_case fields.
+ // `MetricsPanel` owns naming, colors and unit resolution; this only bridges the API's snake_case fields.
chartSeries: [
(s) => [s.queryResults],
(results: MetricsViewerSeries[]): MetricsChartSeries[] =>
@@ -1922,6 +1923,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
points: series.points,
metricName: series.metric_name,
clause: series.clause,
+ unit: series.unit,
})),
],
// Whether the chart has anything to draw. A query can return series with no points
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 8507f0aca885..c77e8a134e90 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -234,6 +234,11 @@ export interface _MetricSeriesApi {
* @nullable
*/
clause?: string | null
+ /**
+ * UCUM unit of the returned values, e.g. "By", "ms", "{request}/s". It is the ingested unit, except that a count of series has no unit and a rate is per second ("ms/s", or "1/s" for a counter without a unit). Null when the values have no unit, when merged series disagree on the unit, and for formula results.
+ * @nullable
+ */
+ unit?: string | null
}
export interface _MetricAnomalyReportApi {
diff --git a/products/metrics/frontend/panels/BarGaugePanel.tsx b/products/metrics/frontend/panels/BarGaugePanel.tsx
index 50d9ee9bef0a..9d379079a1f6 100644
--- a/products/metrics/frontend/panels/BarGaugePanel.tsx
+++ b/products/metrics/frontend/panels/BarGaugePanel.tsx
@@ -7,7 +7,7 @@ import { getColorVar } from 'lib/colors'
import { flattenSeriesRows } from './metricsReduce'
import { thresholdColor } from './metricsThresholds'
-import { formatMetricValue } from './metricsUnits'
+import { metricValuesFormatter } from './metricsUnits'
import type { MetricsPanelProps } from './registry'
import { resolveReducer } from './registry'
@@ -42,6 +42,15 @@ export function BarGaugePanel({ series, display, fallbackName }: MetricsPanelPro
],
[rows, reducer, fallbackName, display.thresholds]
)
+ // `MetricsPanel` gives every series the same resolved unit, so the first row speaks for the chart.
+ const formatValue = useMemo(
+ () =>
+ metricValuesFormatter(
+ rows[0]?.series.unit ?? undefined,
+ rows.map((row) => row.values[reducer] ?? 0)
+ ),
+ [rows, reducer]
+ )
const labels = useMemo(
() =>
rows.map(
@@ -70,7 +79,7 @@ export function BarGaugePanel({ series, display, fallbackName }: MetricsPanelPro
if (!row) {
return null
}
- return <span>{formatMetricValue(row.values[reducer] ?? 0, row.series.unit ?? undefined)}</span>
+ return <span>{formatValue(row.values[reducer] ?? 0)}</span>
}}
/>
</div>
diff --git a/products/metrics/frontend/panels/GaugePanel.tsx b/products/metrics/frontend/panels/GaugePanel.tsx
index 0bfb365b9f19..4c3b12f143d9 100644
--- a/products/metrics/frontend/panels/GaugePanel.tsx
+++ b/products/metrics/frontend/panels/GaugePanel.tsx
@@ -2,7 +2,7 @@ import { getColorVar } from 'lib/colors'
import { flattenSeriesRows } from './metricsReduce'
import { thresholdColor } from './metricsThresholds'
-import { formatMetricValue } from './metricsUnits'
+import { metricValuesFormatter } from './metricsUnits'
import type { MetricsPanelProps } from './registry'
import { resolveReducer } from './registry'
@@ -66,6 +66,7 @@ export function GaugePanel({ series, display, fallbackName }: MetricsPanelProps)
const value = row.values[reducer] ?? null
const unit = row.series.unit ?? undefined
const { min, max } = gaugeBounds(value ?? 0, display)
+ const formatValue = metricValuesFormatter(unit, [value ?? 0, min, max])
const fraction = value === null ? 0 : Math.min(Math.max((value - min) / (max - min), 0), 1)
const color = getColorVar(thresholdColor(value, display.thresholds, FALLBACK_COLOR))
const name =
@@ -107,7 +108,7 @@ export function GaugePanel({ series, display, fallbackName }: MetricsPanelProps)
fontWeight="600"
fill="currentColor"
>
- {value === null ? '—' : formatMetricValue(value, unit)}
+ {value === null ? '—' : formatValue(value)}
</text>
<text
x={cx}
@@ -116,7 +117,7 @@ export function GaugePanel({ series, display, fallbackName }: MetricsPanelProps)
fontSize="9"
fill="var(--color-graph-axis-label)"
>
- {formatMetricValue(min, unit)} – {formatMetricValue(max, unit)}
+ {formatValue(min)} – {formatValue(max)}
</text>
</svg>
<span className="text-xs text-secondary max-w-[120px] truncate">{name}</span>
diff --git a/products/metrics/frontend/panels/HeatmapPanel.test.tsx b/products/metrics/frontend/panels/HeatmapPanel.test.tsx
index 13ab3c5d15b4..b3476856bd82 100644
--- a/products/metrics/frontend/panels/HeatmapPanel.test.tsx
+++ b/products/metrics/frontend/panels/HeatmapPanel.test.tsx
@@ -59,6 +59,13 @@ describe('HeatmapPanel', () => {
expect(screen.getByText(/No data for this metric/)).toBeInTheDocument()
})
+ it('formats every ratio bound on one scale', () => {
+ render(<HeatmapPanel response={response({ bounds: [0.5, 1, 2] })} unit="1" />)
+ expect(screen.getByText('0.5')).toBeInTheDocument()
+ expect(screen.getByText('1')).toBeInTheDocument()
+ expect(screen.queryByText('50%')).not.toBeInTheDocument()
+ })
+
it('formats bounds without a unit as compact numbers', () => {
render(<HeatmapPanel response={response({ bounds: [10, 2000] })} />)
expect(screen.getByText('10')).toBeInTheDocument()
diff --git a/products/metrics/frontend/panels/HeatmapPanel.tsx b/products/metrics/frontend/panels/HeatmapPanel.tsx
index 6002ef20c5e3..c3defaa1d968 100644
--- a/products/metrics/frontend/panels/HeatmapPanel.tsx
+++ b/products/metrics/frontend/panels/HeatmapPanel.tsx
@@ -9,7 +9,7 @@ import { teamLogic } from 'scenes/teamLogic'
import type { MetricsHistogramQueryResponse } from '~/queries/schema/schema-general'
-import { formatMetricValue } from './metricsUnits'
+import { metricValuesFormatter } from './metricsUnits'
/** A latency-over-time heatmap: x = time bucket, y = histogram bucket upper bound, cell =
* observation count. `yLabels[0]` is the bottom row (smallest bucket), so the response's
@@ -28,10 +28,10 @@ export function HeatmapPanel({
() => (response.times ?? []).map((t) => dayjs(t).tz(timezone).format('D MMM HH:mm')),
[response.times, timezone]
)
- const yLabels = useMemo(
- () => (response.bounds ?? []).map((b) => formatMetricValue(b, unit)),
- [response.bounds, unit]
- )
+ const yLabels = useMemo(() => {
+ const bounds = response.bounds ?? []
+ return bounds.map(metricValuesFormatter(unit, bounds))
+ }, [response.bounds, unit])
const cells = useMemo(() => response.counts ?? [], [response.counts])
const hasData = cells.some((row) => row.some((c) => c > 0))
diff --git a/products/metrics/frontend/panels/MetricsPanel.test.tsx b/products/metrics/frontend/panels/MetricsPanel.test.tsx
index 140227941bf7..b9efb91a3ad2 100644
--- a/products/metrics/frontend/panels/MetricsPanel.test.tsx
+++ b/products/metrics/frontend/panels/MetricsPanel.test.tsx
@@ -80,6 +80,21 @@ describe('MetricsPanel', () => {
expect(tooltip.value('http.requests')).toBe('0')
})
+ it('formats the y axis and tooltip with the resolved unit', async () => {
+ renderPanel([seriesWith({}, [250, 1500, 3000], 'http.duration', 'ms')])
+ const chart = getHogChart()
+ expect(chart.yTicks().some((tick) => tick.endsWith(' s'))).toBe(true)
+ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 0, BUCKETS.length))
+ expect(tooltip.value('http.duration')).toBe('250 ms')
+ })
+
+ it('labels every ratio tick on one scale when the data exceeds 1', () => {
+ renderPanel([seriesWith({}, [0, 1, 2], 'load', '1')])
+ const ticks = getHogChart().yTicks()
+ expect(ticks.length).toBeGreaterThan(1)
+ expect(ticks.some((tick) => tick.endsWith('%'))).toBe(false)
+ })
+
it('draws a goal line above the data', () => {
renderPanel([seriesWith({}, [1, 2, 3])], { goalLines: [{ label: 'SLO', value: 10 }] })
expect(screen.getByText('SLO')).toBeInTheDocument()
@@ -127,6 +142,19 @@ describe('MetricsPanel', () => {
expect(screen.getByText('30')).toBeInTheDocument()
})
+ it('formats every ratio cell of the table on one scale', () => {
+ renderPanel([seriesWith({}, [0.5, 1, 2], 'load', '1')], { type: 'table', legendCalcs: ['min', 'max'] })
+ expect(screen.getByText('0.5')).toBeInTheDocument()
+ expect(screen.getByText('2')).toBeInTheDocument()
+ expect(screen.queryByText('50%')).not.toBeInTheDocument()
+ })
+
+ it('formats a ratio gauge value and its bounds on one scale', () => {
+ renderPanel([seriesWith({}, [0, 0, 0.5], 'load', '1')], { type: 'gauge', yAxis: { min: 0, max: 2 } })
+ expect(screen.getByText('0.5')).toBeInTheDocument()
+ expect(screen.getByText('0 – 2')).toBeInTheDocument()
+ })
+
it('renders the gauge arc with a formatted value and bounds', () => {
renderPanel([seriesWith({}, [0, 0, 40], 'cpu', '%')], {
type: 'gauge',
diff --git a/products/metrics/frontend/panels/MetricsPanel.tsx b/products/metrics/frontend/panels/MetricsPanel.tsx
index c63a3369c564..0c9bf82e7119 100644
--- a/products/metrics/frontend/panels/MetricsPanel.tsx
+++ b/products/metrics/frontend/panels/MetricsPanel.tsx
@@ -11,7 +11,7 @@ import { TablePanel } from './TablePanel'
import { TimeSeriesPanel } from './TimeSeriesPanel'
/** A series with its own unit resolved: the display override wins, then the series'
- * ingested unit — but only when no other series carries a different unit, since a tile
+ * ingested unit — but only when every series carries that same unit, since a tile
* mixes the values on one chart. A mixed-unit result renders bare numbers rather than
* mislabeling one series with another's unit. */
function withResolvedUnits(series: MetricsChartSeries[], displayUnit: string | undefined): MetricsChartSeries[] {
diff --git a/products/metrics/frontend/panels/StatPanel.tsx b/products/metrics/frontend/panels/StatPanel.tsx
index 9c3653be3a95..198bf1f4f936 100644
--- a/products/metrics/frontend/panels/StatPanel.tsx
+++ b/products/metrics/frontend/panels/StatPanel.tsx
@@ -10,7 +10,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { flattenSeriesRows } from './metricsReduce'
import { thresholdColor } from './metricsThresholds'
-import { formatMetricValue } from './metricsUnits'
+import { metricValuesFormatter } from './metricsUnits'
import type { MetricsPanelProps } from './registry'
import { resolveReducer } from './registry'
@@ -43,12 +43,15 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):
row.metricName ||
fallbackName
const color = getColorVar(thresholdColor(value, display.thresholds, FALLBACK_COLOR))
+ const data = row.series.points.map((p) => p.value ?? 0)
+ // The headline shows the hovered sparkline point, so it shares one scale with every point.
+ const formatValue = metricValuesFormatter(row.series.unit ?? undefined, [...data, value ?? 0])
return (
<MetricCard
key={index}
title={single ? null : name}
value={value ?? undefined}
- data={row.series.points.map((p) => p.value ?? 0)}
+ data={data}
labels={row.series.points.map((p) => p.time)}
formatLabel={(time) => dayjs(time).tz(timezone).format('D MMM HH:mm')}
// The time shows only on hover. A blank caption at rest keeps its row, so the
@@ -56,7 +59,7 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):
restingSubtitle={' '}
theme={theme}
color={color}
- formatValue={(v) => formatMetricValue(v, row.series.unit ?? undefined)}
+ formatValue={formatValue}
headlineClassName="whitespace-nowrap text-2xl @min-[13rem]:text-3xl @min-[16rem]:text-4xl"
changeInline
sparklineFill={single}
diff --git a/products/metrics/frontend/panels/TablePanel.tsx b/products/metrics/frontend/panels/TablePanel.tsx
index 2578f8320212..c60d140a9252 100644
--- a/products/metrics/frontend/panels/TablePanel.tsx
+++ b/products/metrics/frontend/panels/TablePanel.tsx
@@ -4,7 +4,7 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { capReducers, flattenSeriesRows, MetricsSeriesRow } from './metricsReduce'
import { safeColorToken, thresholdColor } from './metricsThresholds'
-import { formatMetricValue } from './metricsUnits'
+import { metricValuesFormatter } from './metricsUnits'
import type { MetricsPanelProps } from './registry'
import { resolveReducer } from './registry'
@@ -30,6 +30,15 @@ export function TablePanel({ series, display, fallbackName }: MetricsPanelProps)
)
const rows = useMemo(() => flattenSeriesRows(series, reducers), [series, reducers])
const keys = useMemo(() => labelKeys(rows), [rows])
+ // `MetricsPanel` gives every series the same resolved unit, so the first row speaks for the table.
+ const formatValue = useMemo(
+ () =>
+ metricValuesFormatter(
+ rows[0]?.series.unit ?? undefined,
+ rows.flatMap((row) => Object.values(row.values)).filter((v): v is number => v != null)
+ ),
+ [rows]
+ )
const columns: LemonTableColumns<MetricsSeriesRow> = [
...(keys.length > 0
@@ -55,9 +64,7 @@ export function TablePanel({ series, display, fallbackName }: MetricsPanelProps)
return value === null ? (
<span className="text-secondary">—</span>
) : (
- <span className={`text-(--${color})`}>
- {formatMetricValue(value, row.series.unit ?? undefined)}
- </span>
+ <span className={`text-(--${color})`}>{formatValue(value)}</span>
)
},
})),
diff --git a/products/metrics/frontend/panels/TimeSeriesPanel.tsx b/products/metrics/frontend/panels/TimeSeriesPanel.tsx
index 1ab9ff8c8479..45fe6621d028 100644
--- a/products/metrics/frontend/panels/TimeSeriesPanel.tsx
+++ b/products/metrics/frontend/panels/TimeSeriesPanel.tsx
@@ -52,6 +52,9 @@ export function TimeSeriesPanel({
}))
}, [series, fallbackName, isArea])
const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])
+ // `MetricsPanel` gives every series the same resolved unit, so the first series speaks for the chart.
+ const unit = series[0]?.unit ?? undefined
+ const plottedValues = useMemo(() => chartSeries.flatMap((s) => s.data), [chartSeries])
const sharedConfig = useChartConfig<TimeSeriesLineChartConfig>(
() =>
@@ -60,8 +63,10 @@ export function TimeSeriesPanel({
xAxis: { timezone },
seriesCount: chartSeries.length,
labelFormatter: (label: string) => dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss'),
+ unit,
+ values: plottedValues,
}),
- [timezone, chartSeries.length, display]
+ [timezone, chartSeries.length, display, unit, plottedValues]
)
const markers = exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : null
diff --git a/products/metrics/frontend/panels/metricsReduce.test.ts b/products/metrics/frontend/panels/metricsReduce.test.ts
index 4374770b11b7..1a7db7e83bd3 100644
--- a/products/metrics/frontend/panels/metricsReduce.test.ts
+++ b/products/metrics/frontend/panels/metricsReduce.test.ts
@@ -102,8 +102,8 @@ describe('metricsReduce', () => {
expect(seriesUnit([oneSeries('ms'), oneSeries('s')], undefined)).toBeUndefined()
})
- it('ignores series without a unit when the rest agree', () => {
- expect(seriesUnit([oneSeries('ms'), oneSeries(undefined)], undefined)).toBe('ms')
+ it('returns undefined when one series has no unit, rather than lending it the others', () => {
+ expect(seriesUnit([oneSeries('ms'), oneSeries(undefined)], undefined)).toBeUndefined()
})
it('returns undefined when no series carries a unit', () => {
@@ -143,8 +143,8 @@ describe('metricsReduce', () => {
expect(seriesUnit([oneSeries('ms'), oneSeries('s')], undefined)).toBeUndefined()
})
- it('ignores series without a unit when the rest agree', () => {
- expect(seriesUnit([oneSeries('ms'), oneSeries(undefined)], undefined)).toBe('ms')
+ it('returns undefined when one series has no unit, rather than lending it the others', () => {
+ expect(seriesUnit([oneSeries('ms'), oneSeries(undefined)], undefined)).toBeUndefined()
})
it('returns undefined when no series carries a unit', () => {
diff --git a/products/metrics/frontend/panels/metricsReduce.ts b/products/metrics/frontend/panels/metricsReduce.ts
index 93ba536c5423..5035fa0b6231 100644
--- a/products/metrics/frontend/panels/metricsReduce.ts
+++ b/products/metrics/frontend/panels/metricsReduce.ts
@@ -64,15 +64,17 @@ export function flattenSeriesRows(series: ReducibleSeries[], reducers: MetricsRe
}
/** The unit a panel renders with. The explicit display override always wins;
- * without one, the shared ingested unit applies — but only when every series
- * that carries a unit agrees. A mixed-unit result gets no unit rather than
- * one series' values mislabeled with another's. */
+ * without one, the shared ingested unit applies, but only when every series
+ * carries that same unit. A series with no unit counts as a different unit, because
+ * a unitless count beside an `ms` duration is not in milliseconds. A mixed-unit
+ * result gets no unit rather than one series' values mislabeled with another's. */
export function seriesUnit(series: ReducibleSeries[], displayUnit: string | undefined): string | undefined {
if (displayUnit) {
return displayUnit
}
- const units = new Set(series.map((s) => s.unit).filter((u): u is string => !!u))
- return units.size === 1 ? [...units][0] : undefined
+ const units = new Set(series.map((s) => s.unit || undefined))
+ const [shared] = units
+ return units.size === 1 ? shared : undefined
}
/** A persisted `legendCalcs` list is user input from a saved insight: it can
diff --git a/products/metrics/frontend/panels/metricsUnits.test.ts b/products/metrics/frontend/panels/metricsUnits.test.ts
index f5dc34f565c1..a8667cd04055 100644
--- a/products/metrics/frontend/panels/metricsUnits.test.ts
+++ b/products/metrics/frontend/panels/metricsUnits.test.ts
@@ -1,4 +1,4 @@
-import { formatMetricValue, unitAxisFormatter } from './metricsUnits'
+import { formatMetricValue, metricValuesFormatter } from './metricsUnits'
describe('formatMetricValue', () => {
it.each([
@@ -23,6 +23,8 @@ describe('formatMetricValue', () => {
[340, 'ms', '340 ms'],
[1500, 'ms', '1.5 s'],
[250000, 'us', '250 ms'],
+ // a zero tick on a duration axis reads in seconds, not the smallest unit
+ [0, 'ms', '0 s'],
// percent
[42.5, '%', '42.5%'],
// ratio (UCUM "1")
@@ -33,8 +35,15 @@ describe('formatMetricValue', () => {
[88, '1/s', '88/s'],
[88, '{request}/s', '88 request/s'],
[1500, '{message}/s', '1.5K message/s'],
+ [2048, 'By/s', '2 KiB/s'],
// unknown unit falls back to compact + suffix
[1234, 'widgets', '1.23K widgets'],
+ // small nonzero values keep two significant digits instead of rounding to zero
+ [0.0012, undefined, '0.0012'],
+ [0.0042, '%', '0.0042%'],
+ [0.00005, '1', '0.005%'],
+ [0.004, '1/s', '0.004/s'],
+ [0.0031, '{request}/s', '0.0031 request/s'],
])('formats %s with unit %s as %s', (value, unit, expected) => {
expect(formatMetricValue(value, unit)).toBe(expected)
})
@@ -45,14 +54,17 @@ describe('formatMetricValue', () => {
})
})
-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')
+describe('metricValuesFormatter', () => {
+ it.each([
+ // a ratio picks one scale for every value shown together, from the largest of them
+ ['1', [0, 0.5, 1, 1.5, 2], ['0', '0.5', '1', '1.5', '2']],
+ ['1', [-2, 0.5], ['-2', '0.5']],
+ ['1', [0, 0.25, 1], ['0%', '25%', '100%']],
+ // other units still format each value on its own
+ ['ms', [340, 2000], ['340 ms', '2 s']],
+ [undefined, [1500], ['1.5K']],
+ ])('formats unit %s over values %j', (unit, values, expected) => {
+ const fmt = metricValuesFormatter(unit, values)
+ expect(values.map(fmt)).toEqual(expected)
})
})
diff --git a/products/metrics/frontend/panels/metricsUnits.ts b/products/metrics/frontend/panels/metricsUnits.ts
index ecec9947adc3..042087449488 100644
--- a/products/metrics/frontend/panels/metricsUnits.ts
+++ b/products/metrics/frontend/panels/metricsUnits.ts
@@ -4,8 +4,14 @@
* 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)
+import { significantDecimalPlaces } from 'lib/utils/numbers'
+
+// A fixed two decimals renders every value below 0.005 as "0", so a small-valued axis repeats one label.
+const compact = (value: number): string =>
+ new Intl.NumberFormat('en-US', {
+ notation: 'compact',
+ maximumFractionDigits: significantDecimalPlaces(value),
+ }).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']
@@ -19,7 +25,8 @@ const bytes = (value: number, base: 1000 | 1024): string => {
const seconds = (value: number): string => {
const abs = Math.abs(value)
- if (abs >= 1) {
+ // Zero has no magnitude to scale, so it would otherwise fall through to the ns branch.
+ if (abs >= 1 || abs === 0) {
return `${compact(value)} s`
}
if (abs >= 1e-3) {
@@ -35,6 +42,10 @@ const seconds = (value: number): string => {
* a count that happens to be in 0..1 is left alone by the caller passing a more specific unit. */
const RATIO_AS_PERCENT_MAX = 1
+const fitsPercent = (value: number): boolean => Math.abs(value) <= RATIO_AS_PERCENT_MAX
+
+const ratio = (value: number, asPercent: boolean): string => (asPercent ? `${compact(value * 100)}%` : compact(value))
+
/** 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 {
@@ -66,14 +77,15 @@ export function formatMetricValue(value: number, unit: string | undefined): stri
}
if (unit === '1') {
// UCUM "one": a dimensionless ratio. Render small ratios as a percent.
- if (Math.abs(value) <= RATIO_AS_PERCENT_MAX) {
- return `${compact(value * 100)}%`
- }
- return compact(value)
+ return ratio(value, fitsPercent(value))
}
if (unit === '1/s') {
return `${compact(value)}/s`
}
+ if (unit === 'By/s') {
+ // A rate over a byte counter: scale through bytes so it reads as throughput.
+ return `${bytes(value, 1024)}/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, '')
@@ -82,7 +94,13 @@ export function formatMetricValue(value: number, unit: string | undefined): stri
return `${compact(value)} ${unit}`
}
-/** An axis/tooltip formatter bound to a unit. */
-export function unitAxisFormatter(unit: string | undefined): (value: number) => string {
+/** A formatter for values one visual shows together: a chart's ticks and tooltips, a table, a bucket list.
+ * A ratio picks percent or bare numbers once from all `values`, so one visual never shows `100%` next
+ * to `1.5`. Every other unit formats each value on its own. */
+export function metricValuesFormatter(unit: string | undefined, values: readonly number[]): (value: number) => string {
+ if (unit === '1') {
+ const asPercent = values.every(fitsPercent)
+ return (value: number) => ratio(value, asPercent)
+ }
return (value: number) => formatMetricValue(value, unit)
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0d34ae0e612d..50fa5509c27f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -57327,7 +57327,7 @@ 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. */
+ /** UCUM unit of the returned values, e.g. "By", "ms", "1/s". It is the ingested unit, except that a count of series has no unit and a rate is per second. Empty when the values have no unit. */
unit?: string | null;
}
@@ -115591,6 +115591,11 @@ export namespace Schemas {
* @nullable
*/
clause?: string | null;
+ /**
+ * UCUM unit of the returned values, e.g. "By", "ms", "{request}/s". It is the ingested unit, except that a count of series has no unit and a rate is per second ("ms/s", or "1/s" for a counter without a unit). Null when the values have no unit, when merged series disagree on the unit, and for formula results.
+ * @nullable
+ */
+ unit?: string | null;
}
export interface _MetricAnomalyReport {