: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): show which labels drove a metric's move (#89794)
Daniel Viscafb73a7c09ea2
diff --git a/products/metrics/frontend/components/MetricsAnomalyPanel.tsx b/products/metrics/frontend/components/MetricsAnomalyPanel.tsxnew file mode 100644index 000000000000..b23de9e38633--- /dev/null+++ b/products/metrics/frontend/components/MetricsAnomalyPanel.tsx@@ -0,0 +1,99 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonDivider, LemonDropdown, LemonTag } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { MetricTopMoverRow } from '../metricsAnomaly'+import { type MetricsAnomalyBadge, metricsViewerLogic } from './metricsViewerLogic'++const MoverRow = ({ mover, onClick }: { mover: MetricTopMoverRow; onClick: () => void }): JSX.Element => (+ <LemonButton+ fullWidth+ size="small"+ onClick={mover.isFilterable ? onClick : undefined}+ disabledReason={mover.isFilterable ? undefined : 'These series report no value for this attribute'}+ data-attr="metrics-anomaly-mover"+ >+ <div className="flex items-center justify-between gap-2 w-full min-w-0">+ <span className="truncate font-mono text-xs">+ {mover.key}={mover.isFilterable ? mover.label : <span className="italic">(none)</span>}+ </span>+ <span className="shrink-0 text-xs text-secondary">+ {mover.isNew ? (+ <LemonTag type="warning">New</LemonTag>+ ) : (+ <>+ {humanFriendlyNumber(mover.baselineValue)} → {humanFriendlyNumber(mover.anomalyValue)}{' '}+ <span className={mover.direction === 'up' ? 'text-danger' : 'text-success'}>+ {mover.direction === 'up' ? '▲' : '▼'} {mover.percent}%+ </span>+ </>+ )}+ </span>+ </div>+ </LemonButton>+)++/**+ * The "what changed" panel behind the anomaly badge.+ *+ * The backend already attributes a metric's move to the label values that drove it+ * (`anomaly.py`); this puts that ranking in front of the user, and lets one click narrow the+ * chart to a finding so an investigation can stack.+ */+export function MetricsAnomalyPanel({ anomaly }: { anomaly: MetricsAnomalyBadge }): JSX.Element {+ const { anomalyTopMovers } = useValues(metricsViewerLogic)+ const { addAttributeFilter } = useActions(metricsViewerLogic)+ const [isOpen, setIsOpen] = useState(false)++ return (+ <LemonDropdown+ visible={isOpen}+ onClickOutside={() => setIsOpen(false)}+ placement="bottom-start"+ overlay={+ <div className="w-80 max-w-full p-1">+ <div className="px-2 py-1 text-xs text-secondary">+ Baseline {humanFriendlyNumber(anomaly.baselineMean)} → recent{' '}+ {humanFriendlyNumber(anomaly.anomalyMean)}+ {anomaly.onsetTime ? `, from ${dayjs(anomaly.onsetTime).format('D MMM HH:mm')}` : ''}+ </div>+ <LemonDivider className="my-1" />+ {anomalyTopMovers.length ? (+ <>+ <div className="px-2 py-1 text-xs font-semibold">Biggest movers</div>+ {anomalyTopMovers.map((mover) => (+ <MoverRow+ key={`${mover.key}:${mover.label}`}+ mover={mover}+ onClick={() => {+ addAttributeFilter(mover.key, mover.label)+ setIsOpen(false)+ }}+ />+ ))}+ <div className="px-2 py-1 text-xs text-secondary">Pick one to narrow the chart to it.</div>+ </>+ ) : (+ <div className="px-2 py-1 text-xs text-secondary">+ No single label stands out, so the change looks spread across the metric. Group by an+ attribute to break it down.+ </div>+ )}+ </div>+ }+ >+ <LemonTag+ type="warning"+ onClick={() => setIsOpen(!isOpen)}+ className="cursor-pointer"+ data-attr="metrics-viewer-anomaly-badge"+ >+ {anomaly.direction === 'up' ? '▲' : '▼'} {anomaly.percent}% vs baseline+ </LemonTag>+ </LemonDropdown>+ )+}diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 01836539309b..b81864dc2236 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -10,9 +10,7 @@ import {LemonInputSelect,LemonSelect,LemonSwitch,- LemonTag,SpinnerOverlay,- Tooltip,} from '@posthog/lemon-ui'import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'@@ -27,7 +25,6 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'-import { humanFriendlyNumber } from 'lib/utils/numbers'import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'import { urls } from 'scenes/urls'@@ -46,6 +43,7 @@ import { traceUrl } from 'products/tracing/frontend/traceLinks'import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'import { MetricNameFilter } from './MetricNameFilter'import { metricNamePickerLogic } from './metricNamePickerLogic'+import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'import { MetricsChartSettings } from './MetricsChartSettings'import { type MetricsExemplar } from './MetricsExemplarMarkers'import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'@@ -60,7 +58,6 @@ import {LIVE_REFRESH_MS,METRIC_FILTER_OPERATOR_ALLOWLIST,MetricAggregation,- MetricsAnomalyBadge,metricsViewerLogic,RECOMMENDED_AGGREGATION_BY_TYPE,} from './metricsViewerLogic'@@ -342,7 +339,7 @@ export const MetricsViewer = (): JSX.Element => {/><MetricsChartSettings /><MetricsRelatedMenu />- {anomalyBadge && <MetricsAnomalyTag anomaly={anomalyBadge} />}+ {anomalyBadge && <MetricsAnomalyPanel anomaly={anomalyBadge} />}<MetricsLogsSourceTag metricName={metricName} /></div><div className="flex flex-wrap items-center gap-2">@@ -437,17 +434,6 @@ export const MetricsViewer = (): JSX.Element => {// How the recent slice of the window compares against the rest of it, sitting next to the// controls that define the window rather than over the chart, where it would fight the legend.-const MetricsAnomalyTag = ({ anomaly }: { anomaly: MetricsAnomalyBadge }): JSX.Element => (- <Tooltip- title={`Baseline ${humanFriendlyNumber(anomaly.baselineMean)} → recent ${humanFriendlyNumber(- anomaly.anomalyMean- )}${anomaly.onsetTime ? `, onset ${dayjs(anomaly.onsetTime).format('D MMM HH:mm')}` : ''}`}- >- <LemonTag type="warning" data-attr="metrics-viewer-anomaly-badge">- {anomaly.direction === 'up' ? '▲' : '▼'} {anomaly.percent}% vs baseline- </LemonTag>- </Tooltip>-)// Filter chips + "Add filter" button, mirroring the logs viewer's applied-filters row: picking an// attribute opens the chip for value selection, with suggestions fed by the metrics attribute endpoints.diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 3ff5c9a7be84..5c6ce645dfb8 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -354,6 +354,40 @@ describe('metricsViewerLogic', () => {expect(logic.values.queryFilters).toEqual([expected])})+ // The anomaly panel's one-click drilldown: clicking a label value that moved narrows the+ // chart to it. Appending rather than replacing is the point — an investigation stacks+ // findings, and replacing would silently drop the service the user had already pinned.+ describe('addAttributeFilter', () => {+ it('adds the label value as a chip alongside the existing filters', () => {+ logic.actions.setFilterGroup(+ filterGroupWith([{ key: 'service_name', operator: PropertyOperator.Exact, value: ['web'] }])+ )++ logic.actions.addAttributeFilter('pod', 'api-7f9')++ expect(logic.values.queryFilters).toEqual([+ { key: 'service_name', op: 'eq', value: 'web' },+ { key: 'pod', op: 'eq', value: 'api-7f9' },+ ])+ })++ it('does not stack a duplicate when the same value is clicked twice', () => {+ logic.actions.addAttributeFilter('pod', 'api-7f9')+ logic.actions.addAttributeFilter('pod', 'api-7f9')++ expect(logic.values.queryFilters).toEqual([{ key: 'pod', op: 'eq', value: 'api-7f9' }])+ })++ it('widens the existing chip when a second value of the same key is picked', () => {+ // Two chips on one key are ANDed, and no series can equal both values, so appending+ // would blank the chart with no error rather than showing both pods.+ logic.actions.addAttributeFilter('pod', 'api1')+ logic.actions.addAttributeFilter('pod', 'api2')++ expect(logic.values.queryFilters).toEqual([{ key: 'pod', op: 'regex', value: '^(?:api1|api2)$' }])+ })+ })+// Drives the metric picker's scope. Getting this wrong is silent: the picker// reverts to offering every metric while the filter bar still shows a service.it.each([diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex f6b9aa749b21..c88de81e43eb 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -30,7 +30,7 @@ import {NodeKind,} from '~/queries/schema/schema-general'import { QueryBasedInsightModel } from '~/types'-import { PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'+import { PropertyFilterType, PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'import {metricsAttributesRetrieve,@@ -48,6 +48,7 @@ import { canCreateMetricsInsight, canViewMetrics } from 'products/metrics/fronteimport type { Node } from '../../../../frontend/src/queries/schema/schema-general'import type { _MetricNameApi } from '../generated/api.schemas'+import { type MetricTopMoverRow, topMoverRows } from '../metricsAnomaly'import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY } from '../metricsAttributes'import { correlationServiceNames } from '../metricsLinks'import { metricNamePickerLogic } from './metricNamePickerLogic'@@ -191,6 +192,7 @@ export interface metricsViewerLogicValues {anomalyBadge: MetricsAnomalyBadge | nullanomalyReport: _MetricAnomalyReportApi | nullanomalyReportLoading: boolean+ anomalyTopMovers: MetricTopMoverRow[]attributeEndpointFilters: Record<string, string>attributeKeyOptions: {key: string@@ -246,6 +248,13 @@ export interface metricsViewerLogicActions {setServices: (services: string[]) => {services: string[]} // metricNamePickerLogic+ addAttributeFilter: (+ key: string,+ value: string+ ) => {+ key: string+ value: string+ }addGoalLine: () => {value: true}@@ -427,6 +436,7 @@ export interface metricsViewerLogicMeta {attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]hasResults: (queryResults: _MetricSeriesApi[]) => boolean+ anomalyTopMovers: (anomalyReport: _MetricAnomalyReportApi | null) => MetricTopMoverRow[]anomalyBadge: (anomalyReport: _MetricAnomalyReportApi | null) => MetricsAnomalyBadge | null}}@@ -457,6 +467,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),+ // Narrows the chart to one label value, from the anomaly panel's ranked movers.+ addAttributeFilter: (key: string, value: string) => ({ key, value }),// Saves the current query as an insight (reusing the last save while the// query is unchanged) and opens the dashboard picker for it.addToDashboard: true,@@ -604,6 +616,43 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([actions.setServices(values.selectedServices)}},+ addAttributeFilter: ({ key, value }) => {+ const inner = values.filterGroup.values[0] as UniversalFiltersGroup+ const existingIndex = inner.values.findIndex(+ (filter) =>+ !isUniversalGroupFilterLike(filter) &&+ 'key' in filter &&+ filter.key === key &&+ 'operator' in filter &&+ filter.operator === PropertyOperator.Exact+ )+ const existing = existingIndex >= 0 ? (inner.values[existingIndex] as UniversalFilterValue) : null+ const existingValues = existing ? toValueStrings('value' in existing ? existing.value : null) : []+ if (existingValues.includes(value)) {+ return+ }+ // Two chips on one key are ANDed, and no series equals both values, so a second pick of+ // the same key widens the chip it already has instead of adding another.+ const chip = {+ type: PropertyFilterType.MetricAttribute,+ key,+ value: [...existingValues, value],+ operator: PropertyOperator.Exact,+ }+ const nextValues = [...inner.values]+ if (existingIndex >= 0) {+ nextValues[existingIndex] = chip as UniversalFilterValue+ } else {+ nextValues.push(chip as UniversalFilterValue)+ }+ actions.setFilterGroup({+ ...values.filterGroup,+ values: [+ { ...inner, values: nextValues as UniversalFiltersGroup['values'] },+ ...values.filterGroup.values.slice(1),+ ],+ })+ },setMetricName: ({ metricName }) => {const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_typeactions.setSelectedMetricType(toKnownMetricType(metricType))@@ -953,6 +1002,13 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([(s) => [s.queryResults],(results: MetricsViewerSeries[]): boolean => (results[0]?.points.length ?? 0) > 0,],+ // The label values behind the current anomaly, ranked. Empty for an ungrouped metric or+ // when nothing stood out, which the panel reports rather than hiding.+ anomalyTopMovers: [+ (s) => [s.anomalyReport],+ (report: _MetricAnomalyReportApi | null): MetricTopMoverRow[] =>+ report ? topMoverRows(report.top_movers) : [],+ ],// Display shape for the anomaly badge — null when there's no report or the metric is flat.anomalyBadge: [(s) => [s.anomalyReport],diff --git a/products/metrics/frontend/metricsAnomaly.test.ts b/products/metrics/frontend/metricsAnomaly.test.tsnew file mode 100644index 000000000000..dd48dfc60cd7--- /dev/null+++ b/products/metrics/frontend/metricsAnomaly.test.ts@@ -0,0 +1,61 @@+import type { _MetricAnomalyDimensionApi } from './generated/api.schemas'+import { topMoverRows } from './metricsAnomaly'++describe('topMoverRows', () => {+ // Typed against the generated contract, so a new required field on the API response+ // breaks these fixtures rather than letting them drift into an incomplete shape.+ const mover = (overrides: Partial<_MetricAnomalyDimensionApi> = {}): _MetricAnomalyDimensionApi => ({+ key: 'pod',+ label: 'api-7f9',+ baseline_value: 100,+ anomaly_value: 150,+ change_ratio: 1.5,+ ...overrides,+ })++ it('keeps the order the backend ranked, which weighs scale as well as ratio', () => {+ // anomaly.py ranks by a magnitude blending ratio with size, so a rounding-error series that+ // tripled does not outrank a large one that moved a lot. Re-sorting on percentage here would+ // put the noise first, and it is the row a user clicks to narrow the chart.+ const rows = topMoverRows([+ mover({+ key: 'service_name',+ label: 'checkout',+ baseline_value: 5000,+ anomaly_value: 6000,+ change_ratio: 1.2,+ }),+ mover({ label: 'debug-sidecar', baseline_value: 0.2, anomaly_value: 1, change_ratio: 5 }),+ ])++ expect(rows.map((row) => row.label)).toEqual(['checkout', 'debug-sidecar'])+ })++ it('reports how far each label value moved', () => {+ const rows = topMoverRows([mover({ baseline_value: 100, anomaly_value: 300, change_ratio: 3 })])+ expect(rows[0]).toMatchObject({ percent: 200, direction: 'up' })+ })++ it('reads a drop as a drop rather than a negative rise', () => {+ const rows = topMoverRows([mover({ baseline_value: 100, anomaly_value: 25, change_ratio: 0.25 })])+ expect(rows[0]).toMatchObject({ percent: 75, direction: 'down' })+ })++ it('calls a label value that did not exist before new, instead of an infinite rise', () => {+ // The backend yields the anomaly value itself for a zero baseline, so a ratio here is+ // meaningless — "500% up" from nothing is noise, "new" is the actual finding.+ const rows = topMoverRows([mover({ baseline_value: 0, anomaly_value: 42, change_ratio: 42 })])+ expect(rows[0]).toMatchObject({ isNew: true, direction: 'up' })+ })++ it('marks a mover with no label value as unfilterable', () => {+ // A group-by on a key some series lack yields '', which no equality filter can express.+ // Left clickable it appends a chip that filters nothing and cannot be deduped away.+ const rows = topMoverRows([mover({ key: 'service_name', label: '' })])+ expect(rows[0]).toMatchObject({ label: '', isFilterable: false })+ })++ it('returns nothing when the metric has no labels to attribute to', () => {+ expect(topMoverRows([])).toEqual([])+ })+})diff --git a/products/metrics/frontend/metricsAnomaly.ts b/products/metrics/frontend/metricsAnomaly.tsnew file mode 100644index 000000000000..08479bd0e0ed--- /dev/null+++ b/products/metrics/frontend/metricsAnomaly.ts@@ -0,0 +1,44 @@+import type { _MetricAnomalyDimensionApi } from './generated/api.schemas'++/** One label value's contribution to a spike, shaped for display. */+export interface MetricTopMoverRow {+ key: string+ label: string+ baselineValue: number+ anomalyValue: number+ /** How far it moved, as a positive percentage. Meaningless when `isNew`. */+ percent: number+ direction: 'up' | 'down'+ /** Absent from the baseline window, so there is no ratio to quote — it simply appeared. */+ isNew: boolean+ /** Whether clicking it can narrow the chart. False for a mover whose label value is empty. */+ isFilterable: boolean+}++/**+ * Shape the label values behind a metric's move for display.+ *+ * Order comes from the backend and is preserved. `anomaly.py` ranks by a magnitude that blends+ * ratio with scale, precisely so a tiny series that tripled does not outrank a large one that+ * moved a lot — re-sorting on percentage here would undo that and put noise at the top.+ *+ * A value with no baseline is reported as new rather than as a huge percentage: the backend+ * yields the anomaly value itself for a zero baseline, so a ratio there says nothing.+ */+export const topMoverRows = (movers: _MetricAnomalyDimensionApi[]): MetricTopMoverRow[] =>+ movers.map((mover) => {+ const isNew = mover.baseline_value === 0+ return {+ key: mover.key,+ label: mover.label,+ baselineValue: mover.baseline_value,+ anomalyValue: mover.anomaly_value,+ percent: isNew ? 0 : Math.abs(Math.round((mover.change_ratio - 1) * 100)),+ // Read off the raw values rather than the ratio, which inverts on a negative baseline.+ direction: (mover.anomaly_value >= mover.baseline_value ? 'up' : 'down') as 'up' | 'down',+ isNew,+ // A group-by on a key some series lack reports an empty label. No equality filter+ // expresses that, so the row stays informative but is not offered as a drilldown.+ isFilterable: mover.label !== '',+ }+ })