: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
fix(insights): stop metric sparklines drawing backwards (#93201)
Christiaan Hendriksen1972bc62eba8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ac2eb6a503b2..5bb2cf367a2c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3144,6 +3144,10 @@ snapshots:hash: v1.k794b7964.bdc893ac78b0c99cb12fe2d3fa70346f932cccab0ae49df0d8e47e4740224266.KsZ8mkjoktS-Fzlo_tl1EQBX5t3-L0MWAbrR6yO2yCoinsights-metric--default--light:hash: v1.k794b7964.48725db2ac1e33838b543ca02ec02a9531421ae1b72a906e08769203b062878a.FYtwisigBj0inQ6P1fYQm_mYSl94iSjrfM-o0EKI8S8+ insights-metric--spanning-a-year--dark:+ hash: v1.k794b7964.5f97cf4718161e626d80e132389dcfe0d0f8d9dfd5ff2f97b7777ff9e8cb5cbf.TXL-US4qjspNzmlqH5w_txyVvAbRT3uK_mCDAL9vtPs+ insights-metric--spanning-a-year--light:+ hash: v1.k794b7964.3a6e3ab182937bbd5c51c357027278325c9617f4caadde765906884951504065.69-j01NBeFdgeEKFT_MD7cnFVM0mZbfKHPE3oCIeppYinsights-paths--edit-scene--dark:hash: v1.k794b7964.757f761d3358c2e0cd9b696b5c12ef58a2dd6914e8a7c17845a3c6e1ceeeeb5b.jeaScSZJiJejwrS-iysxnANEldxNKwwZdN6vV-NfAi8insights-paths--edit-scene--light:diff --git a/frontend/src/scenes/insights/views/Metric/Metric.stories.tsx b/frontend/src/scenes/insights/views/Metric/Metric.stories.tsxindex b9f9aee018ca..2d93ef2538cf 100644--- a/frontend/src/scenes/insights/views/Metric/Metric.stories.tsx+++ b/frontend/src/scenes/insights/views/Metric/Metric.stories.tsx@@ -27,3 +27,48 @@ export default metaexport const Default: Story = {render: () => <InsightVizStory insight={__trendsMetric as any} />,}++// 13 monthly buckets, so the first and last both fall on April 1. Display text repeats there while the+// bucket keys stay unique, which is the case that collapses the last point onto the first whenever the+// sparkline is keyed on display text.+const MONTHLY_DAYS = [+ '2021-04-01',+ '2021-05-01',+ '2021-06-01',+ '2021-07-01',+ '2021-08-01',+ '2021-09-01',+ '2021-10-01',+ '2021-11-01',+ '2021-12-01',+ '2022-01-01',+ '2022-02-01',+ '2022-03-01',+ '2022-04-01',+]+const MONTHLY_DATA = [1240, 1655, 1980, 2410, 2295, 2870, 3320, 3105, 3890, 4260, 4515, 5090, 5480]++const yearSpanInsight = {+ ...__trendsMetric,+ result: [+ {+ ...(__trendsMetric.result[0] as Record<string, unknown>),+ days: MONTHLY_DAYS,+ labels: MONTHLY_DAYS,+ data: MONTHLY_DATA,+ count: MONTHLY_DATA.reduce((sum, value) => sum + value, 0),+ },+ ],+ query: {+ ...__trendsMetric.query,+ source: {+ ...(__trendsMetric.query as any).source,+ dateRange: { date_from: '-12m' },+ interval: 'month',+ },+ },+}++export const SpanningAYear: Story = {+ render: () => <InsightVizStory insight={yearSpanInsight as any} />,+}diff --git a/frontend/src/scenes/insights/views/Metric/Metric.tsx b/frontend/src/scenes/insights/views/Metric/Metric.tsxindex 5f94dd53b358..e364ee7a46a1 100644--- a/frontend/src/scenes/insights/views/Metric/Metric.tsx+++ b/frontend/src/scenes/insights/views/Metric/Metric.tsx@@ -11,9 +11,7 @@ import {MetricValue,} from '@posthog/quill-components/metric'-import { dayjs } from 'lib/dayjs'import { hexToRGBA } from 'lib/utils/colors'-import { DATE_FORMAT_WITHOUT_YEAR, formatDate } from 'lib/utils/datetime'import {defaultAggregationAxisFormatForDisplay,formatAggregationAxisValue,@@ -29,6 +27,7 @@ import { insightLogic } from '../../insightLogic'import {computeMetricSummary,computeMetricSummaryChange,+ formatMetricLabel,getMetricChangeTooltip,METRIC_COLOR_BY_DIRECTION_DEFAULT,METRIC_DEFAULT_DECREASE_COLOR,@@ -84,9 +83,9 @@ export function MetricCard({ inCardView }: ChartParams): JSX.Element {decreaseColor: trendsFilter?.metricLineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR,})- // Format the backend day labels the app's way, without the year ("June 16" rather than "16-Jun-2026").- const labels =- resultSeries.days?.map((day) => formatDate(dayjs(day), DATE_FORMAT_WITHOUT_YEAR)) ?? resultSeries.labels+ // Raw bucket keys, not display text: the sparkline positions its points off these strings, and+ // "June 16" repeats once a range spans a year. `formatMetricLabel` handles the display side.+ const labels = resultSeries.days ?? resultSeries.labels// Dash the trailing in-progress period, matching the line chart. The offset is negative from the end.const dashedFromIndex =@@ -108,6 +107,7 @@ export function MetricCard({ inCardView }: ChartParams): JSX.Element {restingSubtitle={METRIC_SUMMARY_LABELS[summary]}data={resultSeries.data}labels={labels}+ formatLabel={formatMetricLabel}theme={theme}color={lineColor}showChange={showChange}diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.tsindex 237a68a5b3ba..59790241488d 100644--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts@@ -6,6 +6,7 @@ import {computeMetricChange,computeMetricSummary,computeMetricSummaryChange,+ formatMetricLabel,getMetricChangeTooltip,type MetricSeriesSummary,MetricSummary,@@ -270,3 +271,24 @@ describe('getMetricChangeTooltip', () => {expect(getMetricChangeTooltip(summary, hasComparison, interval)).toBe(expected)})})++describe('formatMetricLabel', () => {+ const cases: { name: string; label: string; expected: string }[] = [+ { name: 'day bucket reads without the year', label: '2026-09-02', expected: 'September 2' },+ {+ name: 'sub-day bucket keeps its time, so every hour of a day reads differently',+ label: '2026-09-02 13:00:00',+ expected: 'September 2, 13:00',+ },+ {+ name: 'midnight of a sub-day bucket still shows the time',+ label: '2026-09-02 00:00:00',+ expected: 'September 2, 00:00',+ },+ { name: 'text dayjs cannot parse passes through', label: 'Chrome', expected: 'Chrome' },+ ]++ it.each(cases)('$name', ({ label, expected }) => {+ expect(formatMetricLabel(label)).toBe(expected)+ })+})diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.tsindex 22374b100906..94aa5ee34592 100644--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts@@ -1,3 +1,21 @@+import { dayjs } from 'lib/dayjs'+import { DATE_FORMAT_WITHOUT_YEAR, formatDate } from 'lib/utils/datetime'+// 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'++// Sub-day bucket keys carry a time ("2026-09-02 13:00:00"), so a date-only caption renders every+// bucket in a day as the same text. Matching how the line chart and the workflows tile read their+// keys, a space in the key means the bucket needs its time.+const SUB_DAY_LABEL_FORMAT = `${DATE_FORMAT_WITHOUT_YEAR}, HH:mm`++/** Render a bucket key the app's way, without the year ("June 16" rather than "16-Jun-2026").+ * Text that dayjs cannot parse is returned unchanged. */+export function formatMetricLabel(label: string): string {+ const parsed = dayjs(label)+ if (!parsed.isValid()) {+ return label+ }+ return formatDate(parsed, label.includes(' ') ? SUB_DAY_LABEL_FORMAT : DATE_FORMAT_WITHOUT_YEAR)+}diff --git a/packages/quill/packages/components/AGENTS.md b/packages/quill/packages/components/AGENTS.mdindex f809b36baa83..ecc80aa3a476 100644--- a/packages/quill/packages/components/AGENTS.md+++ b/packages/quill/packages/components/AGENTS.md@@ -135,6 +135,7 @@ Rules:- `MetricSparkline` owns the bottom-edge alignment (a built-in 6px shift that pushes the canvas's hover-ring margin past the card edge so the line rests on it) — a custom `className` only manages margins (`-mx-*`/`-mb-*`/`mt-*`), never re-adds the offset.- Give the card a height (`className="h-40"`, or `h-full` in a sized box) when using `sparklineFill` or when you want a fixed-height sparkline pinned to the bottom; otherwise it sizes to content (`Metric` is `h-full` so it fills whatever card it's in).- The root owns the data/hover behavior and feeds the parts via context — a part used outside `<Metric>` throws. Pass `value` for a number-only tile; pass `data`+`labels`+`theme` for a sparkline.+- `labels` doubles as the sparkline's x-scale keys, so entries must be **unique** — a duplicate collapses two points onto one position and draws the series backwards (see the charts guide's `labels` rule). Pass raw keys (ISO dates) and render them for display with `formatLabel`, instead of pre-formatting text like `'June 16'`, which repeats once a range spans a year. `formatLabel` covers the subtitle; a `sparklineTooltip` formats the same keys through the charts' own `labelFormatter`.- `MetricDelta` renders a `Badge`; `goodDirection` (default `up`) decides success vs destructive. It carries its own `TooltipProvider`, so `changeTooltip` needs no app-root setup. resize via `className` (the metric insight passes its own larger-pill classes and puts it inline next to the headline via `MetricHeader`; there is no `changeInline` or size prop, compose and style at the call site).- Reproduces `MetricCard`'s behavior (`restingSubtitle`, `hoverChangeFromPreviousPoint`, `changeTooltip`, `positiveColor`/`negativeColor` for user-configured pill colors); omit the color props to keep the semantic `Badge` variants.- `series` draws a multi-series sparkline (one line per series, the charts' `Series[]` shape) instead of the single `data` line. It's purely visual — the headline, hover and change pill still read `data`, so pass the numbers the tile should read (e.g. the per-index totals) as `data` alongside it; the types reject `series` without `data`. The single-line conveniences (`color`, `sparklineDashedFromIndex`) don't apply — set them per series.diff --git a/packages/quill/packages/components/src/metric.test.tsx b/packages/quill/packages/components/src/metric.test.tsxnew file mode 100644index 000000000000..21bfcc2f13d0--- /dev/null+++ b/packages/quill/packages/components/src/metric.test.tsx@@ -0,0 +1,35 @@+import { render } from '@testing-library/react'++import type { ChartTheme } from '@posthog/quill-charts'+import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { Metric, MetricSubtitle } from './metric'++const THEME: ChartTheme = { colors: ['#22d3ee'], backgroundColor: '#ffffff' }+// Raw bucket keys, the shape a caller passes to keep the sparkline's x-scale keys unique.+const KEYS = ['2025-09-01', '2025-10-01', '2025-11-01']++describe('Metric', () => {+ let teardownJsdom: () => void+ let teardownRaf: () => void++ beforeEach(() => {+ teardownJsdom = setupJsdom()+ teardownRaf = setupSyncRaf()+ })++ afterEach(() => {+ teardownRaf()+ teardownJsdom()+ })++ // With no `restingSubtitle`, the subtitle shows the active label, which at rest is the last one.+ it('renders the active label through formatLabel', () => {+ const { container } = render(+ <Metric data={[1, 2, 3]} labels={KEYS} formatLabel={(label) => `bucket ${label}`} theme={THEME}>+ <MetricSubtitle />+ </Metric>+ )+ expect(container.textContent).toContain('bucket 2025-11-01')+ })+})diff --git a/packages/quill/packages/components/src/metric.tsx b/packages/quill/packages/components/src/metric.tsxindex c81580e31a71..0ef8d5d6bef3 100644--- a/packages/quill/packages/components/src/metric.tsx+++ b/packages/quill/packages/components/src/metric.tsx@@ -64,6 +64,7 @@ function useMetric(part: string): MetricContextValue {}const DEFAULT_FORMAT_VALUE = (v: number): string => v.toLocaleString()+const DEFAULT_FORMAT_LABEL = (label: string): React.ReactNode => labelconst DEFAULT_FORMAT_CHANGE = (p: number): string => {// Matches the monolithic MetricCard: `percentage` carries the sign for negatives, we prepend `+`.const formatted = percentage(p / 100, 1, true)@@ -74,8 +75,13 @@ interface MetricBaseProps {/** Resting headline number. Defaults to `data[data.length - 1]` when `data` is present;* required when `data` is empty or omitted. */value?: number- /** Labels paired with `data`. Used for the default subtitle on hover. */+ /** Labels paired with `data`. Used for the default subtitle on hover, and passed to the sparkline+ * as its x-scale keys, so entries must be unique. Pass raw keys (ISO dates) and turn them into+ * display text with `formatLabel`, because pre-formatted text like `'June 16'` repeats once a+ * range spans a year, and a duplicate collapses two points onto one position. */labels?: string[]+ /** Formats a `labels` entry for the subtitle, so `labels` can stay unique raw keys. */+ formatLabel?: (label: string) => React.ReactNode/** Required when `data` is present. */theme?: ChartTheme/** Sparkline line + fill color. Falls back to `theme.colors[0]`. */@@ -170,6 +176,7 @@ function MetricInner({data,series,labels,+ formatLabel = DEFAULT_FORMAT_LABEL,theme,color,sparklineHeight = 120,@@ -236,10 +243,12 @@ function MetricInner({const positive = delta != null && delta.value >= 0const good = goodDirection === 'up' ? positive : !positive+ const activeLabel = labels?.[activeIndex]+ const labelCaption = activeLabel != null ? formatLabel(activeLabel) : undefined+return {headlineDisplay: sparklineData ? formatValue(animatedValue) : formatValue(restingValue),- subtitle:- subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labels?.[activeIndex]),+ subtitle: subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labelCaption),change:delta != null? {@@ -286,6 +295,7 @@ function MetricInner({subtitle,restingSubtitle,labels,+ formatLabel,theme,color,series,diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex 0a236e4b3e7a..074dafeb54b0 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -95,6 +95,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {usersLoading={usersLoading}showIntentClusters={!!featureFlags[FEATURE_FLAGS.MCP_ANALYTICS_INTENT_ROUTING]}theme={theme}+ interval={interval}incompleteTail={kpiIncompleteTail}/></section>diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex 69420ce2d557..19245aacccdf 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -31,7 +31,6 @@ import { FEATURE_FLAGS } from 'lib/constants'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { formatBucketLabel } from 'lib/utils/timeBuckets'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { teamLogic } from 'scenes/teamLogic'@@ -247,7 +246,6 @@ function StatTiles({const errors = summary?.errors ?? 0const errorRate = calls ? (errors / calls) * 100 : 0const errorRateDaily = daily.calls.map((c, i) => (c ? (daily.errors[i] / c) * 100 : 0))- const sparkLabels = daily.labels.map((label) => formatBucketLabel(label, interval))const tiles: {label: string@@ -314,11 +312,12 @@ function StatTiles({key={tile.label}{...tile}loading={loading}- labels={sparkLabels}+ labels={daily.labels}+ interval={interval}theme={theme}restingSubtitle={dateRangeLabel}sparklineHeight={40}- sparklineDashedFromIndex={incompleteTail ? sparkLabels.length - 1 : undefined}+ sparklineDashedFromIndex={incompleteTail ? daily.labels.length - 1 : undefined}/>))}</div>diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex 8cd26af7d587..c3257d562f4e 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -156,6 +156,7 @@ export const KeyMetrics: Story = {usersLoading={false}showIntentClusterstheme={buildTheme()}+ interval="day"incompleteTail={false}/></div>@@ -173,6 +174,7 @@ export const KeyMetricsInProgressBucket: Story = {usersLoading={false}showIntentClusterstheme={buildTheme()}+ interval="day"incompleteTail/></div>diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsxindex 1d512b95546d..dc48a2536c51 100644--- a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx@@ -4,8 +4,10 @@ import { type ChartTheme } from '@posthog/quill-charts'import { formatPercentage } from 'lib/utils/numbers'import { urls } from 'scenes/urls'+import { IntervalType } from '~/types'+import { type KPIData, KPIMetric } from '../mcpDashboardOverviewLogic'-import { formatBucketLabel, formatMs, formatNumber } from './formatters'+import { formatMs, formatNumber } from './formatters'import { MetricTile } from './MetricTile'interface TileSpec {@@ -24,10 +26,12 @@ interface TileSpec {function KPITile({tile,theme,+ interval,incompleteTail,}: {tile: TileSpectheme: ChartTheme+ interval: IntervalTypeincompleteTail: boolean}): JSX.Element {const { metric } = tile@@ -42,7 +46,8 @@ function KPITile({loading={tile.loading}value={metric.value}data={metric.sparkline}- labels={metric.sparklineLabels.map(formatBucketLabel)}+ labels={metric.sparklineLabels}+ interval={interval}theme={theme}color={tile.color}goodDirection={metric.goodDirection}@@ -70,6 +75,7 @@ export function KpiTiles({usersLoading,showIntentClusters,theme,+ interval,incompleteTail,}: {kpis: KPIData@@ -79,6 +85,7 @@ export function KpiTiles({usersLoading: booleanshowIntentClusters: booleantheme: ChartTheme+ interval: IntervalType// When true, the sparklines' final point is the current in-progress interval — dash it so a// partial period doesn't read as a decline. Required rather than optional: an omitted prop// silently renders the partial bucket as settled data.@@ -160,7 +167,13 @@ export function KpiTiles({}`}>{tiles.map((tile) => (- <KPITile key={tile.label} tile={tile} theme={theme} incompleteTail={incompleteTail} />+ <KPITile+ key={tile.label}+ tile={tile}+ theme={theme}+ interval={interval}+ incompleteTail={incompleteTail}+ />))}</div></div>diff --git a/products/mcp_analytics/frontend/dashboard/MetricTile.tsx b/products/mcp_analytics/frontend/dashboard/MetricTile.tsxindex 7269840e9bbe..7f21b9874c1c 100644--- a/products/mcp_analytics/frontend/dashboard/MetricTile.tsx+++ b/products/mcp_analytics/frontend/dashboard/MetricTile.tsx@@ -1,3 +1,5 @@+import { useMemo } from 'react'+import { type ChartTheme } from '@posthog/quill-charts'import {Metric,@@ -11,6 +13,10 @@ import {} from '@posthog/quill-components/metric'import { Card, CardContent, cn, Skeleton } from '@posthog/quill-primitives'+import { formatBucketLabel } from 'lib/utils/timeBuckets'++import { IntervalType } from '~/types'+export interface MetricTileProps {label: stringvalue: number@@ -18,7 +24,12 @@ export interface MetricTileProps {theme: ChartThemeloading: booleandata?: number[]+ // Raw bucket keys, which the sparkline uses as its x-scale keys, so they must be unique per+ // point. Pre-formatted text repeats (every hour of a day reads "Sep 2") and a repeat collapses+ // two points onto one position. The tile formats them for the caption itself.labels?: string[]+ // Grouping interval of the buckets, which decides whether a caption needs the bucket's time.+ interval: IntervalTypecolor?: stringgoodDirection?: 'up' | 'down'restingSubtitle: string@@ -39,6 +50,7 @@ export function MetricTile({loading,data,labels,+ interval,color,goodDirection,restingSubtitle,@@ -50,6 +62,8 @@ export function MetricTile({className,}: MetricTileProps): JSX.Element {const hasSparkline = data != null && data.length > 0+ // A stable identity per interval, so `Metric`'s memoized context does not rebuild every render.+ const formatLabel = useMemo(() => (label: string) => formatBucketLabel(label, interval), [interval])return (<Card size="sm" flush={hasSparkline} className={cn('flex-1', className)}>{loading ? (@@ -63,6 +77,7 @@ export function MetricTile({value={value}data={hasSparkline ? data : undefined}labels={hasSparkline ? labels : undefined}+ formatLabel={formatLabel}theme={theme}color={color}goodDirection={goodDirection}diff --git a/products/mcp_analytics/frontend/dashboard/formatters.ts b/products/mcp_analytics/frontend/dashboard/formatters.tsindex 3978e936e5c6..154010b21105 100644--- a/products/mcp_analytics/frontend/dashboard/formatters.ts+++ b/products/mcp_analytics/frontend/dashboard/formatters.ts@@ -1,14 +1,8 @@-import { dayjs } from 'lib/dayjs'import { humanFriendlyDuration } from 'lib/utils/durations'import { humanFriendlyLargeNumber } from 'lib/utils/numbers'const EMPTY = '—'-export function formatBucketLabel(bucket: string): string {- const d = dayjs(bucket)- return d.isValid() ? d.format('MMM D') : bucket-}-export function formatNumber(n: number): string {if (!isFinite(n)) {return EMPTY