: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(mcp): render distinct bars for funnel steps with duplicate names (#65396)
Georgis Andonis85d9c11220c4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 326328b303eb..332f7af33b95 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4228,6 +4228,8 @@ snapshots:hash: v1.k794b7964.09249f0d06bf5ef94eaddfcd5a97b97943ed42cae7097741dd3989418ec11f50.ROO2zs_uTFgPB7eI8fwi2GIwSo_HHTlhAal5XWBmz7Ymcp-apps-feature-flags--testing-no-match--light:hash: v1.k794b7964.b5eec4d4100dc834d4c7c891e4962c9effa643ff190f3b0957d816d82ebb7269.9Hg0pCpNp895WlYr8k2m97K0fvniLuzPcRSAIWUCtg8+ mcp-apps-funnels--duplicate-step-names--light:+ hash: v1.k794b7964.2f566a1901569cdad84ab37230918b1b219e8c19d9918bf226cc64a923b877f4.Usd-BBA4l0MnrnhYDGyIitmfjjMj8NqB1rW0VPOinEgmcp-apps-funnels--steep-dropoff--light:hash: v1.k794b7964.9b1c95cfbfaa751ecc06b1b998af2a9e79304f9d6bb463e83639fea231a786f8.A2qfI1EvER2HUN40tOYPTXKw9MB1Q10TEY7XdsWr-m4mcp-apps-funnels--three-step--light:diff --git a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.tsindex 79ab4ffcc735..58dd42b1a2e9 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelStepsBarChart/funnelStepsBarTransforms.ts@@ -1,11 +1,15 @@-import type { PointClickData, Series } from '@posthog/quill-charts'+import type { PointClickData } from '@posthog/quill-charts'import type { FunnelStepWithConversionMetrics } from '~/types'-export const FUNNEL_STEPS_SERIES_KEY_PREFIX = 'funnel-step-series-'+import { RATE_TO_PERCENT } from '../shared/funnelBarHorizontalShared'+import {+ buildFunnelStepsBars,+ type FunnelStepsBarsModel,+ type FunnelStepsBarVariant,+} from '../shared/funnelStepsBarShared'-/** `conversionRates.fromBasisStep` is a 0–1 ratio; hog-charts bars are valued in percent. */-const RATE_TO_PERCENT = 100+export const FUNNEL_STEPS_SERIES_KEY_PREFIX = 'funnel-step-series-'/** Identifies which breakdown variant a hog-charts series maps back to, so click and* tooltip handlers can recover the original `FunnelStepWithConversionMetrics`. */@@ -18,11 +22,7 @@ interface BuildOptions {getLabel: (series: FunnelStepWithConversionMetrics) => string}-export interface FunnelStepsBarData {- /** One series per breakdown variant; `data[stepIndex]` is a percent (0–100). */- series: Series<FunnelStepsBarSeriesMeta>[]- labels: string[]-}+export type FunnelStepsBarData = FunnelStepsBarsModel<FunnelStepsBarSeriesMeta>function variantAtStep(step: FunnelStepWithConversionMetrics,@@ -42,23 +42,25 @@ function variantAtStep(}/** Maps the funnel steps onto grouped hog-charts bar series — one series per breakdown- * variant, one bar per step, valued by conversion rate from the basis step. */+ * variant, one bar per step, valued by conversion rate from the basis step. Resolves the+ * breakdown variants (web-only) and defers to the shared builder for the band labels, rows,+ * and overall stats it shares with the MCP funnel app. */export function buildFunnelStepsBarData(steps: FunnelStepWithConversionMetrics[],options: BuildOptions): FunnelStepsBarData {if (steps.length === 0) {- return { series: [], labels: [] }+ return buildFunnelStepsBars<FunnelStepsBarSeriesMeta>([], [])}const isBreakdown = steps[0].nested_breakdown != nullconst breakdownCount = isBreakdown ? steps[0].nested_breakdown!.length : 1- const series: Series<FunnelStepsBarSeriesMeta>[] = []+ const seriesVariants: FunnelStepsBarVariant<FunnelStepsBarSeriesMeta>[] = []for (let breakdownIndex = 0; breakdownIndex < breakdownCount; breakdownIndex++) {const variants = steps.map((step) => variantAtStep(step, breakdownIndex, isBreakdown))const representative = variants[0]- series.push({+ seriesVariants.push({key: `${FUNNEL_STEPS_SERIES_KEY_PREFIX}${breakdownIndex}`,label: representative ? options.getLabel(representative) : '',data: variants.map((variant) => variant.conversionRates.fromBasisStep * RATE_TO_PERCENT),@@ -67,7 +69,7 @@ export function buildFunnelStepsBarData(})}- return { series, labels: steps.map((_, stepIndex) => `${stepIndex + 1}`) }+ return buildFunnelStepsBars(steps, seriesVariants)}export interface FunnelStepClickTarget {diff --git a/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.test.ts b/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.test.tsindex fec705f8b720..a8cdefae4526 100644--- a/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.test.ts+++ b/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.test.ts@@ -1,4 +1,10 @@-import { buildFunnelStepsBarConfig, buildFunnelStepsBars, FUNNEL_STEPS_BAR_SERIES_KEY } from './funnelStepsBarShared'+import {+ buildFunnelStepsBarConfig,+ buildFunnelStepsBars,+ buildSingleSeriesFunnelStepsBars,+ FUNNEL_STEPS_BAR_SERIES_KEY,+ type FunnelStepsBarVariant,+} from './funnelStepsBarShared'describe('funnelStepsBarShared', () => {// The rest of buildFunnelStepsBarConfig is a declarative config literal; only the value-axis@@ -15,26 +21,38 @@ describe('funnelStepsBarShared', () => {})describe('buildFunnelStepsBars', () => {- const OPTS = { color: '#1d4aff' }const steps = [{ name: 'Pageview', count: 1000 },{ name: 'Signed up', count: 400 },{ name: 'Activated', count: 100 },]+ const variants: FunnelStepsBarVariant[] = [{ key: 'a', label: 'A', color: '#1d4aff', data: [100, 40, 10] }]- it('emits one series of per-step conversion-from-first, as a percent', () => {- const { series } = buildFunnelStepsBars(steps, OPTS)+ it('labels the band by 1-based step index, not the step name', () => {+ expect(buildFunnelStepsBars(steps, variants).labels).toEqual(['1', '2', '3'])+ })- expect(series).toHaveLength(1)- expect(series[0]).toMatchObject({ key: FUNNEL_STEPS_BAR_SERIES_KEY, color: '#1d4aff', data: [100, 40, 10] })+ it('keeps duplicate-named steps on distinct bands so they do not collapse', () => {+ const dupSteps = [+ { name: '$pageview', count: 10 },+ { name: '$pageview', count: 2 },+ ]+ expect(buildFunnelStepsBars(dupSteps, variants).labels).toEqual(['1', '2'])})- it('labels the axis with the step names', () => {- expect(buildFunnelStepsBars(steps, OPTS).labels).toEqual(['Pageview', 'Signed up', 'Activated'])+ it('wraps each variant as a series, preserving key, color, data, and meta', () => {+ const { series } = buildFunnelStepsBars(steps, [+ { key: 'mobile', label: 'Mobile', color: '#f00', data: [100, 60], meta: { breakdownIndex: 0 } },+ { key: 'desktop', label: 'Desktop', color: '#0f0', data: [100, 30], meta: { breakdownIndex: 1 } },+ ])++ expect(series).toHaveLength(2)+ expect(series[0]).toMatchObject({ key: 'mobile', label: 'Mobile', color: '#f00', data: [100, 60] })+ expect(series.map((s) => s.meta?.breakdownIndex)).toEqual([0, 1])})- it('computes per-step conversion vs the first step and vs the previous step', () => {- const { rows } = buildFunnelStepsBars(steps, OPTS)+ it('computes per-step conversion vs the first step and vs the previous step from counts', () => {+ const { rows } = buildFunnelStepsBars(steps, variants)expect(rows.map((r) => r.fractionOfBasis)).toEqual([1, 0.4, 0.1])// step 0 has no previous step (value unused by the view); steps 1/2 are vs the prior count.@@ -44,11 +62,40 @@ describe('funnelStepsBarShared', () => {})it('reports overall conversion as last/first', () => {- expect(buildFunnelStepsBars(steps, OPTS).overall).toEqual({ rate: 0.1, firstCount: 1000, lastCount: 100 })+ expect(buildFunnelStepsBars(steps, variants).overall).toEqual({+ rate: 0.1,+ firstCount: 1000,+ lastCount: 100,+ })+ })++ it('returns an empty model for an empty funnel', () => {+ expect(buildFunnelStepsBars([], [])).toEqual({+ series: [],+ labels: [],+ rows: [],+ overall: { rate: 0, firstCount: 0, lastCount: 0 },+ })+ })+ })++ describe('buildSingleSeriesFunnelStepsBars', () => {+ const OPTS = { color: '#1d4aff' }+ const steps = [+ { name: 'Pageview', count: 1000 },+ { name: 'Signed up', count: 400 },+ { name: 'Activated', count: 100 },+ ]++ it('derives one series of per-step conversion-from-first, as a percent', () => {+ const { series } = buildSingleSeriesFunnelStepsBars(steps, OPTS)++ expect(series).toHaveLength(1)+ expect(series[0]).toMatchObject({ key: FUNNEL_STEPS_BAR_SERIES_KEY, color: '#1d4aff', data: [100, 40, 10] })})it('guards divide-by-zero when the first step has no entries', () => {- const { series, rows, overall } = buildFunnelStepsBars(+ const { series, rows, overall } = buildSingleSeriesFunnelStepsBars([{ name: 'A', count: 0 },{ name: 'B', count: 0 },@@ -61,8 +108,8 @@ describe('funnelStepsBarShared', () => {expect(overall.rate).toBe(0)})- it('returns an empty model for an empty funnel', () => {- const { series, labels, rows, overall } = buildFunnelStepsBars([], OPTS)+ it('returns a single empty series for an empty funnel', () => {+ const { series, labels, rows, overall } = buildSingleSeriesFunnelStepsBars([], OPTS)expect(series[0].data).toEqual([])expect(labels).toEqual([])diff --git a/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.ts b/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.tsindex d90320a88172..7fb6eee6b8a9 100644--- a/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.ts+++ b/products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared.ts@@ -57,22 +57,38 @@ export interface FunnelStepsBarRow {fromPrevious: number}-export interface FunnelStepsBarsModel {- /** Single grouped series whose `data[stepIndex]` is the step's conversion from the first step, as- * a percent (0–100). The `track: true` bar config draws the drop-off remainder up to 100%. */- series: Series[]- /** X-axis category labels — the step names. */+/** A grouped-bar series already resolved to per-step conversion percentages. Each surface produces these+ * its own way — the MCP app from raw counts, the web container from per-breakdown conversion rates — and+ * hands them to `buildFunnelStepsBars`, which owns the shared band labels, rows, and overall stats. */+export interface FunnelStepsBarVariant<TMeta = unknown> {+ key: string+ label: string+ color?: string+ meta?: TMeta+ /** `data[stepIndex]` is the conversion from the first step, as a percent (0–100). The `track: true`+ * bar config draws the drop-off remainder up to 100%. */+ data: number[]+}++export interface FunnelStepsBarsModel<TMeta = unknown> {+ /** One grouped series per variant (a single series without a breakdown). */+ series: Series<TMeta>[]+ /** X-axis band labels — 1-based step indices as strings. Always unique, so steps that share an event+ * name (e.g. two `$pageview` steps) don't collapse onto one band slot; surfaces map the index back to+ * the step name for display (web's StepLegend row, the MCP app's `xTickFormatter`). */labels: string[]rows: FunnelStepsBarRow[]overall: { rate: number; firstCount: number; lastCount: number }}-/** Builds the grouped vertical-bar data for the simple (non-breakdown) MCP funnel. Mirrors the web- * FunnelStepsBarChart's single-variant path: one series valued by conversion rate from the basis step. */-export function buildFunnelStepsBars(+/** Assembles the grouped vertical-bar model shared by the web FunnelStepsBarChart and the MCP funnel app.+ * Callers resolve their own per-variant series (single for MCP, one-per-breakdown for web); this owns the+ * pieces that must stay identical across surfaces: the index-keyed band labels, the per-step conversion+ * rows, and the overall first→last rate. */+export function buildFunnelStepsBars<TMeta = unknown>(steps: { name: string; count: number }[],- opts: { color: string }-): FunnelStepsBarsModel {+ variants: FunnelStepsBarVariant<TMeta>[]+): FunnelStepsBarsModel<TMeta> {const firstCount = steps[0]?.count ?? 0const lastCount = steps[steps.length - 1]?.count ?? 0const rows: FunnelStepsBarRow[] = steps.map((step, stepIndex) => ({@@ -82,18 +98,31 @@ export function buildFunnelStepsBars(fractionOfBasis: funnelConversionRate(step.count, firstCount),fromPrevious: funnelConversionRate(step.count, steps[stepIndex - 1]?.count ?? 0),}))- const series: Series[] = [- {- key: FUNNEL_STEPS_BAR_SERIES_KEY,- label: 'Conversion',- data: rows.map((row) => row.fractionOfBasis * RATE_TO_PERCENT),- color: opts.color,- },- ]+ const series: Series<TMeta>[] = variants.map((variant) => ({+ key: variant.key,+ label: variant.label,+ data: variant.data,+ color: variant.color,+ meta: variant.meta,+ }))return {series,- labels: steps.map((step) => step.name),+ labels: steps.map((_, stepIndex) => `${stepIndex + 1}`),rows,overall: { rate: funnelConversionRate(lastCount, firstCount), firstCount, lastCount },}}++/** Convenience for the single-series (non-breakdown) funnel — the MCP app and the web no-breakdown path.+ * Derives the lone "conversion from the first step" series from raw counts, then defers to+ * `buildFunnelStepsBars` for the shared labels, rows, and overall stats. */+export function buildSingleSeriesFunnelStepsBars(+ steps: { name: string; count: number }[],+ opts: { color: string }+): FunnelStepsBarsModel {+ const firstCount = steps[0]?.count ?? 0+ const data = steps.map((step) => funnelConversionRate(step.count, firstCount) * RATE_TO_PERCENT)+ return buildFunnelStepsBars(steps, [+ { key: FUNNEL_STEPS_BAR_SERIES_KEY, label: 'Conversion', color: opts.color, data },+ ])+}diff --git a/services/mcp/src/ui-apps/components/FunnelVisualizer.tsx b/services/mcp/src/ui-apps/components/FunnelVisualizer.tsxindex 809107e131f2..42bfca51557f 100644--- a/services/mcp/src/ui-apps/components/FunnelVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/FunnelVisualizer.tsx@@ -6,7 +6,7 @@ import { BarChart, TooltipSurface, type TooltipContext } from '@posthog/quill-chimport {buildFunnelStepsBarConfig,- buildFunnelStepsBars,+ buildSingleSeriesFunnelStepsBars,type FunnelStepsBarRow,} from 'products/product_analytics/frontend/insights/funnels/shared/funnelStepsBarShared'@@ -46,7 +46,14 @@ function renderTooltip(rows: FunnelStepsBarRow[]) {export function FunnelVisualizer({ results }: FunnelVisualizerProps): ReactElement {const theme = useMcpChartTheme()const steps = normalizeFunnelSteps(results)- const { series, labels, rows, overall } = buildFunnelStepsBars(steps, { color: FUNNEL_COLOR })+ const { series, labels, rows, overall } = buildSingleSeriesFunnelStepsBars(steps, { color: FUNNEL_COLOR })++ // Labels are 1-based step indices (the shared builder keys the band by index so duplicate step names+ // don't collapse onto one slot); map each tick back to its step name for the compact axis.+ const config: typeof CHART_CONFIG = {+ ...CHART_CONFIG,+ xTickFormatter: (_value, index) => rows[index]?.name ?? '',+ }if (steps.length === 0) {return (@@ -70,7 +77,7 @@ export function FunnelVisualizer({ results }: FunnelVisualizerProps): ReactElemeseries={series}labels={labels}theme={theme}- config={CHART_CONFIG}+ config={config}tooltip={renderTooltip(rows)}onError={NOOP}/>diff --git a/services/mcp/src/ui-apps/components/Funnels.stories.tsx b/services/mcp/src/ui-apps/components/Funnels.stories.tsxindex 3e4be1924381..97697a6e0214 100644--- a/services/mcp/src/ui-apps/components/Funnels.stories.tsx+++ b/services/mcp/src/ui-apps/components/Funnels.stories.tsx@@ -29,7 +29,9 @@ export default metatype Story = StoryObj<{}>-const renderFunnel = (results: FunnelResult): ReactElement => <FunnelVisualizer query={FUNNELS_QUERY} results={results} />+const renderFunnel = (results: FunnelResult): ReactElement => (+ <FunnelVisualizer query={FUNNELS_QUERY} results={results} />+)export const ThreeStep: Story = {render: () =>@@ -51,3 +53,15 @@ export const SteepDropoff: Story = {]),name: 'Steep drop-off',}++// Steps that share an event name must still render one bar each. The band scale dedupes its domain,+// so positioning by name would collapse both `$pageview` steps onto a single slot — this guards the+// index-keyed band + tick formatter that keeps them distinct.+export const DuplicateStepNames: Story = {+ render: () =>+ renderFunnel([+ { name: '$pageview', count: 10, order: 0 },+ { name: '$pageview', count: 2, order: 1 },+ ]),+ name: 'Duplicate step names',+}