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(insights): explain the Metric change pill with a tooltip (#64912)

Sam Pennington78999586939c
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.tsx b/frontend/src/scenes/insights/views/Metric/Metric.tsx
index ebe70b54413c..d1da3f273599 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.tsx
+++ b/frontend/src/scenes/insights/views/Metric/Metric.tsx
@@ -17,12 +17,14 @@ import { insightLogic } from '../../insightLogic'
import {
computeMetricSummary,
computeMetricSummaryChange,
+ getMetricChangeTooltip,
METRIC_COLOR_BY_DIRECTION_DEFAULT,
METRIC_DEFAULT_DECREASE_COLOR,
METRIC_DEFAULT_INCREASE_COLOR,
METRIC_SHOW_CHANGE_DEFAULT,
METRIC_SUMMARY_DEFAULT,
METRIC_SUMMARY_LABELS,
+ selectCurrentSeries,
selectPreviousSeriesSummary,
} from './Metric.utils'
@@ -33,11 +35,12 @@ const makeChangeColor = (hex: string): { background: string; foreground: string
export function Metric({ inCardView }: ChartParams): JSX.Element {
const { insightProps } = useValues(insightLogic)
- const { insightData, trendsFilter, compareFilter } = useValues(insightVizDataLogic(insightProps))
+ const { insightData, trendsFilter, interval } = useValues(insightVizDataLogic(insightProps))
const { baseCurrency } = useValues(teamLogic)
const theme = useChartTheme()
- const resultSeries = insightData?.result?.[0] as TrendResult | undefined
+ const results = insightData?.result as TrendResult[] | undefined
+ const resultSeries = selectCurrentSeries(results)
// `count` is typed as a number but can be absent at runtime, which would render a blank tile.
if (!resultSeries || resultSeries.count == null) {
@@ -48,17 +51,13 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
const headlineValue = computeMetricSummary(summary, resultSeries.count, resultSeries.data)
const showChange = trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT
- // When "compare to previous" is on, total/average compare against the previous period (matched by
- // compare_label) instead of the within-window first→last movement.
- const previousSeries = selectPreviousSeriesSummary(
- !!compareFilter?.compare,
- insightData?.result as TrendResult[] | undefined
- )
+ const previousSeries = selectPreviousSeriesSummary(results)
const change = computeMetricSummaryChange(
summary,
{ total: resultSeries.count, data: resultSeries.data },
previousSeries
)
+ const changeTooltip = getMetricChangeTooltip(summary, previousSeries != null, interval)
const isIncrease = (change?.value ?? 0) >= 0
const pillColors = {
@@ -87,6 +86,7 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
changeSize="md"
changeInline
change={change}
+ changeTooltip={changeTooltip}
hoverChangeFromPreviousPoint
{...pillColors}
restingSubtitle={METRIC_SUMMARY_LABELS[summary]}
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
index 11a2e21ae596..237a68a5b3ba 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
@@ -1,11 +1,15 @@
import { type MetricChange } from '@posthog/quill-charts'
+import { IntervalType } from '~/types'
+
import {
computeMetricChange,
computeMetricSummary,
computeMetricSummaryChange,
+ getMetricChangeTooltip,
type MetricSeriesSummary,
MetricSummary,
+ selectCurrentSeries,
selectPreviousSeriesSummary,
} from './Metric.utils'
@@ -165,28 +169,104 @@ describe('selectPreviousSeriesSummary', () => {
const cases: {
name: string
- enabled: boolean
results: { count: number; data: number[]; compare_label?: string }[] | undefined
expected: MetricSeriesSummary | undefined
}[] = [
- { name: 'compare disabled → no previous', enabled: false, results: [current, previous], expected: undefined },
- { name: 'undefined results → no previous', enabled: true, results: undefined, expected: undefined },
- { name: 'no previous-labelled series → no previous', enabled: true, results: [current], expected: undefined },
+ { name: 'undefined results → no previous', results: undefined, expected: undefined },
+ { name: 'no previous-labelled series → no previous', results: [current], expected: undefined },
{
name: 'picks the previous-labelled series',
- enabled: true,
results: [current, previous],
expected: { total: 300, data: [50, 100, 150] },
},
{
name: 'matches by compare_label, not array position',
- enabled: true,
results: [previous, current],
expected: { total: 300, data: [50, 100, 150] },
},
]
- it.each(cases)('$name', ({ enabled, results, expected }) => {
- expect(selectPreviousSeriesSummary(enabled, results)).toEqual(expected)
+ it.each(cases)('$name', ({ results, expected }) => {
+ expect(selectPreviousSeriesSummary(results)).toEqual(expected)
+ })
+})
+
+describe('selectCurrentSeries', () => {
+ const current = { count: 600, data: [100, 200, 300], compare_label: 'current' }
+ const previous = { count: 300, data: [50, 100, 150], compare_label: 'previous' }
+ const unlabelled = { count: 600, data: [100, 200, 300] }
+
+ const cases: {
+ name: string
+ results: { count: number; data: number[]; compare_label?: string }[] | undefined
+ expected: { count: number; data: number[]; compare_label?: string } | undefined
+ }[] = [
+ { name: 'undefined results → undefined', results: undefined, expected: undefined },
+ { name: 'single unlabelled series (no comparison) → that series', results: [unlabelled], expected: unlabelled },
+ { name: 'picks current by compare_label, not array position', results: [previous, current], expected: current },
+ ]
+
+ it.each(cases)('$name', ({ results, expected }) => {
+ expect(selectCurrentSeries(results)).toEqual(expected)
+ })
+})
+
+describe('getMetricChangeTooltip', () => {
+ const firstLast = (noun: string): string =>
+ `Comparing the first ${noun}'s value to the most recent ${noun}'s value.`
+
+ const cases: {
+ name: string
+ summary: MetricSummary
+ hasComparison: boolean
+ interval: IntervalType | null | undefined
+ expected: string
+ }[] = [
+ {
+ name: 'total vs previous period',
+ summary: 'total',
+ hasComparison: true,
+ interval: 'day',
+ expected: "Comparing this period's total to the previous period's total.",
+ },
+ {
+ name: 'average vs previous period',
+ summary: 'average',
+ hasComparison: true,
+ interval: 'day',
+ expected: "Comparing this period's average to the previous period's average.",
+ },
+ {
+ name: 'latest ignores the comparison period',
+ summary: 'latest',
+ hasComparison: true,
+ interval: 'day',
+ expected: firstLast('day'),
+ },
+ {
+ name: 'total falls back to first→last without a comparison',
+ summary: 'total',
+ hasComparison: false,
+ interval: 'day',
+ expected: firstLast('day'),
+ },
+ {
+ name: 'non-day interval flows into the noun',
+ summary: 'latest',
+ hasComparison: false,
+ interval: 'hour',
+ expected: firstLast('hour'),
+ },
+ {
+ name: 'missing interval falls back to "day"',
+ summary: 'latest',
+ hasComparison: false,
+ interval: null,
+ expected: firstLast('day'),
+ },
+ ]
+
+ it.each(cases)('$name', ({ summary, hasComparison, interval, expected }) => {
+ expect(getMetricChangeTooltip(summary, hasComparison, interval)).toBe(expected)
})
})
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
index bdb0fd3d1e33..07649bfb19cc 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
@@ -1,5 +1,7 @@
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×
@@ -67,22 +69,20 @@ interface ComparableSeries {
compare_label?: string | null
}
-// The previous comparison period, when "compare to previous" is on. Matched by `compare_label` rather
-// than position so it stays correct if the results array ever holds more than the current series.
+// Matched by `compare_label`, not array position (the backend doesn't guarantee order).
export function selectPreviousSeriesSummary(
- compareEnabled: boolean,
results: readonly ComparableSeries[] | undefined
): MetricSeriesSummary | undefined {
- if (!compareEnabled || !results) {
- return undefined
- }
- const previous = results.find((series) => series.compare_label === 'previous')
+ const previous = results?.find((series) => series.compare_label === 'previous')
return previous ? { total: previous.count, data: previous.data } : undefined
}
-// The change pill, matched to the chosen summary:
-// - `total`/`average` with a comparison period → this period's total/average vs the previous period's.
-// - `latest`, or `total`/`average` without a comparison period → first → last of the current series.
+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,
@@ -95,3 +95,18 @@ export function computeMetricSummaryChange(
}
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/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 2348ea7757d0..0e0dce8c69dc 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -74,7 +74,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. `config.legend.renderItem(defaultNode, item)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
-- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`. `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point).
+- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`. `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).
- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index 878dcbc0a4f7..70ed67e8f3d6 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -1,8 +1,22 @@
-import React, { useMemo, useState } from 'react'
+import {
+ arrow,
+ autoUpdate,
+ flip,
+ FloatingArrow,
+ FloatingPortal,
+ offset,
+ shift,
+ useFloating,
+ useHover,
+ useInteractions,
+ useRole,
+} from '@floating-ui/react'
+import React, { useMemo, useRef, useState } from 'react'
import { Sparkline } from '../../charts/Sparkline/Sparkline'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import type { ChartTheme } from '../../core/types'
+import { TOOLTIP_FALLBACK_BG, TOOLTIP_FALLBACK_COLOR } from '../../overlays/TooltipSurface'
import { percentage } from '../../utils/format'
import { type MetricChange, resolveDelta } from './resolveDelta'
import { useAnimatedNumber } from './useAnimatedNumber'
@@ -44,6 +58,8 @@ export interface MetricCardProps {
changeSize?: 'sm' | 'md'
/** Render the change pill inline next to the headline instead of in the header row. */
changeInline?: boolean
+ /** Tooltip shown on hover over the change pill, e.g. explaining what it compares. */
+ changeTooltip?: string
positiveColor?: ChangeColor
negativeColor?: ChangeColor
/** Caption under the headline. Defaults to `labels[activeIndex]` when a sparkline is present.
@@ -101,6 +117,7 @@ function MetricCardInner({
goodDirection = 'up',
changeSize = 'sm',
changeInline = false,
+ changeTooltip,
positiveColor = DEFAULT_POSITIVE_COLOR,
negativeColor = DEFAULT_NEGATIVE_COLOR,
subtitle,
@@ -146,6 +163,8 @@ function MetricCardInner({
fallbackChangePercent,
formatChange,
})
+ // The tooltip describes the resting comparison, so hide it once the pill shows the per-point delta.
+ const activeChangeTooltip = usePrevPointHover ? undefined : changeTooltip
const headlineDisplay = sparklineData ? formatValue(animatedValue) : formatValue(restingValue)
const resolvedSubtitle =
subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labels?.[activeIndex])
@@ -174,6 +193,7 @@ function MetricCardInner({
label={headerDelta.label}
colors={pillColors}
size={changeSize}
+ tooltip={activeChangeTooltip}
/>
)}
</div>
@@ -182,7 +202,13 @@ function MetricCardInner({
{changeInline && delta != null ? (
<div className="flex items-center justify-between gap-2">
{renderedHeadline}
- <ChangePill positive={positive} label={delta.label} colors={pillColors} size={changeSize} />
+ <ChangePill
+ positive={positive}
+ label={delta.label}
+ colors={pillColors}
+ size={changeSize}
+ tooltip={activeChangeTooltip}
+ />
</div>
) : (
renderedHeadline
@@ -249,11 +275,12 @@ interface ChangePillProps {
label: React.ReactNode
colors: ChangeColor
size?: 'sm' | 'md'
+ tooltip?: string
}
-function ChangePill({ positive, label, colors, size = 'sm' }: ChangePillProps): React.ReactElement {
+function ChangePill({ positive, label, colors, size = 'sm', tooltip }: ChangePillProps): React.ReactElement {
const sizeClasses = size === 'md' ? 'gap-1.5 px-2.5 py-1 text-sm' : 'gap-1 px-2 py-0.5 text-xs'
- return (
+ const pill = (
<div
className={`inline-flex items-center rounded-full font-medium transition-colors ${sizeClasses}`}
style={{ background: colors.background, color: colors.foreground }}
@@ -263,6 +290,76 @@ function ChangePill({ positive, label, colors, size = 'sm' }: ChangePillProps):
<span className="tabular-nums">{label}</span>
</div>
)
+ if (!tooltip) {
+ return pill
+ }
+ return <ChangePillTooltip content={tooltip}>{pill}</ChangePillTooltip>
+}
+
+// A hover tooltip for the change pill. Built on floating-ui directly so the charts package stays
+// dependency-light (no app Tooltip import), but styled with the app's tooltip surface tokens so it
+// reads as a normal PostHog tooltip and stays legible over the tile's own --card background. Falls
+// back to the chart tooltip constants in non-app hosts that don't define those vars.
+const TOOLTIP_BG = `var(--color-bg-surface-tooltip, ${TOOLTIP_FALLBACK_BG})`
+const TOOLTIP_COLOR = `var(--color-text-primary-inverse, ${TOOLTIP_FALLBACK_COLOR})`
+
+function ChangePillTooltip({
+ content,
+ children,
+}: {
+ content: React.ReactNode
+ children: React.ReactNode
+}): React.ReactElement {
+ const [open, setOpen] = useState(false)
+ const arrowRef = useRef<SVGSVGElement>(null)
+ const { refs, floatingStyles, context } = useFloating({
+ open,
+ onOpenChange: setOpen,
+ placement: 'top',
+ strategy: 'fixed',
+ whileElementsMounted: autoUpdate,
+ middleware: [offset(8), flip(), shift({ padding: 8 }), arrow({ element: arrowRef })],
+ })
+ const hover = useHover(context, { move: false })
+ const role = useRole(context, { role: 'tooltip' })
+ const { getReferenceProps, getFloatingProps } = useInteractions([hover, role])
+
+ return (
+ <>
+ <span ref={refs.setReference} {...getReferenceProps()} className="inline-flex">
+ {children}
+ </span>
+ {open && (
+ <FloatingPortal>
+ <div
+ ref={refs.setFloating}
+ {...getFloatingProps()}
+ className="pointer-events-none max-w-80 rounded-md px-3 py-1.5 text-xs font-normal leading-snug"
+ // Dynamic only: floating-ui position + app tooltip tokens. Static styling stays in Tailwind.
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ ...floatingStyles,
+ zIndex: 'var(--z-tooltip, 9999)',
+ background: TOOLTIP_BG,
+ color: TOOLTIP_COLOR,
+ boxShadow: 'var(--modal-shadow-elevation, 0 2px 8px rgb(0 0 0 / 18%))',
+ }}
+ >
+ {content}
+ {/* `currentColor` + the bg-colored `color` paints the arrow the same surface color
+ (a CSS var can't go in the SVG `fill` attribute directly). */}
+ <FloatingArrow
+ ref={arrowRef}
+ context={context}
+ fill="currentColor"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ color: TOOLTIP_BG }}
+ />
+ </div>
+ </FloatingPortal>
+ )}
+ </>
+ )
}
function Chevron({ up, size = 10 }: { up: boolean; size?: number }): React.ReactElement {
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
index c0ce5a8a89ee..549cf37a56ba 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
@@ -46,6 +46,7 @@ from posthog.schema import (
InCohortVia,
IntervalType,
MathGroupTypeIndex,
+ MetricSummary,
MultipleBreakdownType,
PersonPropertyFilter,
PropertyMathType,
@@ -687,6 +688,42 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual("Formula (A+2*B)", response.results[0]["label"])
self.assertEqual(True, response.results[0]["compare"])
+ def test_metric_display_forces_compare(self):
+ self._create_test_events()
+
+ response = self._run_trends_query(
+ "2020-01-15",
+ "2020-01-19",
+ IntervalType.DAY,
+ [EventsNode(event="$pageview")],
+ TrendsFilter(display=ChartDisplayType.METRIC),
+ )
+
+ self.assertEqual(2, len(response.results))
+ self.assertEqual("current", response.results[0]["compare_label"])
+ self.assertEqual("previous", response.results[1]["compare_label"])
+
+ @parameterized.expand(
+ [
+ ("all_time", "all", TrendsFilter(display=ChartDisplayType.METRIC)),
+ ("pill_hidden", "2020-01-15", TrendsFilter(display=ChartDisplayType.METRIC, metricShowChange=False)),
+ (
+ "latest_summary",
+ "2020-01-15",
+ TrendsFilter(display=ChartDisplayType.METRIC, metricSummary=MetricSummary.LATEST),
+ ),
+ ]
+ )
+ def test_metric_display_does_not_force_compare(self, _name, date_from, trends_filter):
+ self._create_test_events()
+
+ response = self._run_trends_query(
+ date_from, None, IntervalType.DAY, [EventsNode(event="$pageview")], trends_filter
+ )
+
+ self.assertEqual(1, len(response.results))
+ self.assertNotIn("compare_label", response.results[0])
+
def test_formula_with_compare_to_week(self):
self._create_test_events()
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index 5bce70a20f7c..f17291e027ab 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py
@@ -20,6 +20,7 @@ from posthog.schema import (
CachedTrendsQueryResponse,
ChartDisplayType,
Compare,
+ CompareFilter,
CompareItem,
DashboardFilter,
DataWarehouseEventsModifier,
@@ -32,6 +33,7 @@ from posthog.schema import (
InCohortVia,
InsightActorsQueryOptionsResponse,
IntervalType,
+ MetricSummary,
MultipleBreakdownOptions,
MultipleBreakdownType,
QueryTiming,
@@ -124,6 +126,20 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
# Use the new function to handle WAU/MAU conversions
query = convert_active_user_math_based_on_interval(query)
+ # The Metric change pill compares to the previous period, but the display has no compare toggle —
+ # force it when the pill needs it (shown, not "latest", and a previous period exists).
+ if (
+ query.trendsFilter
+ and query.trendsFilter.display == ChartDisplayType.METRIC
+ and query.trendsFilter.metricShowChange is not False
+ and query.trendsFilter.metricSummary != MetricSummary.LATEST
+ and not (query.dateRange and query.dateRange.date_from == "all")
+ ):
+ if query.compareFilter is None:
+ query.compareFilter = CompareFilter(compare=True)
+ else:
+ query.compareFilter.compare = True
+
super().__init__(query, team=team, timings=timings, modifiers=modifiers, limit_context=limit_context, user=user)
def __post_init__(self):