: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(funnels): add 'compare to previous' for trends funnels (#59536)
Thomas Obermüllerb6d4f4b5a58e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f3cb7841e335..2704d5546242 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5182,6 +5182,10 @@ snapshots:hash: v1.k794b7964.b7b66559dccb763f858ee380c0d40d53762513df15f578847fb7d9e4d895bac8.6oo4h2VarntGAxWHNR2JnaPQL3-aBA8yjSewpfh1nK8scenes-app-insights-funnels--funnel-historical-trends--light:hash: v1.k794b7964.9fe64ca28742cf7dfb240b6aa406aaa4a2f432c37ee9bb8f48226288a0cc211a.cBV0X_j0CpIsQmxGgG-npGLQE1GhEHECWbdfi3lrviY+ scenes-app-insights-funnels--funnel-historical-trends-compare--dark:+ hash: v1.k794b7964.51f9e17a891ee9e734b149f3d3e0d75a17efed2739fca34b2a60303707df663a.ILben9P-htPVE30EG-LMY2AmDKjaCcboMcsAm88a5gc+ scenes-app-insights-funnels--funnel-historical-trends-compare--light:+ hash: v1.k794b7964.0c262649d9cccd6e0db23747e5dea4d4c6482ec8c39a843f85dc3d57e353dca8.WlfMvGeOV7nIb2BT5eLjcx5gG3UhzUIXXknUZ6p5xgwscenes-app-insights-funnels--funnel-historical-trends-edit--dark:hash: v1.k794b7964.ddf1de4101252c9ab760f84a933063eeb60ccb17365da86b45e17eb2e427f1de.XJJJZj03zYGcwzIfDinL9v1jjblvbhyoBw6vJrZ-uZkscenes-app-insights-funnels--funnel-historical-trends-edit--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex aac0ad9ebf6a..f51080975170 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -417,6 +417,7 @@ export const FEATURE_FLAGS = {POSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-posthog-codePRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analytics+ PRODUCT_ANALYTICS_FUNNELS_COMPARE: 'product-analytics-funnels-compare', // owner: @thmsobrmlr #team-product-analytics, gates "Compare to previous" toggle on funnel insightsPRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-eventsPRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL: 'product-analytics-hog-charts-funnel', // owner: @sampennington #team-product-analyticsPRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE: 'product-analytics-hog-charts-lifecycle', // owner: @sampennington #team-product-analyticsdiff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelHistoricalTrendsCompare.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelHistoricalTrendsCompare.jsonnew file mode 100644index 000000000000..42e871821c7e--- /dev/null+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelHistoricalTrendsCompare.json@@ -0,0 +1,137 @@+{+ "id": 52,+ "short_id": "funnelTrendsCompare",+ "name": null,+ "derived_name": "Pageview → Pageview → Pageview user conversion trend (compare)",+ "filters": {},+ "filters_hash": "cache_funnel_trends_compare",+ "order": null,+ "deleted": false,+ "dashboard": null,+ "layouts": {},+ "color": null,+ "last_refresh": null,+ "refreshing": false,+ "result": [+ {+ "count": 8,+ "data": [14.05, 15.61, 16.66, 3.08, 0, 0, 1.85, 0],+ "days": [+ "2022-03-08",+ "2022-03-09",+ "2022-03-10",+ "2022-03-11",+ "2022-03-12",+ "2022-03-13",+ "2022-03-14",+ "2022-03-15"+ ],+ "labels": [+ "8-Mar-2022",+ "9-Mar-2022",+ "10-Mar-2022",+ "11-Mar-2022",+ "12-Mar-2022",+ "13-Mar-2022",+ "14-Mar-2022",+ "15-Mar-2022"+ ],+ "compare": true,+ "compare_label": "current"+ },+ {+ "count": 5,+ "data": [8.4, 9.9, 6.2, 2.0, 0, 0, 0, 0],+ "days": [+ "2022-03-01",+ "2022-03-02",+ "2022-03-03",+ "2022-03-04",+ "2022-03-05",+ "2022-03-06",+ "2022-03-07",+ "2022-03-08"+ ],+ "labels": [+ "1-Mar-2022",+ "2-Mar-2022",+ "3-Mar-2022",+ "4-Mar-2022",+ "5-Mar-2022",+ "6-Mar-2022",+ "7-Mar-2022",+ "8-Mar-2022"+ ],+ "compare": true,+ "compare_label": "previous"+ }+ ],+ "created_at": "2022-03-15T21:31:00.192917Z",+ "created_by": {+ "id": 1,+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",+ "first_name": "Marius",+ "email": "[email protected]"+ },+ "description": "",+ "updated_at": "2022-03-15T21:48:00.105822Z",+ "tags": [],+ "favorited": false,+ "saved": true,+ "last_modified_at": "2022-03-15T21:48:00.096438Z",+ "last_modified_by": {+ "id": 1,+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",+ "first_name": "Marius",+ "email": "[email protected]"+ },+ "is_sample": false,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "compareFilter": {+ "compare": true+ },+ "dateRange": {+ "date_from": "2022-03-08",+ "date_to": "2022-03-15"+ },+ "funnelsFilter": {+ "exclusions": [],+ "funnelVizType": "trends",+ "layout": "horizontal"+ },+ "interval": "day",+ "kind": "FunnelsQuery",+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": []+ }+ ]+ },+ "series": [+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview"+ },+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview"+ },+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview"+ }+ ]+ },+ "full": true+ }+}diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsxindex 9ef45c28742e..4de5815c34f5 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx@@ -116,13 +116,15 @@ export function InsightDisplayConfig(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)const hideWeekendsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HIDE_WEEKENDS]+ const funnelsCompareEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]const showCompare =(isTrends &&display !== ChartDisplayType.ActionsAreaGraph &&display !== ChartDisplayType.CalendarHeatmap &&display !== ChartDisplayType.BoxPlot) ||isStickiness ||- isWebAnalyticsInsightQuery(querySource)+ isWebAnalyticsInsightQuery(querySource) ||+ (funnelsCompareEnabled && isTrendsFunnel)const showInterval =isTrendsFunnel ||isLifecycle ||diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex c3fd4226e193..d4dcf6a72d64 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -21879,6 +21879,10 @@"$ref": "#/definitions/BreakdownFilter","description": "Breakdown of the events and actions"},+ "compareFilter": {+ "$ref": "#/definitions/CompareFilter",+ "description": "Compare to date range"+ },"dataColorTheme": {"description": "Colors used in the insight's visualization","type": ["number", "null"]diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex d0ca5649ad5d..48c298976807 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1719,6 +1719,8 @@ export interface FunnelsQuery extends InsightsQueryBase<FunnelsQueryResponse> {funnelsFilter?: FunnelsFilter/** Breakdown of the events and actions */breakdownFilter?: BreakdownFilter+ /** Compare to date range */+ compareFilter?: CompareFilter}/** @asType integer */diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex 6690f9a64a75..6fd69f0b2fdb 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -407,8 +407,14 @@ export function isInsightQueryWithBreakdown(export function isInsightQueryWithCompare(node?: Record<string, any> | null-): node is TrendsQuery | StickinessQuery | WebStatsTableQuery | WebOverviewQuery {- return isTrendsQuery(node) || isStickinessQuery(node) || isWebStatsTableQuery(node) || isWebOverviewQuery(node)+): node is TrendsQuery | StickinessQuery | WebStatsTableQuery | WebOverviewQuery | FunnelsQuery {+ return (+ isTrendsQuery(node) ||+ isStickinessQuery(node) ||+ isWebStatsTableQuery(node) ||+ isWebOverviewQuery(node) ||+ isFunnelsQuery(node)+ )}export function isDatabaseSchemaQuery(node?: Node): node is DatabaseSchemaQuery {diff --git a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.tsindex 97d90a8488b0..363b39fca061 100644--- a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts+++ b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts@@ -321,6 +321,103 @@ export const funnelResultTrends = {is_cached: false,}+// 1. Add step "Pageview"+// 2. Select graph type "Trends"+// 3. Toggle "Compare to previous"+// Note: the runner tags rows with `compare_label` but does not set `compare: true` —+// indexedSteps normalizes that so LineGraph dims the previous-period series.+export const funnelResultTrendsCompare = {+ result: [+ {+ count: 31,+ data: [74.12, 68.67, 71.05, 72.06, 69.33, 70.83, 72.37],+ days: ['2023-02-01', '2023-02-02', '2023-02-03', '2023-02-04', '2023-02-05', '2023-02-06', '2023-02-07'],+ labels: ['1-Feb-2023', '2-Feb-2023', '3-Feb-2023', '4-Feb-2023', '5-Feb-2023', '6-Feb-2023', '7-Feb-2023'],+ compare_label: 'current',+ },+ {+ count: 18,+ data: [55.2, 60.1, 58.9, 61.0, 56.4, 59.8, 57.3],+ days: ['2023-01-25', '2023-01-26', '2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31'],+ labels: [+ '25-Jan-2023',+ '26-Jan-2023',+ '27-Jan-2023',+ '28-Jan-2023',+ '29-Jan-2023',+ '30-Jan-2023',+ '31-Jan-2023',+ ],+ compare_label: 'previous',+ },+ ],+ timezone: 'UTC',+ last_refresh: '2023-03-03T18:55:57.840129Z',+ is_cached: false,+}++// 1. Add step "Pageview"+// 2. Select graph type "Trends"+// 3. Break down by country+// 4. Toggle "Compare to previous"+// Note: the runner tags rows with `compare_label` but does not set `compare: true` —+// indexedSteps normalizes that so LineGraph dims the previous-period series.+export const funnelResultTrendsCompareWithBreakdown = {+ result: [+ {+ count: 31,+ data: [74.12, 68.67, 71.05, 72.06, 69.33, 70.83, 72.37],+ days: ['2023-02-01', '2023-02-02', '2023-02-03', '2023-02-04', '2023-02-05', '2023-02-06', '2023-02-07'],+ labels: ['1-Feb-2023', '2-Feb-2023', '3-Feb-2023', '4-Feb-2023', '5-Feb-2023', '6-Feb-2023', '7-Feb-2023'],+ breakdown_value: 'us',+ compare_label: 'current',+ },+ {+ count: 24,+ data: [62.5, 64.1, 60.0, 65.2, 63.4, 61.9, 66.1],+ days: ['2023-02-01', '2023-02-02', '2023-02-03', '2023-02-04', '2023-02-05', '2023-02-06', '2023-02-07'],+ labels: ['1-Feb-2023', '2-Feb-2023', '3-Feb-2023', '4-Feb-2023', '5-Feb-2023', '6-Feb-2023', '7-Feb-2023'],+ breakdown_value: 'uk',+ compare_label: 'current',+ },+ {+ count: 18,+ data: [55.2, 60.1, 58.9, 61.0, 56.4, 59.8, 57.3],+ days: ['2023-01-25', '2023-01-26', '2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31'],+ labels: [+ '25-Jan-2023',+ '26-Jan-2023',+ '27-Jan-2023',+ '28-Jan-2023',+ '29-Jan-2023',+ '30-Jan-2023',+ '31-Jan-2023',+ ],+ breakdown_value: 'us',+ compare_label: 'previous',+ },+ {+ count: 15,+ data: [48.0, 51.3, 50.2, 52.7, 49.8, 53.1, 50.6],+ days: ['2023-01-25', '2023-01-26', '2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31'],+ labels: [+ '25-Jan-2023',+ '26-Jan-2023',+ '27-Jan-2023',+ '28-Jan-2023',+ '29-Jan-2023',+ '30-Jan-2023',+ '31-Jan-2023',+ ],+ breakdown_value: 'uk',+ compare_label: 'previous',+ },+ ],+ timezone: 'UTC',+ last_refresh: '2023-03-03T18:55:57.840129Z',+ is_cached: false,+}+// 1. Add step "Pageview"// 2. Add "Pageview" as exclusion stepexport const funnelInvalidExclusionError = {diff --git a/frontend/src/scenes/funnels/funnelDataLogic.test.ts b/frontend/src/scenes/funnels/funnelDataLogic.test.tsindex e9088e99d412..4e488b1561bf 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.test.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.test.ts@@ -14,6 +14,8 @@ import {funnelResultTimeToConvert,funnelResultTimeToConvertWithoutConversions,funnelResultTrends,+ funnelResultTrendsCompare,+ funnelResultTrendsCompareWithBreakdown,funnelResultWithBreakdown,funnelResultWithMultiBreakdown,} from './__mocks__/funnelDataLogicMocks'@@ -1311,4 +1313,71 @@ describe('funnelDataLogic', () => {})})})++ describe('indexedSteps colorIndex pairing', () => {+ const trendsQuery: FunnelsQuery = {+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: {+ funnelVizType: FunnelVizType.Trends,+ },+ }++ async function loadResult(result: unknown): Promise<void> {+ const insight: Partial<InsightModel> = {+ filters: { insight: InsightType.FUNNELS },+ result: result as InsightModel['result'],+ }+ await expectLogic(logic, () => {+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ logic.actions.updateQuerySource(trendsQuery)+ }).toFinishAllListeners()+ }++ it('assigns colorIndex 0 to a single-period trends result', async () => {+ await loadResult(funnelResultTrends.result)+ const steps = logic.values.indexedSteps as Array<Record<string, unknown>>+ expect(steps).toHaveLength(1)+ expect(steps[0].colorIndex).toBe(0)+ expect(steps[0].seriesIndex).toBe(0)+ })++ it('pairs current and previous on the same colorIndex without a breakdown', async () => {+ await loadResult(funnelResultTrendsCompare.result)+ const steps = logic.values.indexedSteps as Array<Record<string, unknown>>+ expect(steps).toHaveLength(2)+ expect(steps[0].colorIndex).toBe(0)+ expect(steps[1].colorIndex).toBe(0)+ expect(steps[0].seriesIndex).toBe(0)+ expect(steps[1].seriesIndex).toBe(1)+ expect(steps[0].compare_label).toBe('current')+ expect(steps[1].compare_label).toBe('previous')+ // The runner only sets `compare_label`; `indexedSteps` normalizes `compare: true`+ // so LineGraph.processDataset dims the previous-period series.+ expect(steps[0].compare).toBe(true)+ expect(steps[1].compare).toBe(true)+ })++ it('pairs current and previous per breakdown value', async () => {+ await loadResult(funnelResultTrendsCompareWithBreakdown.result)+ const steps = logic.values.indexedSteps as Array<Record<string, unknown>>+ expect(steps).toHaveLength(4)++ const byKey = (label: string, breakdownValue: string): Record<string, unknown> => {+ const found = steps.find((s) => s.compare_label === label && s.breakdown_value === breakdownValue)+ if (!found) {+ throw new Error(`missing row ${label}/${breakdownValue}`)+ }+ return found+ }+ const currentUs = byKey('current', 'us')+ const previousUs = byKey('previous', 'us')+ const currentUk = byKey('current', 'uk')+ const previousUk = byKey('previous', 'uk')++ expect(currentUs.colorIndex).toBe(previousUs.colorIndex)+ expect(currentUk.colorIndex).toBe(previousUk.colorIndex)+ expect(currentUs.colorIndex).not.toBe(currentUk.colorIndex)+ })+ })})diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.tsindex 8e59bd5b9d51..da165093a073 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts@@ -637,8 +637,38 @@ export const funnelDataLogic = kea<funnelDataLogicType>([],indexedSteps: [(s) => [s.steps],- (steps) =>- Array.isArray(steps) ? steps.map((step, index) => ({ ...step, seriesIndex: index, id: index })) : [],+ (steps) => {+ if (!Array.isArray(steps)) {+ return []+ }+ // Pair rows on `breakdown_value` (no `compare_label`) so current/previous of the+ // same series share the same base color. The downstream color resolver prefers+ // `colorIndex` over `seriesIndex` (see `getTrendResultCustomizationColorToken`),+ // and `LineGraph.processDataset` then dims the previous-period series to 50% alpha.+ const colorIndexMap = new Map<string, number>()+ for (const step of steps) {+ const key = getFunnelDatasetKey(step)+ if (!colorIndexMap.has(key)) {+ colorIndexMap.set(key, colorIndexMap.size)+ }+ }+ return steps.map((step, index) => {+ // The funnels runner tags compare rows with `compare_label` but doesn't set+ // `compare: true`. `LineGraph.processDataset` requires both to dim the previous+ // line — normalize here so the previous-period series renders at 50% alpha.+ const stepWithCompare = step as typeof step & {+ compare_label?: 'current' | 'previous'+ compare?: boolean+ }+ return {+ ...step,+ seriesIndex: index,+ colorIndex: colorIndexMap.get(getFunnelDatasetKey(step)) ?? 0,+ id: index,+ compare: stepWithCompare.compare_label != null ? true : stepWithCompare.compare,+ }+ })+ },],getFunnelsColorToken: [(s) => [s.resultCustomizations, s.getTheme, s.breakdownFilter, s.querySource],diff --git a/frontend/src/scenes/insights/Funnels.stories.tsx b/frontend/src/scenes/insights/Funnels.stories.tsxindex f88e2da66281..26881097f712 100644--- a/frontend/src/scenes/insights/Funnels.stories.tsx+++ b/frontend/src/scenes/insights/Funnels.stories.tsx@@ -4,6 +4,7 @@ import { Meta, StoryObj } from '@storybook/react'import { waitFor } from '@testing-library/dom'import userEvent from '@testing-library/user-event'+import { FEATURE_FLAGS } from 'lib/constants'import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'import { mswDecorator } from '~/mocks/browser'@@ -128,6 +129,15 @@ export const FunnelHistoricalTrendsEdit: Story = createInsightStory(FunnelHistoricalTrendsEdit.parameters = {testOptions: { waitForSelector: '[data-attr=trend-line-graph-funnel] > canvas' },}+export const FunnelHistoricalTrendsCompare: Story = createInsightStory(+ require('../../mocks/fixtures/api/projects/team_id/insights/funnelHistoricalTrendsCompare.json')+)+FunnelHistoricalTrendsCompare.parameters = {+ // funnels-compare gates the Compare-to-previous toggle on funnel trends — without this the+ // dual-period chart degrades back to the single-period rendering and the snapshot is wrong.+ featureFlags: [FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE],+ testOptions: { waitForSelector: '[data-attr=trend-line-graph-funnel] > canvas' },+}export const FunnelTimeToConvert: Story = createInsightStory(require('../../mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvert.json')diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 8d1f760cc3a3..811c863f95b5 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -9,8 +9,9 @@ import {} from 'lib/components/InsightLegend/utils'import { Intervals, intervals } from 'lib/components/IntervalFilter/intervals'import { parseProperties } from 'lib/components/PropertyFilters/utils'-import { NON_TIME_SERIES_DISPLAY_TYPES, NON_VALUES_ON_SERIES_DISPLAY_TYPES } from 'lib/constants'+import { FEATURE_FLAGS, NON_TIME_SERIES_DISPLAY_TYPES, NON_VALUES_ON_SERIES_DISPLAY_TYPES } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { dateMapping, is12HoursOrLess, isLessThan2Days } from 'lib/utils'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'@@ -99,7 +100,14 @@ import {supportsBarValueStacking,supportsPercentStackView,} from '~/queries/utils'-import { BaseMathType, ChartDisplayType, InsightLogicProps, LabelGroupType, SlowQueryPossibilities } from '~/types'+import {+ BaseMathType,+ ChartDisplayType,+ FunnelVizType,+ InsightLogicProps,+ LabelGroupType,+ SlowQueryPossibilities,+} from '~/types'import type { insightVizDataLogicType } from './insightVizDataLogicType'@@ -122,6 +130,8 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([['dataWarehouseTablesMap'],dataThemeLogic,['getTheme'],+ featureFlagLogic,+ ['featureFlags'],],actions: [insightDataLogic,@@ -212,12 +222,24 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([isTrendsLike: [(s) => [s.querySource], (q) => isTrendsQuery(q) || isLifecycleQuery(q) || isStickinessQuery(q)], // this is for filtering out world mapsupportsDisplay: [(s) => [s.querySource], (q) => isTrendsQuery(q) || isStickinessQuery(q)],supportsCompare: [- (s) => [s.querySource, s.display, s.dateRange],- (q, display, dateRange) =>- (isTrendsQuery(q) || isStickinessQuery(q) || isWebAnalyticsInsightQuery(q)) &&- display !== ChartDisplayType.WorldMap &&- display !== ChartDisplayType.CalendarHeatmap &&- dateRange?.date_from !== 'all',+ (s) => [s.querySource, s.display, s.dateRange, s.featureFlags],+ (q, display, dateRange, featureFlags) => {+ if (dateRange?.date_from === 'all') {+ return false+ }+ if (isTrendsQuery(q) || isStickinessQuery(q) || isWebAnalyticsInsightQuery(q)) {+ return display !== ChartDisplayType.WorldMap && display !== ChartDisplayType.CalendarHeatmap+ }+ // Funnel compare ships behind a flag, and only for the TRENDS viz mode in slice 1.+ if (+ isFunnelsQuery(q) &&+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE] &&+ q.funnelsFilter?.funnelVizType === FunnelVizType.Trends+ ) {+ return true+ }+ return false+ },],supportsPercentStackView: [(s) => [s.querySource], (q) => supportsPercentStackView(q)],supportsBarValueStacking: [(s) => [s.querySource], (q) => supportsBarValueStacking(q)],diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsxindex 8ec0f73a0732..41cacfccb352 100644--- a/frontend/src/scenes/insights/utils.tsx+++ b/frontend/src/scenes/insights/utils.tsx@@ -563,7 +563,7 @@ export function insightUrlForEvent(event: Pick<EventType, 'event' | 'properties'return query ? urls.insightNew({ query }) : undefined}-export function getFunnelDatasetKey(dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics): string {+export function getFunnelDatasetKey(dataset: { breakdown_value?: BreakdownKeyType }): string {const breakdown_value =Array.isArray(dataset.breakdown_value) && dataset.breakdown_value.length == 1? dataset.breakdown_value[0]diff --git a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py b/posthog/hogql_queries/insights/funnels/funnels_query_runner.pyindex 6e46545b3995..158458b75db9 100644--- a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnels_query_runner.py@@ -1,10 +1,17 @@+import threadingfrom collections.abc import Sequencefrom datetime import datetime, timedeltafrom math import ceilfrom typing import Any, Optional+from django.conf import settings++import structlog+import posthoganalytics+from posthog.schema import (CachedFunnelsQueryResponse,+ DateRange,FunnelsQuery,FunnelsQueryResponse,FunnelVizType,@@ -19,6 +26,8 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimingsfrom posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL+from posthog.clickhouse import query_tagging+from posthog.clickhouse.query_tagging import QueryTagsfrom posthog.hogql_queries.insights.funnels import FunnelTrendsUDF, FunnelUDFfrom posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContextfrom posthog.hogql_queries.insights.funnels.funnel_time_to_convert import FunnelTimeToConvertUDF@@ -29,13 +38,17 @@ from posthog.hogql_queries.insights.funnels.funnel_validation_rules import (ValidateOptionalFunnelSteps,)from posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRangefrom posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRangefrom posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettingsfrom posthog.hogql_queries.validation.validation import QueryValidationRulefrom posthog.models import Teamfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.user import User+logger = structlog.get_logger(__name__)+class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):query: FunnelsQuery@@ -97,7 +110,24 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):return self.funnel_actor_class.actor_query()def _calculate(self):- query = self.to_query()+ if self._is_compare_active():+ return self._calculate_compare()+ return self._calculate_single_period(self.funnel_class)++ def _calculate_single_period(+ self,+ funnel_class,+ timings_override: Optional[HogQLTimings] = None,+ date_range_override: Optional[QueryDateRange] = None,+ ) -> FunnelsQueryResponse:+ query = funnel_class.get_query()+ # Compare runs subqueries in parallel threads; each worker passes its own clone since+ # HogQLTimings is not thread-safe. Single-period runs fall back to the shared instance.+ effective_timings = timings_override if timings_override is not None else self.timings+ # Previous-period funnels resolve a shifted date range; without the override the response+ # would advertise the current-period range, which is wrong for any caller that inspects+ # resolved_date_range on a non-current sub-response.+ effective_date_range = date_range_override if date_range_override is not None else self.query_date_rangetimings = []# TODO: can we get this from execute_hogql_query as well?@@ -108,7 +138,7 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):query=query,team=self.team,user=self.user,- timings=self.timings,+ timings=effective_timings,modifiers=self.modifiers,limit_context=self.limit_context,settings=HogQLGlobalSettings(@@ -117,7 +147,7 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):),)- results = self.funnel_class._format_results(response.results)+ results = funnel_class._format_results(response.results)if response.timings is not None:timings.extend(response.timings)@@ -127,12 +157,150 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):timings=timings,hogql=hogql,modifiers=self.modifiers,+ resolved_date_range=ResolvedDateRangeResponse(+ date_from=effective_date_range.date_from(),+ date_to=effective_date_range.date_to(),+ ),+ )++ def _calculate_compare(self) -> FunnelsQueryResponse:+ """Run current + previous period queries and merge tagged rows.++ Each row in `results: Any` is tagged with `compare_label: 'current' | 'previous'`. The+ response shape is otherwise identical to a single-period response — this is the contract+ the frontend (and later viz-mode slices) rely on. Two parallel queries instead of a UNION+ because funnel queries are CTE/UDF-heavy; doubling cost is the explicit trade-off.+ """+ previous_funnel = self._build_previous_funnel()+ responses: list[Optional[FunnelsQueryResponse]] = [None, None]+ errors: list[Exception] = []+ funnels = [self.funnel_class, previous_funnel]+ # Aligns each sub-response's resolved_date_range with the period it actually computed,+ # rather than leaking the current-period range into the previous-period response.+ date_ranges = [self.query_date_range, self.query_previous_date_range]++ def run(index: int, timings: HogQLTimings, query_tags: Optional[QueryTags] = None) -> None:+ try:+ # Worker threads start with an empty QueryTags ContextVar — restore the parent's+ # snapshot so execute_hogql_query has the required feature/product tags.+ if query_tags is not None:+ query_tagging.update_tags(query_tags)+ responses[index] = self._calculate_single_period(+ funnels[index],+ timings_override=timings,+ date_range_override=date_ranges[index],+ )+ except Exception as exc: # noqa: BLE001+ errors.append(exc)+ finally:+ if not settings.IN_UNIT_TESTING:+ # Close the per-thread DB connection so this thread doesn't leak it.+ from django.db import connection++ connection.close()++ if settings.IN_UNIT_TESTING:+ # Django + threads in tests is flaky; trends compare uses the same bypass.+ for index in range(len(funnels)):+ run(index, self.timings.clone_for_subquery(index))+ else:+ parent_tags = query_tagging.get_query_tags().model_copy(deep=True)+ jobs = [+ threading.Thread(+ target=run,+ args=(index, self.timings.clone_for_subquery(index), parent_tags),+ )+ for index in range(len(funnels))+ ]+ for job in jobs:+ job.start()+ for job in jobs:+ job.join()++ if errors:+ # Surface every secondary error with its traceback before re-raising the first,+ # so dual-query failures don't disappear into the void.+ for dropped in errors[1:]:+ logger.exception("funnels_compare_secondary_error", exc_info=dropped)+ raise errors[0]++ current_response, previous_response = responses+ assert current_response is not None and previous_response is not None++ merged_results = []+ for row in current_response.results or []:+ row["compare_label"] = "current"+ merged_results.append(row)+ for row in previous_response.results or []:+ row["compare_label"] = "previous"+ merged_results.append(row)++ timings = list(current_response.timings or []) + list(previous_response.timings or [])++ return FunnelsQueryResponse(+ results=merged_results,+ timings=timings,+ hogql=current_response.hogql,+ modifiers=self.modifiers,resolved_date_range=ResolvedDateRangeResponse(date_from=self.query_date_range.date_from(),date_to=self.query_date_range.date_to(),),)+ def _build_previous_funnel(self) -> FunnelTrendsUDF:+ """Construct a FunnelTrendsUDF pinned to the previous-period date range.++ The previous query is a clone of `self.query` with its `dateRange` swapped for the+ shifted range and `compareFilter` cleared (to prevent infinite recursion if the cloned+ query ever flows back through this runner).+ """+ prev_date_from = self.query_previous_date_range.date_from()+ prev_date_to = self.query_previous_date_range.date_to()+ previous_query = self.query.model_copy(+ update={+ "dateRange": DateRange(+ date_from=prev_date_from.isoformat() if prev_date_from else None,+ date_to=prev_date_to.isoformat() if prev_date_to else None,+ explicitDate=True,+ ),+ "compareFilter": None,+ }+ )+ previous_context = FunnelQueryContext(+ query=previous_query,+ team=self.team,+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ )+ return FunnelTrendsUDF(context=previous_context, just_summarize=self.just_summarize)++ def _is_compare_active(self) -> bool:+ compare_filter = self.query.compareFilter+ if compare_filter is None or not compare_filter.compare:+ return False+ # Slice 1 ships compare only for the TRENDS viz mode. Other viz modes land in later slices.+ if self.context.funnelsFilter.funnelVizType != FunnelVizType.TRENDS:+ return False+ return self._team_flag_funnels_compare()++ def _team_flag_funnels_compare(self) -> bool:+ return posthoganalytics.feature_enabled(+ "product-analytics-funnels-compare",+ str(self.team.uuid),+ groups={+ "organization": str(self.team.organization_id),+ "project": str(self.team.id),+ },+ group_properties={+ "organization": {"id": str(self.team.organization_id)},+ "project": {"id": str(self.team.id)},+ },+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+@cached_propertydef funnel_order_class(self):return FunnelUDF(context=self.context)@@ -168,3 +336,21 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):now=datetime.now(),exact_timerange=self.exact_timerange,)++ @cached_property+ def query_previous_date_range(self) -> QueryDateRange:+ compare_filter = self.query.compareFilter+ if compare_filter is not None and compare_filter.compare_to:+ return QueryCompareToDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=self.query.interval,+ now=datetime.now(),+ compare_to=compare_filter.compare_to,+ )+ return QueryPreviousPeriodDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=self.query.interval,+ now=datetime.now(),+ )diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.pyindex 15d804fe7c70..5db1fc28f55b 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py@@ -10,12 +10,16 @@ from posthog.test.base import (_create_person,snapshot_clickhouse_queries,)+from unittest.mock import patch++from django.test import override_settingsfrom parameterized import parameterizedfrom posthog.schema import (BreakdownAttributionType,BreakdownFilter,+ CompareFilter,DateRange,EventPropertyFilter,EventsNode,@@ -3445,3 +3449,184 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):self.assertEqual(1, results[0]["reached_from_step_count"])self.assertEqual(0, results[0]["reached_to_step_count"])+++@override_settings(IN_UNIT_TESTING=True)+class TestFunnelTrendsCompareUDF(ClickhouseTestMixin, APIBaseTest):+ """Compare-to-previous on funnel TRENDS viz. Tagged-row contract that later viz modes will reuse."""++ maxDiff = None++ def _build_query(+ self,+ date_from: str = "2021-06-07 00:00:00",+ date_to: str = "2021-06-13 23:59:59",+ compare: bool = True,+ compare_to: Optional[str] = None,+ ) -> FunnelsQuery:+ return FunnelsQuery(+ dateRange=DateRange(date_from=date_from, date_to=date_to),+ interval="day",+ series=[EventsNode(event="step one"), EventsNode(event="step two")],+ funnelsFilter=FunnelsFilter(+ funnelVizType="trends",+ funnelWindowInterval=7,+ funnelWindowIntervalUnit="day",+ ),+ compareFilter=CompareFilter(compare=compare, compare_to=compare_to),+ )++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_default_previous_period_tags_rows(self, _feature_enabled):+ # Current period 2021-06-07 .. 2021-06-13. Default previous is the prior 7-day window+ # (2021-05-31 .. 2021-06-06). One conversion lands in each window.+ journeys_for(+ {+ "current_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ "previous_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 1, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 1, 11)},+ ],+ },+ self.team,+ )++ results = FunnelsQueryRunner(query=self._build_query(), team=self.team).calculate().results++ # Frontend-facing shape: one summarized series per period, tagged with compare_label.+ # This is the same contract STEPS and TIME_TO_CONVERT slices will reuse.+ labels = [row.get("compare_label") for row in results]+ self.assertEqual(labels, ["current", "previous"])++ current_series = next(r for r in results if r["compare_label"] == "current")+ previous_series = next(r for r in results if r["compare_label"] == "previous")++ # Each series carries the standard summarized funnel-trends payload (count is interval count).+ self.assertEqual(len(current_series["data"]), 7)+ self.assertEqual(len(previous_series["data"]), 7)+ # Conversion happened on day index 1 (June 8) in current and day index 1 (June 1) in previous.+ # Conversion rate is 100% (1/1) so the data point is 100.0.+ self.assertIn(100.0, current_series["data"])+ self.assertIn(100.0, previous_series["data"])+ # Day labels for current period start at 2021-06-07; previous at 2021-05-31.+ self.assertEqual(current_series["days"][0], "2021-06-07")+ self.assertEqual(previous_series["days"][0], "2021-05-31")++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_with_custom_offset_shifts_previous_window(self, _feature_enabled):+ # Custom offset `-30d` puts the previous window 30 days before the current window's start+ # regardless of the current window's length.+ journeys_for(+ {+ "current_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ "previous_user": [+ # 2021-05-08 = 30 days before 2021-06-07+ {"event": "step one", "timestamp": datetime(2021, 5, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 5, 8, 11)},+ ],+ "noise_user": [+ # Falls in the *default* previous window but NOT in the -30d window: must be ignored.+ {"event": "step one", "timestamp": datetime(2021, 6, 1, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 1, 11)},+ ],+ },+ self.team,+ )++ results = FunnelsQueryRunner(query=self._build_query(compare_to="-30d"), team=self.team).calculate().results++ previous_series = next(r for r in results if r["compare_label"] == "previous")+ # Previous window starts 30 days before the current window's start (2021-06-07 - 30d = 2021-05-08).+ self.assertEqual(previous_series["days"][0], "2021-05-08")+ # The conversion on 2021-05-08 lands inside the previous window.+ self.assertIn(100.0, previous_series["data"])+ # The 2021-06-01 conversion (default-previous window) does NOT contribute here.+ self.assertEqual(previous_series["data"].count(100.0), 1)++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_with_empty_previous_period(self, _feature_enabled):+ # Only the current period has events; previous-period series must still be returned (zeroed).+ journeys_for(+ {+ "current_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ },+ self.team,+ )++ results = FunnelsQueryRunner(query=self._build_query(), team=self.team).calculate().results++ labels = [row["compare_label"] for row in results]+ self.assertEqual(labels, ["current", "previous"])++ previous_series = next(r for r in results if r["compare_label"] == "previous")+ # Skeleton intact: 7 days, no conversions.+ self.assertEqual(len(previous_series["data"]), 7)+ self.assertEqual(len(previous_series["days"]), 7)+ self.assertEqual(set(previous_series["data"]), {0.0})++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_holds_funnel_window_constant(self, _feature_enabled):+ # The previous-period sub-runner must use the same funnel window as the current-period one.+ # Only the date range shifts when compare is on; funnelWindowInterval / funnelWindowIntervalUnit+ # stay put. This is what keeps current and previous comparable.+ runner = FunnelsQueryRunner(query=self._build_query(), team=self.team)+ previous_funnel = runner._build_previous_funnel()++ # Structural contract: previous funnel inherits the same funnelsFilter (window, attribution, etc.)+ self.assertEqual(previous_funnel.context.funnelsFilter, runner.context.funnelsFilter)+ # Sanity: compareFilter is cleared on the previous query so it can't recurse.+ self.assertIsNone(previous_funnel.context.query.compareFilter)+ # Sanity: previous query's dateRange differs from current.+ self.assertNotEqual(previous_funnel.context.query.dateRange, runner.query.dateRange)++ @patch("posthoganalytics.feature_enabled", return_value=False)+ def test_compare_feature_flag_off_returns_single_period(self, _feature_enabled):+ # When the `funnels-compare` flag is off, the runner ignores compareFilter and behaves+ # as if compare=False — saved-funnel safety.+ journeys_for(+ {+ "u": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ },+ self.team,+ )++ results = FunnelsQueryRunner(query=self._build_query(), team=self.team).calculate().results++ # Single-period response: one summarized series, no compare_label tagging.+ self.assertEqual(len(results), 1)+ self.assertNotIn("compare_label", results[0])++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_with_all_time_date_range(self, _feature_enabled):+ # When date_from='all', mirror trends' behavior: the runner does not reject the query;+ # the previous period is whatever QueryPreviousPeriodDateRange resolves to and rows are+ # tagged accordingly. The frontend toggle hides "compare" when date_from='all', but the+ # backend stays tolerant of stale clients.+ journeys_for(+ {+ "u": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ },+ self.team,+ )++ query = self._build_query(date_from="all", date_to="2021-06-13 23:59:59")+ results = FunnelsQueryRunner(query=query, team=self.team).calculate().results++ labels = {row.get("compare_label") for row in results}+ # The orchestrator still emits both tags; the data may be empty / overlapping — that's expected.+ self.assertEqual(labels, {"current", "previous"})diff --git a/posthog/schema.py b/posthog/schema.pyindex 20a5835c2e72..2cb65f0d3f8c 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -23604,6 +23604,7 @@ class FunnelsQuery(BaseModel):)aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")breakdownFilter: BreakdownFilter | None = Field(default=None, description="Breakdown of the events and actions")+ compareFilter: CompareFilter | None = Field(default=None, description="Compare to date range")dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")dateRange: DateRange | None = Field(default=None, description="Date range for the query")filterTestAccounts: bool | None = Field(diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 48fce477300b..e5cba3601828 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2478,6 +2478,8 @@ export interface FunnelsQueryApi {aggregation_group_type_index?: number | null/** Breakdown of the events and actions */breakdownFilter?: BreakdownFilterApi | null+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null/** Colors used in the insight's visualization */dataColorTheme?: number | null/** Date range for the query */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 5f57a18920e4..01031e2e03e6 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -2013,6 +2013,8 @@ export interface FunnelsQueryApi {aggregation_group_type_index?: number | null/** Breakdown of the events and actions */breakdownFilter?: BreakdownFilterApi | null+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null/** Colors used in the insight's visualization */dataColorTheme?: number | null/** Date range for the query */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 825e1f608e6a..ed002ff429b0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2452,6 +2452,8 @@ export namespace Schemas {aggregation_group_type_index?: number | null;/** Breakdown of the events and actions */breakdownFilter?: BreakdownFilter | null;+ /** Compare to date range */+ compareFilter?: CompareFilter | null;/** Colors used in the insight's visualization */dataColorTheme?: number | null;/** Date range for the query */