Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(insights): base lifecycle percentages on active orgs (#66136)

Sam Pennington6ca377f993c5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 783c3a7832d4..962ab11a1155 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2625,13 +2625,13 @@ snapshots:
insights-trendslifecyclechart--stacked-with-legend--light:
hash: v1.k794b7964.4270d6defbb370ea52d45fc9485bb625970c9b6b5181b6289132070392d2b807.Xk8absK51TdOh0ipMUZWdNQUvEzaF-pPGMDgKJvgZLU
insights-trendslifecyclechart--stacked-with-percentages-on-series--dark:
- hash: v1.k794b7964.a07939aacffaca561bf32b6d94c8c1fe24b401a097633e3ddc830dee3dd01564.jaqXSLUJl_Sv4mJP-_CUEyd1xXeNRTxmh7f4ueVidqM
+ hash: v1.k794b7964.59cf0eab0c3beaae947e06f2990dd08f721da9ebd8cc9a6708f14c8bbd62c7c3.UquKOuojddZncTZbu7VtCMjZhNToO3806iWtoO5jW3Q
insights-trendslifecyclechart--stacked-with-percentages-on-series--light:
- hash: v1.k794b7964.95dbfe49e07359ad08092c9aea300fa39f431d42db0ce4d83bfad96920c33a68.af5298viZpgYvU0-zUDX1a9-n4u_81whHApLAKruA0o
+ hash: v1.k794b7964.42966031c8a2c5530fff80b23350c3c4152f89ae65486debe465e0e22a20a311.ax_FlXBRiNFBJmhuuO4XZ5Mf3plxuYdN6CKkLI2WBkg
insights-trendslifecyclechart--stacked-with-percentages-only-on-series--dark:
- hash: v1.k794b7964.3d32eaa1ed6138f2753d6a5fb25ee121412a269c1578e6e6c348126d3d0a6428.g6Ml5o7sXaFcX1mQ1KzES5tljY1juyMh_XsFb6aY_xU
+ hash: v1.k794b7964.7d8f4c6fa924cb6128d7c24e186beb17ee0cbd6ef4a7614cbcd6f5d93c4a699d.7iIKWltoBs5_Wvf0q-sgrr5K7JxtWtW81nSuAK5qaYU
insights-trendslifecyclechart--stacked-with-percentages-only-on-series--light:
- hash: v1.k794b7964.dff5234fd86fa7563c36c5cca274f9784ad6f78bc32868a996516426390db4d1.ZjjuIwPFFfrC_pkxcd0MqAaD-eP1saEB0omdCJfaO70
+ hash: v1.k794b7964.beb4b557b7717d0cd5530dbd23116fa472f35f5c272633fbfd43c71274bfeec0.Rw3UWxZGdqJ-e_blvA4gG2ye4u3kc0Z8NuEb-Ii3Mq8
insights-trendslifecyclechart--stacked-with-values-on-series--dark:
hash: v1.k794b7964.b19dec9224b226b8ac7a42ec1d73afa18c2f3366779c568589d7fd3c08cd5ef9.4_lO71FM0ds0HH19knoAl9E9wmOngD1gDaO7z32RJ6c
insights-trendslifecyclechart--stacked-with-values-on-series--light:
@@ -2645,9 +2645,9 @@ snapshots:
insights-trendslifecyclechart--unstacked-with-legend--light:
hash: v1.k794b7964.2256dd4ae7dd4b50df9adfe0dbdd1af2fe7a337a69d75cfa0fea2763dd00fae7.Bhs-r2irJrYC5LDouGsRe8NsjM0hzcDdPvnNtOhPOhw
insights-trendslifecyclechart--unstacked-with-percentages-on-series--dark:
- hash: v1.k794b7964.e89fef8b35437fb4e4dc345c809e7e8a8d84df5f4114e59e9eb7d773b310fb23.9GII3E9SZ9-KPi_lgA6rjSV23tfGVlVUXArAaYkdW-Q
+ hash: v1.k794b7964.7538b02b001a4eee4da641d2e7446599a1798e9431363a60737ceff76d815bf3.GPXUv6gResKOPi4h3DUv-P4K4GwQE2IYzYcBgzzBZ4U
insights-trendslifecyclechart--unstacked-with-percentages-on-series--light:
- hash: v1.k794b7964.4f5e9b4411156cf351f81e433bdc96a5010bf3f3f2b7fb6c44cd64c018583e2e.ddMvEBYqWpy8J48Gj_fK_LUT5iPp2DJCb0EDPXjCK2k
+ hash: v1.k794b7964.246d4c6cc2004051b0cc9f25902777432baf005fa7d3b956af36bb0d3235a7ff.KvJ0yLvh1-ooj6Ymrerhx_i9pNJmpUMWF0AXKG1QPMw
insights-trendslifecyclechart--unstacked-with-values-on-series--dark:
hash: v1.k794b7964.ec2fb36742db8a2378cedea7929d2f0c1a8bfe1ca5cc37ddded1cfbc2946d5b3.Gf0bkG7fY_WV5m5xJ51dF7XsFJTgq4bOTymKY6BENU4
insights-trendslifecyclechart--unstacked-with-values-on-series--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index fcc82218eef4..9590b29058ca 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -670,6 +670,7 @@ describe('sqlLineGraphAdapter', () => {
const ctx = (rawValue: number): ValueLabelContext => ({
rawValue,
bandValues: [rawValue],
+ previousBandValues: [],
isPercent: false,
})
// The label reads context.rawValue (not the percent-fraction `value` arg) with each series' settings.
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index e8f3a422ea68..4dc100f2e78b 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -70,7 +70,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.
- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint).
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
-- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.
+- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period).
- 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). Long labels clip to a max width with an ellipsis and expose the full text via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at ~45% width), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.
- `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.
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
index 4035eb4960f6..9c90907fe710 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
@@ -332,6 +332,23 @@ describe('ValueLabels', () => {
).toEqual(['-10|30,-10', '25|25,75', '30|30,-10', '75|25,75'])
})
+ it('passes the preceding band as previousBandValues (empty at the first index)', () => {
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#a00', data: [30, 25] },
+ { key: 'b', label: 'B', color: '#0a0', data: [-10, 75] },
+ ]
+ const ctx = makeContext(series, { labels: ['Mon', 'Tue'] })
+ const { container } = renderInChart(
+ ctx,
+ <ValueLabels valueFormatter={(_v, _si, _di, c) => `${c.rawValue}|${c.previousBandValues.join(',')}`} />
+ )
+ expect(
+ labelDivs(container)
+ .map((d) => d.textContent)
+ .sort()
+ ).toEqual(['-10|', '25|30,-10', '30|', '75|30,-10'])
+ })
+
it('marks the context isPercent in percent layout and passes the segment fraction as value', () => {
const series: ResolvedSeries[] = [
{ key: 'a', label: 'A', color: '#a00', data: [20, 60] },
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
index af75abab4feb..8c9c822c22a2 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
@@ -19,6 +19,8 @@ export interface ValueLabelContext {
/** Finite values of every series contributing to this band's stack (non-excluded, not a fill
* lower-bound, not an overlay) at this dataIndex — the denominator set for share math. */
bandValues: number[]
+ /** Same as `bandValues` for the preceding dataIndex; empty at the first index. */
+ previousBandValues: number[]
/** True in normalized/percent layout, where `value` is already a fraction. */
isPercent: boolean
}
@@ -186,6 +188,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
const text = valueFormatter(total, -1, dIdx, {
rawValue: total,
bandValues: bandValuesAt(visible, dIdx),
+ previousBandValues: dIdx > 0 ? bandValuesAt(visible, dIdx - 1) : [],
isPercent,
})
if (text === '') {
@@ -262,6 +265,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
const text = valueFormatter(displayValue, sIdx, dIdx, {
rawValue,
bandValues: bandValuesByIndex[dIdx],
+ previousBandValues: dIdx > 0 ? bandValuesByIndex[dIdx - 1] : [],
isPercent,
})
if (text === '') {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
index 572eea22f853..0c75d848e62d 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
@@ -246,31 +246,61 @@ describe('buildTrendsLifecycleConfig', () => {
describe('buildLifecycleValueLabelFormatter', () => {
const formatValue = (v: number): string => `${v}`
- // Diverging band: positive new + negative dormant. abs total = 30, so 20 → 67%, -10 → 33%.
- const band: ValueLabelContext = { rawValue: 20, bandValues: [20, -10], isPercent: false }
+ const band: ValueLabelContext = {
+ rawValue: 20,
+ bandValues: [20, 10, -10],
+ previousBandValues: [40, 10, -5],
+ isPercent: false,
+ }
it.each([
{ name: 'values only', showValues: true, showPercentages: false, expected: '20' },
{ name: 'values + percentages', showValues: true, showPercentages: true, expected: '20 (67%)' },
{ name: 'percentages only', showValues: false, showPercentages: true, expected: '67%' },
- ])('renders $name as "$expected"', ({ showValues, showPercentages, expected }) => {
+ ])('renders active $name as "$expected"', ({ showValues, showPercentages, expected }) => {
const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues, showPercentages })
expect(formatter(20, 0, 0, band)).toBe(expected)
})
- it('uses absolute values so the negative dormant segment gets a sensible share', () => {
+ it('excludes dormant from the active denominator so active statuses sum to 100%', () => {
const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: false, showPercentages: true })
- expect(formatter(-10, 1, 0, { rawValue: -10, bandValues: [20, -10], isPercent: false })).toBe('33%')
+ expect(formatter(20, 0, 0, { ...band, rawValue: 20 })).toBe('67%')
+ expect(formatter(10, 1, 0, { ...band, rawValue: 10 })).toBe('33%')
})
- it('returns an empty string (skip) for percentages-only when the band has no total', () => {
+ it('measures dormant against the previous period active total', () => {
const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: false, showPercentages: true })
- expect(formatter(0, 0, 0, { rawValue: 0, bandValues: [0, 0], isPercent: false })).toBe('')
+ expect(formatter(-10, 2, 1, { ...band, rawValue: -10 })).toBe('20%')
+ })
+
+ it('labels the first-period dormant bar with its value in both modes (no previous band)', () => {
+ const firstPeriodDormant: ValueLabelContext = {
+ rawValue: -10,
+ bandValues: [20, -10],
+ previousBandValues: [],
+ isPercent: false,
+ }
+ const withValues = buildLifecycleValueLabelFormatter(formatValue, { showValues: true, showPercentages: true })
+ expect(withValues(-10, 2, 0, firstPeriodDormant)).toBe('-10')
+ const percentagesOnly = buildLifecycleValueLabelFormatter(formatValue, {
+ showValues: false,
+ showPercentages: true,
+ })
+ expect(percentagesOnly(-10, 2, 0, firstPeriodDormant)).toBe('-10')
+ })
+
+ it('returns an empty string (skip) for percentages-only when the band has no active total', () => {
+ const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: false, showPercentages: true })
+ expect(formatter(0, 0, 0, { rawValue: 0, bandValues: [0, 0], previousBandValues: [], isPercent: false })).toBe(
+ ''
+ )
})
it('does not append percentages in percent layout (labels already express fractions)', () => {
const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: true, showPercentages: true })
- expect(formatter(0.2, 0, 0, { rawValue: 20, bandValues: [20, 80], isPercent: true })).toBe('0.2')
+ expect(
+ formatter(0.2, 0, 0, { rawValue: 20, bandValues: [20, 80], previousBandValues: [], isPercent: true })
+ ).toBe('0.2')
})
})
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
index 283bde48572f..d4e014773851 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
@@ -30,8 +30,13 @@ export interface LifecycleValueLabelOptions {
showPercentages: boolean
}
-// Each segment's percentage is its share of the band's absolute total — `abs` so the negative
-// dormant series contributes a sensible denominator instead of cancelling the positives.
+// Positives only — dormant is the lone negative series, so it's excluded from the active total.
+function activeBandTotal(bandValues: number[] | undefined): number {
+ return (bandValues ?? []).reduce((sum, v) => (v > 0 ? sum + v : sum), 0)
+}
+
+// Dormant orgs lapsed from the *previous* period's active pool, so their share divides by that
+// period's total rather than the current one.
export function buildLifecycleValueLabelFormatter(
formatValue: (value: number) => string,
{ showValues, showPercentages }: LifecycleValueLabelOptions
@@ -41,11 +46,15 @@ export function buildLifecycleValueLabelFormatter(
if (!showPercentages || context.isPercent) {
return valueText
}
- const absTotal = context.bandValues.reduce((sum, v) => sum + Math.abs(v), 0)
- if (absTotal === 0) {
- return valueText
+ const isDormant = context.rawValue < 0
+ const denominator = isDormant
+ ? activeBandTotal(context.previousBandValues)
+ : activeBandTotal(context.bandValues)
+ if (denominator === 0) {
+ // Dormant in the first period has no previous band to divide by — show its value rather than blank.
+ return isDormant ? formatValue(value) : valueText
}
- const pct = Math.round((Math.abs(context.rawValue) / absTotal) * 100)
+ const pct = Math.round((Math.abs(context.rawValue) / denominator) * 100)
return showValues ? `${valueText} (${pct}%)` : `${pct}%`
}
}