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): viewer stat/multi-series/filters UI (#66437)

Daniel Visca70236e823d5b
diff --git a/frontend/src/lib/components/Metric/metricSummary.ts b/frontend/src/lib/components/Metric/metricSummary.ts
new file mode 100644
index 000000000000..07649bfb19cc
--- /dev/null
+++ b/frontend/src/lib/components/Metric/metricSummary.ts
@@ -0,0 +1,112 @@
+import { type MetricChange } from '@posthog/quill-charts'
+
+import { IntervalType } from '~/types'
+
+// Above this magnitude the exact percentage is noise (it comes from a near-zero start), so show ∞ instead.
+export const MAX_CHANGE_PERCENT = 10_000 // ≈100×
+
+export type MetricSummary = 'total' | 'average' | 'latest'
+
+export const METRIC_SUMMARY_DEFAULT: MetricSummary = 'total'
+export const METRIC_SUMMARY_LABELS: Record<MetricSummary, string> = {
+ total: 'Total',
+ average: 'Avg',
+ latest: 'Latest',
+}
+
+export const METRIC_SHOW_CHANGE_DEFAULT = true
+export const METRIC_COLOR_BY_DIRECTION_DEFAULT = false
+export const METRIC_DEFAULT_INCREASE_COLOR = '#388600'
+export const METRIC_DEFAULT_DECREASE_COLOR = '#db3707'
+
+const finiteValues = (data: number[] | undefined): number[] => (data ?? []).filter((v) => Number.isFinite(v))
+
+const mean = (values: number[]): number => values.reduce((sum, v) => sum + v, 0) / values.length
+
+const meanOfFinite = (data: number[] | undefined): number | undefined => {
+ const finite = finiteValues(data)
+ return finite.length === 0 ? undefined : mean(finite)
+}
+
+// Percentage change from `start` to `end`. Renders ∞ when the start is zero (infinite) or the magnitude
+// is so large the exact percentage is just noise. A missing endpoint yields `undefined` (no pill).
+function changeBetween(start: number | undefined, end: number | undefined): MetricChange | null | undefined {
+ if (start == null || end == null) {
+ return undefined
+ }
+ if (start === 0) {
+ return end === 0 ? null : { value: end > 0 ? 1 : -1, label: '∞' }
+ }
+ const percent = ((end - start) / Math.abs(start)) * 100
+ return Math.abs(percent) >= MAX_CHANGE_PERCENT ? { value: percent, label: '∞' } : { value: percent }
+}
+
+export function computeMetricChange(data: number[] | undefined): MetricChange | null | undefined {
+ const finite = finiteValues(data)
+ return finite.length < 2 ? undefined : changeBetween(finite[0], finite[finite.length - 1])
+}
+
+// Falls back to the total when the series has no finite points.
+export function computeMetricSummary(summary: MetricSummary, total: number, data: number[] | undefined): number {
+ if (summary === 'total') {
+ return total
+ }
+ const finite = finiteValues(data)
+ if (finite.length === 0) {
+ return total
+ }
+ return summary === 'latest' ? finite[finite.length - 1] : mean(finite)
+}
+
+export interface MetricSeriesSummary {
+ total: number
+ data: number[] | undefined
+}
+
+interface ComparableSeries {
+ count: number
+ data: number[]
+ compare_label?: string | null
+}
+
+// Matched by `compare_label`, not array position (the backend doesn't guarantee order).
+export function selectPreviousSeriesSummary(
+ results: readonly ComparableSeries[] | undefined
+): MetricSeriesSummary | undefined {
+ const previous = results?.find((series) => series.compare_label === 'previous')
+ return previous ? { total: previous.count, data: previous.data } : undefined
+}
+
+export function selectCurrentSeries<T extends { compare_label?: string | null }>(
+ results: readonly T[] | undefined
+): T | undefined {
+ return results?.find((series) => series.compare_label !== 'previous') ?? results?.[0]
+}
+
+export function computeMetricSummaryChange(
+ summary: MetricSummary,
+ current: MetricSeriesSummary,
+ previous: MetricSeriesSummary | undefined
+): MetricChange | null | undefined {
+ if (previous && summary !== 'latest') {
+ return summary === 'total'
+ ? changeBetween(previous.total, current.total)
+ : changeBetween(meanOfFinite(previous.data), meanOfFinite(current.data))
+ }
+ return computeMetricChange(current.data)
+}
+
+// Keep in sync with computeMetricSummaryChange — same total/average-vs-previous vs first→last split.
+export function getMetricChangeTooltip(
+ summary: MetricSummary,
+ hasComparison: boolean,
+ interval: IntervalType | null | undefined
+): string {
+ if (!hasComparison || summary === 'latest') {
+ const noun = interval ?? 'day'
+ return `Comparing the first ${noun}'s value to the most recent ${noun}'s value.`
+ }
+ return summary === 'total'
+ ? "Comparing this period's total to the previous period's total."
+ : "Comparing this period's average to the previous period's average."
+}
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
index 07649bfb19cc..22374b100906 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
@@ -1,112 +1,3 @@
-import { type MetricChange } from '@posthog/quill-charts'
-
-import { IntervalType } from '~/types'
-
-// Above this magnitude the exact percentage is noise (it comes from a near-zero start), so show ∞ instead.
-export const MAX_CHANGE_PERCENT = 10_000 // ≈100×
-
-export type MetricSummary = 'total' | 'average' | 'latest'
-
-export const METRIC_SUMMARY_DEFAULT: MetricSummary = 'total'
-export const METRIC_SUMMARY_LABELS: Record<MetricSummary, string> = {
- total: 'Total',
- average: 'Avg',
- latest: 'Latest',
-}
-
-export const METRIC_SHOW_CHANGE_DEFAULT = true
-export const METRIC_COLOR_BY_DIRECTION_DEFAULT = false
-export const METRIC_DEFAULT_INCREASE_COLOR = '#388600'
-export const METRIC_DEFAULT_DECREASE_COLOR = '#db3707'
-
-const finiteValues = (data: number[] | undefined): number[] => (data ?? []).filter((v) => Number.isFinite(v))
-
-const mean = (values: number[]): number => values.reduce((sum, v) => sum + v, 0) / values.length
-
-const meanOfFinite = (data: number[] | undefined): number | undefined => {
- const finite = finiteValues(data)
- return finite.length === 0 ? undefined : mean(finite)
-}
-
-// Percentage change from `start` to `end`. Renders ∞ when the start is zero (infinite) or the magnitude
-// is so large the exact percentage is just noise. A missing endpoint yields `undefined` (no pill).
-function changeBetween(start: number | undefined, end: number | undefined): MetricChange | null | undefined {
- if (start == null || end == null) {
- return undefined
- }
- if (start === 0) {
- return end === 0 ? null : { value: end > 0 ? 1 : -1, label: '∞' }
- }
- const percent = ((end - start) / Math.abs(start)) * 100
- return Math.abs(percent) >= MAX_CHANGE_PERCENT ? { value: percent, label: '∞' } : { value: percent }
-}
-
-export function computeMetricChange(data: number[] | undefined): MetricChange | null | undefined {
- const finite = finiteValues(data)
- return finite.length < 2 ? undefined : changeBetween(finite[0], finite[finite.length - 1])
-}
-
-// Falls back to the total when the series has no finite points.
-export function computeMetricSummary(summary: MetricSummary, total: number, data: number[] | undefined): number {
- if (summary === 'total') {
- return total
- }
- const finite = finiteValues(data)
- if (finite.length === 0) {
- return total
- }
- return summary === 'latest' ? finite[finite.length - 1] : mean(finite)
-}
-
-export interface MetricSeriesSummary {
- total: number
- data: number[] | undefined
-}
-
-interface ComparableSeries {
- count: number
- data: number[]
- compare_label?: string | null
-}
-
-// Matched by `compare_label`, not array position (the backend doesn't guarantee order).
-export function selectPreviousSeriesSummary(
- results: readonly ComparableSeries[] | undefined
-): MetricSeriesSummary | undefined {
- const previous = results?.find((series) => series.compare_label === 'previous')
- return previous ? { total: previous.count, data: previous.data } : undefined
-}
-
-export function selectCurrentSeries<T extends { compare_label?: string | null }>(
- results: readonly T[] | undefined
-): T | undefined {
- return results?.find((series) => series.compare_label !== 'previous') ?? results?.[0]
-}
-
-export function computeMetricSummaryChange(
- summary: MetricSummary,
- current: MetricSeriesSummary,
- previous: MetricSeriesSummary | undefined
-): MetricChange | null | undefined {
- if (previous && summary !== 'latest') {
- return summary === 'total'
- ? changeBetween(previous.total, current.total)
- : changeBetween(meanOfFinite(previous.data), meanOfFinite(current.data))
- }
- return computeMetricChange(current.data)
-}
-
-// Keep in sync with computeMetricSummaryChange — same total/average-vs-previous vs first→last split.
-export function getMetricChangeTooltip(
- summary: MetricSummary,
- hasComparison: boolean,
- interval: IntervalType | null | undefined
-): string {
- if (!hasComparison || summary === 'latest') {
- const noun = interval ?? 'day'
- return `Comparing the first ${noun}'s value to the most recent ${noun}'s value.`
- }
- return summary === 'total'
- ? "Comparing this period's total to the previous period's total."
- : "Comparing this period's average to the previous period's average."
-}
+// The metric summary math (total / average / latest + change pill) is shared with the Metrics product,
+// so it lives in `lib/components/Metric/metricSummary`. Re-exported here to keep the insights call sites stable.
+export * from 'lib/components/Metric/metricSummary'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c7a1f8c57189..89c1385ba233 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3663,6 +3663,9 @@ importers:
'@posthog/products-error-tracking':
specifier: workspace:*
version: link:../error_tracking
+ '@posthog/quill-charts':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/charts
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/products/metrics/frontend/components/MetricStatPanel.tsx b/products/metrics/frontend/components/MetricStatPanel.tsx
new file mode 100644
index 000000000000..6902ddb5c06a
--- /dev/null
+++ b/products/metrics/frontend/components/MetricStatPanel.tsx
@@ -0,0 +1,79 @@
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { MetricCard, useChartTheme } from '@posthog/quill-charts'
+
+import {
+ computeMetricSummary,
+ computeMetricSummaryChange,
+ getMetricChangeTooltip,
+ type MetricSummary,
+ METRIC_SUMMARY_LABELS,
+} from 'lib/components/Metric/metricSummary'
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { MetricAggregation, MetricsAnomalyBadge } from './metricsViewerLogic'
+
+export interface MetricStatPanelProps {
+ /** Headline title — the metric name. */
+ title: string
+ /** How the series is summarized into one value. */
+ summary: MetricSummary
+ /** The bucket aggregation, shown in the subtitle for context. */
+ aggregation: MetricAggregation
+ /** Grand total across buckets (basis for the 'total' summary). */
+ total: number
+ /** Per-bucket values the summary and sparkline are computed from. */
+ values: number[]
+ /** Pre-formatted bucket labels for the sparkline hover. */
+ labels: string[]
+ /** "vs baseline" anomaly badge, or null when the metric is flat / not characterized. */
+ anomaly: MetricsAnomalyBadge | null
+}
+
+/** A Grafana-style "stat" panel: one headline value + change pill + sparkline, with an optional anomaly badge. */
+export function MetricStatPanel({
+ title,
+ summary,
+ aggregation,
+ total,
+ values,
+ labels,
+ anomaly,
+}: MetricStatPanelProps): JSX.Element {
+ const theme = useChartTheme()
+ return (
+ <div className="flex flex-col h-full">
+ {anomaly && (
+ <div className="flex justify-end">
+ <Tooltip
+ title={`Baseline ${humanFriendlyNumber(anomaly.baselineMean)} → recent ${humanFriendlyNumber(
+ anomaly.anomalyMean
+ )}${anomaly.onsetTime ? `, onset ${dayjs(anomaly.onsetTime).format('D MMM HH:mm')}` : ''}`}
+ >
+ <LemonTag type="warning">
+ {anomaly.direction === 'up' ? '▲' : '▼'} {anomaly.percent}% vs baseline
+ </LemonTag>
+ </Tooltip>
+ </div>
+ )}
+ <MetricCard
+ className="flex-1"
+ title={title}
+ restingSubtitle={`${METRIC_SUMMARY_LABELS[summary]} · ${aggregation}`}
+ value={computeMetricSummary(summary, total, values)}
+ change={computeMetricSummaryChange(summary, { total, data: values }, undefined)}
+ changeTooltip={getMetricChangeTooltip(summary, false, null)}
+ changeSize="md"
+ changeInline
+ hoverChangeFromPreviousPoint
+ data={values}
+ labels={labels}
+ theme={theme}
+ sparklineFill
+ sparklineHeight={140}
+ formatValue={(value) => humanFriendlyNumber(value)}
+ dataAttr="metrics-stat-value"
+ />
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsChartLegend.tsx b/products/metrics/frontend/components/MetricsChartLegend.tsx
new file mode 100644
index 000000000000..49820cfe08dc
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsChartLegend.tsx
@@ -0,0 +1,23 @@
+import { getColorVar } from 'lib/colors'
+import { type SparklineTimeSeries } from 'lib/components/Sparkline'
+
+/** Legend for the multi-series chart — a colour swatch + name per series. Hidden for a single series. */
+export function MetricsChartLegend({ series }: { series: SparklineTimeSeries[] }): JSX.Element | null {
+ if (series.length < 2) {
+ return null
+ }
+ return (
+ <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
+ {series.map((s, i) => (
+ <span key={`${i}-${s.name}`} className="flex items-center gap-1.5 text-xs text-secondary">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ // Dynamic per-series colour can't be a Tailwind class.
+ style={{ backgroundColor: getColorVar(s.color ?? 'muted') }}
+ />
+ {s.name}
+ </span>
+ ))}
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 6e6dcfb2bc66..a52914854440 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -1,10 +1,11 @@
import { useActions, useMountedLogic, useValues } from 'kea'
import { useCallback, useEffect, useMemo } from 'react'
-import { LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'
+import { LemonInputSelect, LemonSegmentedButton, LemonSelect, LemonSwitch, SpinnerOverlay } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
+import { type MetricSummary } from 'lib/components/Metric/metricSummary'
import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
import { dayjs } from 'lib/dayjs'
import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
@@ -13,7 +14,21 @@ import { DateMappingOption } from '~/types'
import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
-import { MetricAggregation, metricsViewerLogic } from './metricsViewerLogic'
+import { MetricsChartLegend } from './MetricsChartLegend'
+import { MetricStatPanel } from './MetricStatPanel'
+import { LIVE_REFRESH_MS, MetricAggregation, metricsViewerLogic, MetricsViewMode } from './metricsViewerLogic'
+
+const VIEW_MODE_OPTIONS: { value: MetricsViewMode; label: string }[] = [
+ { value: 'chart', label: 'Chart' },
+ { value: 'stat', label: 'Stat' },
+]
+
+// How the stat card summarizes the series into one headline value.
+const SUMMARY_OPTIONS: { value: MetricSummary; label: string }[] = [
+ { value: 'latest', label: 'Latest' },
+ { value: 'average', label: 'Average' },
+ { value: 'total', label: 'Total' },
+]
const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
{ value: 'sum', label: 'Sum' },
@@ -78,18 +93,48 @@ export const MetricsViewer = (): JSX.Element => {
aggregation,
dateFrom,
dateTo,
+ viewMode,
+ statSummary,
+ groupByKeys,
+ filterStrings,
+ chartSeries,
sparklineValues,
sparklineLabels,
+ statTotal,
+ anomalyBadge,
+ liveRefresh,
queryResultsLoading,
hasMetricName,
} = useValues(logic)
- const { setMetricName, setAggregation, setDateFrom, setDateTo, fetchQueryResults } = useActions(logic)
+ const {
+ setMetricName,
+ setAggregation,
+ setDateFrom,
+ setDateTo,
+ setViewMode,
+ setStatSummary,
+ setGroupByKeys,
+ setFilterStrings,
+ setLiveRefresh,
+ fetchQueryResults,
+ fetchAnomaly,
+ clearAnomaly,
+ } = useActions(logic)
const { items: pickerItems } = useValues(pickerLogic)
// Refetch the chart whenever any filter changes — the loader breakpoint debounces input.
useEffect(() => {
fetchQueryResults({})
- }, [metricName, aggregation, dateFrom, dateTo]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [metricName, aggregation, dateFrom, dateTo, groupByKeys, filterStrings]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Characterize the recent window only while the stat card is visible — the badge is stat-mode only.
+ useEffect(() => {
+ if (viewMode === 'stat' && hasMetricName) {
+ fetchAnomaly({})
+ } else {
+ clearAnomaly()
+ }
+ }, [metricName, aggregation, dateFrom, dateTo, viewMode, hasMetricName, filterStrings]) // eslint-disable-line react-hooks/exhaustive-deps
const selectedMetricType = useMemo(
() => pickerItems.find((item) => item.name === metricName)?.metric_type,
@@ -158,6 +203,26 @@ export const MetricsViewer = (): JSX.Element => {
options={AGGREGATION_OPTIONS}
onChange={(value) => setAggregation(value as MetricAggregation)}
/>
+ <LemonInputSelect
+ mode="multiple"
+ size="small"
+ allowCustomValues
+ value={groupByKeys}
+ onChange={setGroupByKeys}
+ options={[]}
+ placeholder="Group by attribute…"
+ className="min-w-[12rem]"
+ />
+ <LemonInputSelect
+ mode="multiple"
+ size="small"
+ allowCustomValues
+ value={filterStrings}
+ onChange={setFilterStrings}
+ options={[]}
+ placeholder="Filter attribute=value…"
+ className="min-w-[14rem]"
+ />
<DateFilter
size="small"
dateFrom={dateFrom}
@@ -172,16 +237,47 @@ export const MetricsViewer = (): JSX.Element => {
allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks']}
use24HourFormat
/>
+ <LemonSegmentedButton
+ size="small"
+ value={viewMode}
+ options={VIEW_MODE_OPTIONS}
+ onChange={(value) => setViewMode(value)}
+ />
+ {viewMode === 'stat' && (
+ <LemonSelect
+ size="small"
+ value={statSummary}
+ options={SUMMARY_OPTIONS}
+ onChange={(value) => setStatSummary(value)}
+ />
+ )}
+ <LemonSwitch
+ label="Live"
+ checked={liveRefresh}
+ onChange={setLiveRefresh}
+ tooltip={`Auto-refresh every ${LIVE_REFRESH_MS / 1000}s`}
+ bordered
+ />
</div>
<div className="relative h-[360px] border rounded p-3">
{!hasMetricName ? (
<div className="h-full flex items-center justify-center text-secondary text-sm">
Pick a metric to see its time series.
</div>
+ ) : hasResults && viewMode === 'stat' ? (
+ <MetricStatPanel
+ title={metricName}
+ summary={statSummary}
+ aggregation={aggregation}
+ total={statTotal}
+ values={sparklineValues}
+ labels={sparklineLabels.map(renderLabel)}
+ anomaly={anomalyBadge}
+ />
) : hasResults ? (
<Sparkline
type="line"
- data={[{ name: aggregation, values: sparklineValues, color: 'data-color-1' }]}
+ data={chartSeries}
labels={sparklineLabels}
className="w-full h-full"
withXScale={withXScale}
@@ -194,6 +290,7 @@ export const MetricsViewer = (): JSX.Element => {
) : null}
{queryResultsLoading && <SpinnerOverlay />}
</div>
+ {viewMode === 'chart' && hasResults && <MetricsChartLegend series={chartSeries} />}
</div>
)
}
diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.ts
new file mode 100644
index 000000000000..d652e02fa7c8
--- /dev/null
+++ b/products/metrics/frontend/components/metricsSeries.ts
@@ -0,0 +1,16 @@
+import type { _MetricSeriesApi } from 'products/metrics/frontend/generated/api.schemas'
+
+// PostHog defines data-color-1..15 in vars.scss; cycle through them so each series gets a distinct line.
+const SERIES_COLOR_COUNT = 15
+
+export const seriesColor = (index: number): string => `data-color-${(index % SERIES_COLOR_COUNT) + 1}`
+
+// Human-readable series name from its label map (e.g. "service.name=checkout, env=prod"),
+// falling back to the metric name then a provided default for ungrouped/unlabelled series.
+export const formatSeriesName = (series: _MetricSeriesApi, fallback: string): string => {
+ const entries = Object.entries(series.labels ?? {})
+ if (entries.length > 0) {
+ return entries.map(([key, value]) => `${key}=${value}`).join(', ')
+ }
+ return series.metric_name ?? fallback
+}
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 808500eb6b78..9fc4b347af83 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -1,22 +1,55 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { type MetricSummary } from 'lib/components/Metric/metricSummary'
+import { type SparklineTimeSeries } from 'lib/components/Sparkline'
import { dayjs } from 'lib/dayjs'
import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
-import { metricsQueryCreate } from 'products/metrics/frontend/generated/api'
-import type { _MetricSeriesApi } from 'products/metrics/frontend/generated/api.schemas'
+import { metricsCharacterizeCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'
+import type {
+ _MetricAnomalyReportApi,
+ _MetricFilterApi,
+ _MetricSeriesApi,
+ MetricAnomalyDirectionEnumApi,
+} from 'products/metrics/frontend/generated/api.schemas'
+import { formatSeriesName, seriesColor } from './metricsSeries'
import type { metricsViewerLogicType } from './metricsViewerLogicType'
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95'
+// `chart` shows the time series; `stat` shows a single headline value + change pill (a Grafana "stat" panel).
+export type MetricsViewMode = 'chart' | 'stat'
+
export type MetricsViewerSeries = _MetricSeriesApi
+// Display shape for the stat card's "vs baseline" anomaly badge (null = no anomaly / flat metric).
+export interface MetricsAnomalyBadge {
+ direction: MetricAnomalyDirectionEnumApi
+ percent: number
+ baselineMean: number
+ anomalyMean: number
+ onsetTime: string | null
+}
+
const DEFAULT_AGGREGATION: MetricAggregation = 'sum'
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.
+const ANOMALY_WINDOW_FRACTION = 0.2
+export const LIVE_REFRESH_MS = 15_000
+const LIVE_REFRESH_KEY = 'metricsLiveRefresh'
+
+// Parse a "key=value" chip into an equality filter. Returns null for malformed input (no key before '=').
+const parseFilter = (raw: string): _MetricFilterApi | null => {
+ const eq = raw.indexOf('=')
+ if (eq <= 0) {
+ return null
+ }
+ return { key: raw.slice(0, eq).trim(), op: 'eq', value: raw.slice(eq + 1).trim() }
+}
const resolveDate = (value: string | null | undefined): string | null => {
if (!value) {
@@ -36,6 +69,11 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
setDateFrom: (dateFrom: string | null) => ({ dateFrom }),
setDateTo: (dateTo: string | null) => ({ dateTo }),
+ setViewMode: (viewMode: MetricsViewMode) => ({ viewMode }),
+ setStatSummary: (statSummary: MetricSummary) => ({ statSummary }),
+ setLiveRefresh: (liveRefresh: boolean) => ({ liveRefresh }),
+ setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
+ setFilterStrings: (filterStrings: string[]) => ({ filterStrings }),
// AbortController plumbing mirrors logsViewerDataLogic: a `cancelInProgress`
// action aborts the previous controller before storing the new one.
setQueryAbortController: (controller: AbortController | null) => ({ controller }),
@@ -49,18 +87,42 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
],
dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],
+ viewMode: ['chart' as MetricsViewMode, { setViewMode: (_, { viewMode }) => viewMode }],
+ // 'latest' (current value) is the natural default for a live single-metric stat.
+ statSummary: ['latest' as MetricSummary, { setStatSummary: (_, { statSummary }) => statSummary }],
+ liveRefresh: [false, { setLiveRefresh: (_, { liveRefresh }) => liveRefresh }],
+ // Attribute keys to split the metric into one series each (e.g. ['service.name', 'env']).
+ groupByKeys: [[] as string[], { setGroupByKeys: (_, { groupByKeys }) => groupByKeys }],
+ // Raw "key=value" filter chips; parsed into query filters by the `queryFilters` selector.
+ filterStrings: [[] as string[], { setFilterStrings: (_, { filterStrings }) => filterStrings }],
queryAbortController: [
null as AbortController | null,
{ setQueryAbortController: (_, { controller }) => controller },
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
cancelInProgressQuery: ({ controller }) => {
if (values.queryAbortController !== null) {
values.queryAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)
}
actions.setQueryAbortController(controller)
},
+ setLiveRefresh: ({ liveRefresh }) => {
+ if (!liveRefresh) {
+ cache.disposables.dispose(LIVE_REFRESH_KEY)
+ return
+ }
+ // pauseOnPageHidden (default) stops polling on a hidden tab and resumes on focus.
+ cache.disposables.add(() => {
+ const intervalId = setInterval(() => {
+ actions.fetchQueryResults({})
+ if (values.viewMode === 'stat') {
+ actions.fetchAnomaly({})
+ }
+ }, LIVE_REFRESH_MS)
+ return () => clearInterval(intervalId)
+ }, LIVE_REFRESH_KEY)
+ },
})),
loaders(({ values, actions }) => ({
queryResults: [
@@ -87,6 +149,10 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
aggregation: values.aggregation,
dateFrom: dateFromISO,
...(dateToISO ? { dateTo: dateToISO } : {}),
+ ...(values.groupByKeys.length
+ ? { groupBy: values.groupByKeys.map((key) => ({ key })) }
+ : {}),
+ ...(values.queryFilters.length ? { filters: values.queryFilters } : {}),
},
},
{ signal: controller.signal }
@@ -97,12 +163,86 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
},
},
],
+ anomalyReport: [
+ null as _MetricAnomalyReportApi | null,
+ {
+ clearAnomaly: () => null,
+ fetchAnomaly: async (_, breakpoint) => {
+ const trimmedName = values.metricName.trim()
+ const fromISO = resolveDate(values.dateFrom)
+ if (!trimmedName || !fromISO) {
+ return null
+ }
+ const toISO = resolveDate(values.dateTo) ?? dayjs().toISOString()
+ const spanMs = dayjs(toISO).diff(dayjs(fromISO))
+ if (spanMs <= 0) {
+ return null
+ }
+ const anomalyFrom = dayjs(toISO)
+ .subtract(spanMs * ANOMALY_WINDOW_FRACTION, 'ms')
+ .toISOString()
+ await breakpoint(300)
+ const report = await metricsCharacterizeCreate(String(values.currentTeamId), {
+ query: {
+ metricName: trimmedName,
+ aggregation: values.aggregation,
+ anomalyFrom,
+ anomalyTo: toISO,
+ ...(values.queryFilters.length ? { filters: values.queryFilters } : {}),
+ },
+ })
+ breakpoint()
+ return report
+ },
+ },
+ ],
})),
selectors({
hasMetricName: [(s) => [s.metricName], (metricName) => metricName.trim().length > 0],
+ queryFilters: [
+ (s) => [s.filterStrings],
+ (filterStrings: string[]): _MetricFilterApi[] =>
+ filterStrings.map(parseFilter).filter((f): f is _MetricFilterApi => f !== null),
+ ],
// The viewer renders the first series only for now; group-by lands
// multi-series rendering in a later PR.
- sparklineValues: [(s) => [s.queryResults], (results) => (results[0]?.points ?? []).map((p) => p.value)],
- sparklineLabels: [(s) => [s.queryResults], (results) => (results[0]?.points ?? []).map((p) => p.time)],
+ // Metrics has no compare/previous-series concept, so "current" is simply the first series.
+ currentSeries: [(s) => [s.queryResults], (results): MetricsViewerSeries | undefined => results[0]],
+ // All series rendered as chart lines (a group-by query returns one series per label combination).
+ // The x-axis labels come from `sparklineLabels` (the backend grids every series onto one time axis).
+ chartSeries: [
+ (s) => [s.queryResults, s.metricName],
+ (results: MetricsViewerSeries[], metricName: string): SparklineTimeSeries[] =>
+ results.map((series, index) => ({
+ name: formatSeriesName(series, metricName),
+ values: series.points.map((p) => p.value),
+ color: seriesColor(index),
+ })),
+ ],
+ sparklineValues: [
+ (s) => [s.currentSeries],
+ (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.value),
+ ],
+ sparklineLabels: [
+ (s) => [s.currentSeries],
+ (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.time),
+ ],
+ // The stat card summarizes the per-bucket `sparklineValues` into one headline value;
+ // `statTotal` is the grand total across buckets (the basis for the 'total' summary).
+ statTotal: [(s) => [s.sparklineValues], (values: number[]) => values.reduce((sum, v) => sum + v, 0)],
+ // Display shape for the anomaly badge — null when there's no report or the metric is flat.
+ anomalyBadge: [
+ (s) => [s.anomalyReport],
+ (report: _MetricAnomalyReportApi | null): MetricsAnomalyBadge | null =>
+ report && report.direction !== 'flat'
+ ? {
+ direction: report.direction,
+ percent: Math.abs(Math.round((report.change_ratio - 1) * 100)),
+ baselineMean: report.baseline_mean,
+ anomalyMean: report.anomaly_mean,
+ onsetTime: report.onset_time,
+ }
+ : null,
+ ],
}),
])
diff --git a/products/metrics/package.json b/products/metrics/package.json
index d553ace6ffb2..823b831681e8 100644
--- a/products/metrics/package.json
+++ b/products/metrics/package.json
@@ -5,6 +5,7 @@
"backend:contract-check": "echo 'Contract files unchanged'"
},
"dependencies": {
+ "@posthog/quill-charts": "workspace:*",
"kea": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",