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): default counter metrics to increase, expose rate/increase in viewer (#68109)

Daniel Visca27e2650cc350
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index a52914854440..0c3664f9d53a 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -16,7 +16,13 @@ import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import { MetricsChartLegend } from './MetricsChartLegend'
import { MetricStatPanel } from './MetricStatPanel'
-import { LIVE_REFRESH_MS, MetricAggregation, metricsViewerLogic, MetricsViewMode } from './metricsViewerLogic'
+import {
+ LIVE_REFRESH_MS,
+ MetricAggregation,
+ metricsViewerLogic,
+ MetricsViewMode,
+ RECOMMENDED_AGGREGATION_BY_TYPE,
+} from './metricsViewerLogic'
const VIEW_MODE_OPTIONS: { value: MetricsViewMode; label: string }[] = [
{ value: 'chart', label: 'Chart' },
@@ -35,19 +41,10 @@ const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
{ value: 'avg', label: 'Average' },
{ value: 'count', label: 'Count' },
{ value: 'p95', label: 'p95' },
+ { value: 'rate', label: 'Rate (/s)' },
+ { value: 'increase', label: 'Increase' },
]
-// Recommended aggregation per OTel metric type. Used for an inline hint —
-// we don't auto-switch the user's choice (hint, don't overwrite).
-const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation> = {
- gauge: 'avg',
- sum: 'sum',
- counter: 'sum',
- histogram: 'p95',
- summary: 'p95',
- exponential_histogram: 'p95',
-}
-
// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.
const DATE_OPTIONS: DateMappingOption[] = [
{ key: CUSTOM_OPTION_KEY, values: [] },
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
new file mode 100644
index 000000000000..bad1f60b759e
--- /dev/null
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -0,0 +1,55 @@
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+
+import { metricNamePickerLogic } from './metricNamePickerLogic'
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+const PICKER_ITEMS = [
+ { name: 'requests_total', metric_type: 'sum' },
+ { name: 'queue_depth', metric_type: 'gauge' },
+ { name: 'request_duration', metric_type: 'histogram' },
+ { name: 'mystery_metric', metric_type: 'unknown_type' },
+]
+
+describe('metricsViewerLogic', () => {
+ let logic: ReturnType<typeof metricsViewerLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.spyOn(api.metrics, 'values').mockResolvedValue({ results: PICKER_ITEMS })
+ logic = metricsViewerLogic()
+ logic.mount()
+ metricNamePickerLogic.actions.loadItemsSuccess(PICKER_ITEMS)
+ })
+
+ afterEach(() => {
+ 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)
+ })
+
+ it('keeps a manual aggregation pick until the metric changes', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.setAggregation('rate')
+ expect(logic.values.aggregation).toBe('rate')
+ logic.actions.setMetricName('queue_depth')
+ expect(logic.values.aggregation).toBe('avg')
+ })
+
+ it('leaves aggregation untouched for unknown metric types', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.setMetricName('mystery_metric')
+ expect(logic.values.aggregation).toBe('increase')
+ })
+})
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 9fc4b347af83..df845d30f9ab 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -15,10 +15,11 @@ import type {
MetricAnomalyDirectionEnumApi,
} from 'products/metrics/frontend/generated/api.schemas'
+import { metricNamePickerLogic } from './metricNamePickerLogic'
import { formatSeriesName, seriesColor } from './metricsSeries'
import type { metricsViewerLogicType } from './metricsViewerLogicType'
-export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95'
+export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95' | 'rate' | 'increase'
// `chart` shows the time series; `stat` shows a single headline value + change pill (a Grafana "stat" panel).
export type MetricsViewMode = 'chart' | 'stat'
@@ -35,6 +36,19 @@ export interface MetricsAnomalyBadge {
}
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',
+}
const DEFAULT_DATE_FROM = '-1h'
const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, cancelling the previous one'
// The anomaly badge characterizes the most recent slice of the selected window against the rest.
@@ -62,7 +76,7 @@ const resolveDate = (value: string | null | undefined): string | null => {
export const metricsViewerLogic = kea<metricsViewerLogicType>([
path(['products', 'metrics', 'frontend', 'components', 'metricsViewerLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamId']],
+ values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['items']],
})),
actions({
setMetricName: (metricName: string) => ({ metricName }),
@@ -101,6 +115,15 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
+ setMetricName: ({ metricName }) => {
+ // Each metric type has one sensible default; a manual aggregation pick
+ // holds only until the next metric switch.
+ const metricType = values.items.find((item) => item.name === metricName)?.metric_type
+ const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
+ if (recommended && recommended !== values.aggregation) {
+ actions.setAggregation(recommended)
+ }
+ },
cancelInProgressQuery: ({ controller }) => {
if (values.queryAbortController !== null) {
values.queryAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)