: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 funnel steps viz (#64055)
Thomas Obermüller6bf3141d8c42
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 79ba7732d774..f22c57ccdbad 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5436,6 +5436,10 @@ snapshots:hash: v1.k794b7964.1df97c88a1076b096c08deccb8c4c291c13b6a4a59fb615e2d77254547381c48.gTsDByOCU_bfzNraCRF_0neMgtIfTq796QitehbRNVQscenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:hash: v1.k794b7964.fcca265dc40531abfaeacdd71516413f6be97d773801b41204984515bcfef7e5.4QKORBqqQqXYcI8OeFErU3aC7gNVdKvl_HAZDwEsv_0+ scenes-app-insights-funnels--funnel-left-to-right-compare--dark:+ hash: v1.k794b7964.c06558a5d730d4d4787f1c99172c390030bf55f05ed7596bd4d1f6bd0bbe0a1a.kxR9FFETw4hbO_cV17X3fMfFOrrxD2w-I8gACLI3WG4+ scenes-app-insights-funnels--funnel-left-to-right-compare--light:+ hash: v1.k794b7964.efd117b25bc08be5aafeea0d2eebbb2d4b07a542e762584e99b8b68172520877.emnTmFYizx7ABBBfqC7j-WmDRIqgqkQHt7Wv5kj0H4sscenes-app-insights-funnels--funnel-left-to-right-edit--dark:hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.xupnP9sdcp25xPBOMzrhSHwtRpKPLKHaqLDBncapvQAscenes-app-insights-funnels--funnel-left-to-right-edit--light:diff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelLeftToRightCompare.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelLeftToRightCompare.jsonnew file mode 100644index 000000000000..d1649635ad60--- /dev/null+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelLeftToRightCompare.json@@ -0,0 +1,170 @@+{+ "id": 5151,+ "short_id": "funCmpST",+ "name": "Funnel steps compare",+ "derived_name": "Pageview \u2192 Pageview \u2192 Pageview user conversion rate",+ "filters": {},+ "filters_hash": "cache_85ca8909ab22e34f387fa4f17e919410",+ "order": null,+ "deleted": false,+ "dashboard": null,+ "layouts": {},+ "color": null,+ "last_refresh": null,+ "refreshing": false,+ "result": [+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 0,+ "people": [],+ "count": 20166,+ "type": "events",+ "average_conversion_time": null,+ "median_conversion_time": null,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=1&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": null,+ "compare_label": "current"+ },+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 1,+ "people": [],+ "count": 8438,+ "type": "events",+ "average_conversion_time": 370.48673834484913,+ "median_conversion_time": 0,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=2&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=-2&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "compare_label": "current"+ },+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 2,+ "people": [],+ "count": 2864,+ "type": "events",+ "average_conversion_time": 398.36358625967165,+ "median_conversion_time": 0,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=3&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=-3&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "compare_label": "current"+ },+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 0,+ "people": [],+ "count": 16000,+ "type": "events",+ "average_conversion_time": null,+ "median_conversion_time": null,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=1&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": null,+ "compare_label": "previous"+ },+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 1,+ "people": [],+ "count": 6200,+ "type": "events",+ "average_conversion_time": 426.05974909657647,+ "median_conversion_time": 0,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=2&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=-2&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "compare_label": "previous"+ },+ {+ "action_id": "$pageview",+ "name": "$pageview",+ "custom_name": null,+ "order": 2,+ "people": [],+ "count": 1900,+ "type": "events",+ "average_conversion_time": 458.11812419862235,+ "median_conversion_time": 0,+ "converted_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=3&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "dropped_people_url": "/api/person/funnel/?date_from=2022-03-08T00%3A00%3A00%2B00%3A00&date_to=2022-03-15T21%3A42%3A48.469119%2B00%3A00&display=FunnelViz&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+1%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%2C+%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+2%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&funnel_step=-3&funnel_viz_type=steps&funnel_window_interval=14&funnel_window_interval_unit=day&insight=FUNNELS&interval=day&limit=100",+ "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:42:52.989476Z",+ "tags": [],+ "favorited": false,+ "saved": true,+ "last_modified_at": "2022-03-15T21:42:52.984610Z",+ "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": {+ "funnelsFilter": {+ "exclusions": [],+ "funnelVizType": "steps"+ },+ "interval": "day",+ "kind": "FunnelsQuery",+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": []+ }+ ]+ },+ "samplingFactor": 0.1,+ "series": [+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview"+ },+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview",+ "optionalInFunnel": true+ },+ {+ "event": "$pageview",+ "kind": "EventsNode",+ "name": "$pageview"+ }+ ],+ "compareFilter": {+ "compare": true+ },+ "dateRange": {+ "date_from": "2022-03-08",+ "date_to": "2022-03-15"+ }+ },+ "full": true+ }+}diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsxindex d859e8821bb0..fac61720f15d 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx@@ -134,7 +134,7 @@ export function InsightDisplayConfig(): JSX.Element {!isSlopeGraph) ||isStickiness ||isWebAnalyticsInsightQuery(querySource) ||- (funnelsCompareEnabled && (isTrendsFunnel || isTimeToConvertFunnel))+ (funnelsCompareEnabled && isFunnels)const showInterval =isTrendsFunnel ||isLifecycle ||diff --git a/frontend/src/scenes/funnels/FunnelTooltip.tsx b/frontend/src/scenes/funnels/FunnelTooltip.tsxindex 1c45c0814a27..74dd1caebd20 100644--- a/frontend/src/scenes/funnels/FunnelTooltip.tsx+++ b/frontend/src/scenes/funnels/FunnelTooltip.tsx@@ -22,6 +22,7 @@ import { FunnelStepWithConversionMetrics } from '~/types'import { funnelDataLogic } from './funnelDataLogic'import { funnelTooltipLogic } from './funnelTooltipLogic'+import { funnelComparePeriodDateRange } from './funnelUtils'/** The tooltip is offset horizontally by a few pixels from the bar to give it some breathing room. */const FUNNEL_TOOLTIP_OFFSET_PX = 4@@ -33,6 +34,8 @@ export interface FunnelTooltipProps {groupTypeLabel: stringbreakdownFilter: BreakdownFilter | null | undefinedembedded?: boolean+ /** Date range of the hovered series' compare period; shown when the series is compare-tagged. */+ comparePeriodDateRange?: string | null}export function FunnelTooltip({@@ -42,6 +45,7 @@ export function FunnelTooltip({groupTypeLabel,breakdownFilter,embedded = false,+ comparePeriodDateRange,}: FunnelTooltipProps): JSX.Element {const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)@@ -58,12 +62,16 @@ export function FunnelTooltip({<strong><EntityFilterInfo filter={getActionFilterFromFunnelStep(series)} allowWrap /><span className="mx-1">•</span>- {formatBreakdownLabel(- series.breakdown_value,- breakdownFilter,- allCohorts.results,- formatPropertyValueForDisplay- )}+ {series.compare_label+ ? `${series.compare_label === 'current' ? 'Current' : 'Previous'}${+ comparePeriodDateRange ? ` (${comparePeriodDateRange})` : ''+ }`+ : formatBreakdownLabel(+ series.breakdown_value,+ breakdownFilter,+ allCohorts.results,+ formatPropertyValueForDisplay+ )}</strong></LemonRow><LemonDivider className="my-2" />@@ -115,7 +123,7 @@ export function FunnelTooltip({export function useFunnelTooltip(showPersonsModal: boolean): React.RefObject<HTMLDivElement> {const { insightProps } = useValues(insightLogic)- const { breakdownFilter, querySource } = useValues(funnelDataLogic(insightProps))+ const { breakdownFilter, querySource, insightData } = useValues(funnelDataLogic(insightProps))const { isTooltipShown, currentTooltip, tooltipOrigin } = useValues(funnelTooltipLogic(insightProps))const { aggregationLabel } = useValues(groupsModel)@@ -137,6 +145,15 @@ export function useFunnelTooltip(showPersonsModal: boolean): React.RefObject<HTMseries={currentTooltip[1]}groupTypeLabel={aggregationLabel(querySource?.aggregation_group_type_index).plural}breakdownFilter={breakdownFilter}+ comparePeriodDateRange={+ currentTooltip[1].compare_label+ ? funnelComparePeriodDateRange(+ currentTooltip[1].compare_label,+ insightData?.resolved_date_range,+ querySource?.compareFilter?.compare_to+ )+ : null+ }/>)}</>diff --git a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.tsindex 3ea14103763b..cd2680aefe71 100644--- a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts+++ b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts@@ -448,6 +448,74 @@ export const funnelResultTrendsCompareWithBreakdown = {is_cached: false,}+// 1. Add steps "sign up" -> "buy"+// 2. Toggle "Compare to previous" (default STEPS viz, no breakdown)+// The runner returns a flat list of step dicts for both periods, each tagged with compare_label:+// [step0_current, step1_current, step0_previous, step1_previous].+export const funnelResultStepsCompare: FunnelAPIResponse = {+ result: [+ {+ action_id: 'sign up',+ name: 'sign up',+ custom_name: null,+ order: 0,+ people: [],+ count: 200,+ type: 'events',+ average_conversion_time: null,+ median_conversion_time: null,+ converted_people_url: '',+ dropped_people_url: null,+ compare_label: 'current',+ },+ {+ action_id: 'buy',+ name: 'buy',+ custom_name: null,+ order: 1,+ people: [],+ count: 100,+ type: 'events',+ average_conversion_time: 3600,+ median_conversion_time: 1800,+ converted_people_url: '',+ dropped_people_url: null,+ compare_label: 'current',+ },+ {+ action_id: 'sign up',+ name: 'sign up',+ custom_name: null,+ order: 0,+ people: [],+ count: 150,+ type: 'events',+ average_conversion_time: null,+ median_conversion_time: null,+ converted_people_url: '',+ dropped_people_url: null,+ compare_label: 'previous',+ },+ {+ action_id: 'buy',+ name: 'buy',+ custom_name: null,+ order: 1,+ people: [],+ count: 60,+ type: 'events',+ average_conversion_time: 4200,+ median_conversion_time: 2100,+ converted_people_url: '',+ dropped_people_url: null,+ compare_label: 'previous',+ },+ ],+ timezone: 'UTC',+ last_refresh: '2023-02-22T08:24:07.710763Z',+ is_cached: true,+}+// 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 d63b87bdb9d1..9fc5486112ab 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.test.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.test.ts@@ -11,6 +11,7 @@ import { FunnelConversionWindowTimeUnit, FunnelVizType, InsightLogicProps, Insigimport {funnelResult,+ funnelResultStepsCompare,funnelResultTimeToConvert,funnelResultTimeToConvertCompare,funnelResultTimeToConvertWithoutConversions,@@ -21,6 +22,7 @@ import {funnelResultWithMultiBreakdown,} from './__mocks__/funnelDataLogicMocks'import { funnelDataLogic } from './funnelDataLogic'+import { dimPreviousPeriodColor } from './funnelUtils'let logic: ReturnType<typeof funnelDataLogic.build>let builtDataNodeLogic: ReturnType<typeof dataNodeLogic.build>@@ -1439,4 +1441,100 @@ describe('funnelDataLogic', () => {expect(currentUs.colorIndex).not.toBe(currentUk.colorIndex)})})++ describe('steps compare (grouped bars)', () => {+ const stepsQuery: FunnelsQuery = {+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: { funnelVizType: FunnelVizType.Steps },+ compareFilter: { compare: true },+ }++ async function loadStepsCompare(result: unknown): Promise<void> {+ const insight: Partial<InsightModel> = {+ filters: { insight: InsightType.FUNNELS },+ result: result as InsightModel['result'],+ }+ await expectLogic(logic, () => {+ logic.actions.updateQuerySource(stepsQuery)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toFinishAllListeners()+ }++ it('reshapes a compare-tagged flat result into one step per order with current+previous bars', async () => {+ await loadStepsCompare(funnelResultStepsCompare.result)++ const steps = logic.values.visibleStepsWithConversionMetrics+ // One column per funnel step (not one per period).+ expect(steps).toHaveLength(2)++ // Each step renders two bars: current then previous, tagged accordingly.+ steps.forEach((step) => {+ expect(step.nested_breakdown).toHaveLength(2)+ expect(step.nested_breakdown?.[0].compare_label).toBe('current')+ expect(step.nested_breakdown?.[1].compare_label).toBe('previous')+ })++ // Counts come from the respective period (current 200->100, previous 150->60).+ expect(steps[0].nested_breakdown?.[0].count).toBe(200)+ expect(steps[0].nested_breakdown?.[1].count).toBe(150)+ expect(steps[1].nested_breakdown?.[0].count).toBe(100)+ expect(steps[1].nested_breakdown?.[1].count).toBe(60)+ })++ it('scales both periods against a shared baseline so the previous bar reflects its volume', async () => {+ await loadStepsCompare(funnelResultStepsCompare.result)++ const steps = logic.values.visibleStepsWithConversionMetrics++ // Bar height (fromBasisStep) is relative to the larger period's first step (200).+ expect(steps[0].nested_breakdown?.[0].conversionRates.fromBasisStep).toBe(1) // 200/200+ expect(steps[0].nested_breakdown?.[1].conversionRates.fromBasisStep).toBe(150 / 200) // not full height+ expect(steps[1].nested_breakdown?.[0].conversionRates.fromBasisStep).toBe(100 / 200)+ expect(steps[1].nested_breakdown?.[1].conversionRates.fromBasisStep).toBe(60 / 200)++ // Tooltip conversion rates stay per-period: previous step 1 converts 60/150 of its own funnel.+ expect(steps[0].nested_breakdown?.[1].conversionRates.total).toBe(1)+ expect(steps[1].nested_breakdown?.[1].conversionRates.total).toBe(60 / 150)+ })++ it('renders the previous-period bar desaturated relative to the current bar', async () => {+ await loadStepsCompare(funnelResultStepsCompare.result)++ const step = logic.values.visibleStepsWithConversionMetrics[0]+ const currentSeries = step.nested_breakdown![0]+ const previousSeries = step.nested_breakdown![1]++ const currentColor = logic.values.getFunnelsColor(currentSeries)+ const previousColor = logic.values.getFunnelsColor(previousSeries)++ // Both bars share the base hue; the previous one is dimmed to 50% opacity.+ expect(previousColor).toBe(dimPreviousPeriodColor(currentColor))+ expect(previousColor).not.toBe(currentColor)+ })++ it('leaves a non-compared steps funnel unchanged (single bar per step)', async () => {+ const stepsQueryNoCompare: FunnelsQuery = {+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: { funnelVizType: FunnelVizType.Steps },+ }+ const insight: Partial<InsightModel> = {+ filters: { insight: InsightType.FUNNELS },+ result: funnelResult.result,+ }+ await expectLogic(logic, () => {+ logic.actions.updateQuerySource(stepsQueryNoCompare)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toFinishAllListeners()++ expect(logic.values.isComparedFunnel).toBe(false)+ const steps = logic.values.visibleStepsWithConversionMetrics+ expect(steps).toHaveLength(2)+ steps.forEach((step) => {+ expect(step.nested_breakdown).toHaveLength(1)+ expect(step.nested_breakdown?.[0].compare_label).toBeUndefined()+ })+ })+ })})diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.tsindex 1d74d8013e4d..ff818a405162 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts@@ -44,13 +44,16 @@ import type { funnelDataLogicType } from './funnelDataLogicType'import {TIME_INTERVAL_BOUNDS,aggregateBreakdownResult,+ aggregateFunnelCompareResult,aggregationLabelForHogQL,+ dimPreviousPeriodColor,flattenedStepsByBreakdown,getIncompleteConversionWindowStartDate,getLastFilledStep,getReferenceStep,getVisibilityKey,isBreakdownFunnelResults,+ isFunnelStepsCompareResult,isFunnelWithEnoughSteps,isFunnelWithIncompleteDataWarehouseStep,stepsWithConversionMetrics,@@ -337,6 +340,7 @@ export const funnelDataLogic = kea<funnelDataLogicType>([s.breakdownFilter,s.results,s.isTimeToConvertFunnel,+ s.isStepsFunnel,],(insightData,@@ -344,7 +348,8 @@ export const funnelDataLogic = kea<funnelDataLogicType>([querySource,breakdownFilter,results,- isTimeToConvertFunnel+ isTimeToConvertFunnel,+ isStepsFunnel): FunnelStepWithNestedBreakdown[] => {if (!isFunnelsQueryOrLegacyFilter(insightData, querySource)) {return []@@ -353,6 +358,12 @@ export const funnelDataLogic = kea<funnelDataLogicType>([// we need to check wether results are an array, since isTimeToConvertFunnel can be false,// while still having "time-to-convert" results in insightDataif (!isTimeToConvertFunnel && Array.isArray(results) && results.length > 0) {+ // STEPS compare: the runner returns both periods' steps as a flat tagged list.+ // Reshape into one step per order with current+previous as nested bars. Trends+ // also tags rows with compare_label but renders via indexedSteps, so gate on STEPS.+ if (isStepsFunnel && isFunnelStepsCompareResult(results)) {+ return aggregateFunnelCompareResult(results)+ }if (isBreakdownFunnelResults(results)) {const breakdownProperty = breakdownFilter?.breakdowns? breakdownFilter?.breakdowns.map((b) => b.property).join('::')@@ -397,6 +408,15 @@ export const funnelDataLogic = kea<funnelDataLogicType>([}))},],+ // True when STEPS results carry compare-tagged nested bars (current + previous per step).+ // Compare reshapes the data to look like a 2-value breakdown, so the breakdown baseline /+ // visibility machinery must be bypassed for it.+ isComparedFunnel: [+ (s) => [s.steps],+ (steps): boolean =>+ Array.isArray(steps) &&+ steps.some((step) => step.nested_breakdown?.some((series) => series.compare_label != null)),+ ],stepsWithConversionMetrics: [(s) => [s.steps, s.funnelsFilter, s.querySource],(@@ -426,13 +446,19 @@ export const funnelDataLogic = kea<funnelDataLogicType>([s.funnelsFilter,s.disableFunnelBreakdownBaseline,s.breakdownSorting,+ s.isComparedFunnel,],(steps: FunnelStepWithConversionMetrics[],funnelsFilter: FunnelsFilter | null | undefined,disableBaseline: boolean,- breakdownSorting: string | undefined+ breakdownSorting: string | undefined,+ isComparedFunnel: boolean): FlattenedFunnelStepByBreakdown[] => {+ // Compare's current/previous bars are not breakdown values — no breakdown table.+ if (isComparedFunnel) {+ return []+ }const breakdowns = flattenedStepsByBreakdown(steps, funnelsFilter?.layout, disableBaseline, true)if (!breakdownSorting) {return breakdowns@@ -457,12 +483,18 @@ export const funnelDataLogic = kea<funnelDataLogicType>([],resultCustomizations: [(s) => [s.funnelsFilter], (funnelsFilter) => funnelsFilter?.resultCustomizations],visibleStepsWithConversionMetrics: [- (s) => [s.stepsWithConversionMetrics, s.flattenedBreakdowns, s.hiddenLegendBreakdowns],+ (s) => [s.stepsWithConversionMetrics, s.flattenedBreakdowns, s.hiddenLegendBreakdowns, s.isComparedFunnel],(steps: FunnelStepWithConversionMetrics[],flattenedBreakdowns: FlattenedFunnelStepByBreakdown[],- hiddenLegendBreakdowns: string[] | undefined+ hiddenLegendBreakdowns: string[] | undefined,+ isComparedFunnel: boolean): FunnelStepWithConversionMetrics[] => {+ // Compare already shaped nested_breakdown into [current, previous]; skip the+ // breakdown baseline-prepend / hidden-legend reordering, which assumes real breakdowns.+ if (isComparedFunnel) {+ return steps+ }const isOnlySeries = flattenedBreakdowns.length <= 1const baseLineSteps = flattenedBreakdowns.find((b) => b.isBaseline)@@ -756,7 +788,12 @@ export const funnelDataLogic = kea<funnelDataLogicType>([(getFunnelsColorToken) => {return (dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics) => {const [colorTheme, colorToken] = getFunnelsColorToken(dataset)- return colorTheme && colorToken ? getColorFromToken(colorTheme, colorToken) : '#000000'+ const color = colorTheme && colorToken ? getColorFromToken(colorTheme, colorToken) : '#000000'+ // Current/previous compare bars share a color token (no breakdown_value), so the+ // previous-period bar is dimmed here to distinguish it — same treatment as trends.+ return (dataset as FunnelStepWithConversionMetrics).compare_label === 'previous'+ ? dimPreviousPeriodColor(color)+ : color}},],diff --git a/frontend/src/scenes/funnels/funnelUtils.test.ts b/frontend/src/scenes/funnels/funnelUtils.test.tsindex b14d13200c9c..2a1ae0618b7e 100644--- a/frontend/src/scenes/funnels/funnelUtils.test.ts+++ b/frontend/src/scenes/funnels/funnelUtils.test.ts@@ -1,4 +1,5 @@import { dayjs } from 'lib/dayjs'+import { formatDateRange } from 'lib/utils/datetime'import { EventsNode, FunnelsQuery, NodeKind } from '~/queries/schema/schema-general'import {@@ -13,7 +14,9 @@ import {import {aggregateBreakdownResult,+ dimPreviousPeriodColor,EMPTY_BREAKDOWN_VALUES,+ funnelComparePeriodDateRange,getBreakdownStepValues,getClampedFunnelStepRange,getIncompleteConversionWindowStartDate,@@ -576,6 +579,70 @@ describe('stepsWithConversionMetrics', () => {expect(result[1].nested_breakdown![1].conversionRates.total).toBe(10 / 80)})+ it('compare mode — bars share one baseline so the previous bar reflects its volume', () => {+ // current 200->100, previous 150->60; nested_breakdown is [current, previous] per step.+ const makeCompareStep = (order: number, current: number, previous: number): FunnelStepWithNestedBreakdown =>+ makeNestedStep({+ count: current,+ order,+ nested_breakdown: [+ makeStep({ count: current, order, compare_label: 'current' }),+ makeStep({ count: previous, order, compare_label: 'previous' }),+ ],+ })+ const steps = [makeCompareStep(0, 200, 150), makeCompareStep(1, 100, 60)]+ const result = stepsWithConversionMetrics(steps, FunnelStepReference.total)++ // Baseline is the larger period's first step (200) — the previous first bar is no longer full height.+ expect(result[0].nested_breakdown![0].conversionRates.fromBasisStep).toBe(1) // 200/200+ expect(result[0].nested_breakdown![1].conversionRates.fromBasisStep).toBe(150 / 200)+ expect(result[1].nested_breakdown![0].conversionRates.fromBasisStep).toBe(100 / 200)+ expect(result[1].nested_breakdown![1].conversionRates.fromBasisStep).toBe(60 / 200)++ // Tooltip rates stay per-period.+ expect(result[0].nested_breakdown![1].conversionRates.total).toBe(1)+ expect(result[1].nested_breakdown![1].conversionRates.total).toBe(60 / 150)+ })++ it('compare mode — a larger previous period caps at full height while the current bar shrinks', () => {+ const steps = [+ makeNestedStep({+ count: 200,+ order: 0,+ nested_breakdown: [+ makeStep({ count: 200, order: 0, compare_label: 'current' }),+ makeStep({ count: 300, order: 0, compare_label: 'previous' }),+ ],+ }),+ ]+ const result = stepsWithConversionMetrics(steps, FunnelStepReference.total)++ // Baseline is max(200, 300) = 300, so the tallest bar is 100% and nothing overflows.+ expect(result[0].nested_breakdown![0].conversionRates.fromBasisStep).toBe(200 / 300)+ expect(result[0].nested_breakdown![1].conversionRates.fromBasisStep).toBe(1)+ })++ it('compare mode — empty previous period → nested total is 0, not NaN', () => {+ // The previous period is zeroed (backend skeleton), so its first-step count is 0.+ const makeCompareStep = (order: number, current: number, previous: number): FunnelStepWithNestedBreakdown =>+ makeNestedStep({+ count: current,+ order,+ nested_breakdown: [+ makeStep({ count: current, order, compare_label: 'current' }),+ makeStep({ count: previous, order, compare_label: 'previous' }),+ ],+ })+ const steps = [makeCompareStep(0, 200, 0), makeCompareStep(1, 100, 0)]+ const result = stepsWithConversionMetrics(steps, FunnelStepReference.total)++ // The empty previous series divides 0/0 — guarded to 0 so the tooltip shows 0%, not NaN%.+ expect(result[0].nested_breakdown![1].conversionRates.total).toBe(0)+ expect(result[1].nested_breakdown![1].conversionRates.total).toBe(0)+ expect(Number.isNaN(result[0].nested_breakdown![1].conversionRates.total)).toBe(false)+ expect(Number.isNaN(result[1].nested_breakdown![1].conversionRates.total)).toBe(false)+ })+it('nested breakdowns with outlier detection — divergent breakdown gets significant: true', () => {// Create 5 breakdowns where one is an outlierconst breakdownCounts = [@@ -860,3 +927,41 @@ describe('hasBreakdown', () => {expect(hasBreakdown(breakdownValue as Parameters<typeof hasBreakdown>[0])).toBe(expected)})})++describe('funnelComparePeriodDateRange', () => {+ const resolved = { date_from: '2021-06-07', date_to: '2021-06-13' }++ it('returns the current window for the current period', () => {+ expect(funnelComparePeriodDateRange('current', resolved)).toBe(+ formatDateRange(dayjs('2021-06-07'), dayjs('2021-06-13'))+ )+ })++ it('returns the preceding equal-length window for the default previous period', () => {+ expect(funnelComparePeriodDateRange('previous', resolved)).toBe(+ formatDateRange(dayjs('2021-05-31'), dayjs('2021-06-06'))+ )+ })++ it('shifts the previous window by a custom compare_to offset', () => {+ expect(funnelComparePeriodDateRange('previous', resolved, '-30d')).toBe(+ formatDateRange(dayjs('2021-05-08'), dayjs('2021-05-14'))+ )+ })++ it('returns null when the resolved range is missing', () => {+ expect(funnelComparePeriodDateRange('current', null)).toBeNull()+ expect(funnelComparePeriodDateRange('previous', { date_from: null, date_to: null })).toBeNull()+ })+})++describe('dimPreviousPeriodColor', () => {+ it('dims a 6-digit hex to 50% opacity (matching the trends previous-period treatment)', () => {+ expect(dimPreviousPeriodColor('#1d4aff')).toBe('#1d4aff80')+ })++ it('leaves colors that already carry alpha or a non-hex format unchanged', () => {+ expect(dimPreviousPeriodColor('#1d4aff80')).toBe('#1d4aff80')+ expect(dimPreviousPeriodColor('rgba(29, 74, 255, 0.5)')).toBe('rgba(29, 74, 255, 0.5)')+ })+})diff --git a/frontend/src/scenes/funnels/funnelUtils.tsx b/frontend/src/scenes/funnels/funnelUtils.tsxindex 9a8f035f6310..4b4791dc3cf5 100644--- a/frontend/src/scenes/funnels/funnelUtils.tsx+++ b/frontend/src/scenes/funnels/funnelUtils.tsx@@ -1,5 +1,6 @@import { FunnelLayout } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import { formatDateRange } from 'lib/utils/datetime'import { humanFriendlyDuration } from 'lib/utils/durations'import { autoCaptureEventToDescription } from 'lib/utils/events'import { clamp, percentage } from 'lib/utils/numbers'@@ -176,6 +177,90 @@ export function isBreakdownFunnelResults(results: FunnelResultType): results isreturn Array.isArray(results) && (results.length === 0 || Array.isArray(results[0]))}+/** Whether a STEPS result is a compare-tagged flat list (both periods' steps tagged with+ * `compare_label`, no breakdown). Breakdown compare lands in a later slice. */+export function isFunnelStepsCompareResult(results: FunnelResultType): results is FunnelStep[] {+ return (+ Array.isArray(results) &&+ results.length > 0 &&+ !Array.isArray(results[0]) &&+ (results as FunnelStep[]).some((step) => step.compare_label != null)+ )+}++const COMPARE_TO_UNIT: Record<string, dayjs.ManipulateType> = {+ h: 'hour',+ d: 'day',+ w: 'week',+ m: 'month',+ y: 'year',+}++function parseCompareToOffset(+ compareTo: string | null | undefined+): { amount: number; unit: dayjs.ManipulateType } | null {+ const match = compareTo?.match(/^-?(\d+)([hdwmy])$/)+ return match ? { amount: parseInt(match[1], 10), unit: COMPARE_TO_UNIT[match[2]] } : null+}++/**+ * Human-friendly date range for a funnel compare period, derived from the resolved current range+ * plus the compare offset — the frontend mirror of the backend's previous-period shifting (the+ * merged response only carries the current period's resolved range). Returns null when the range+ * is unavailable.+ */+export function funnelComparePeriodDateRange(+ compareLabel: 'current' | 'previous',+ resolvedDateRange: { date_from?: string | null; date_to?: string | null } | null | undefined,+ compareTo?: string | null+): string | null {+ const from = resolvedDateRange?.date_from ? dayjs(resolvedDateRange.date_from) : null+ const to = resolvedDateRange?.date_to ? dayjs(resolvedDateRange.date_to) : null+ if (!from || !to || !from.isValid() || !to.isValid()) {+ return null+ }+ if (compareLabel === 'current') {+ return formatDateRange(from, to)+ }+ const offset = parseCompareToOffset(compareTo)+ if (offset) {+ return formatDateRange(from.subtract(offset.amount, offset.unit), to.subtract(offset.amount, offset.unit))+ }+ // Default previous period: the equal-length window ending the day before the current window.+ const previousTo = from.subtract(1, 'day')+ const previousFrom = previousTo.subtract(to.diff(from, 'day'), 'day')+ return formatDateRange(previousFrom, previousTo)+}++/** Desaturate a series color to the "previous period" treatment (50% opacity), matching the+ * dimmed previous-period series in trends (`LineGraph.processDataset`). */+export function dimPreviousPeriodColor(color: string): string {+ // Only plain 6-digit hex gets an alpha suffix; anything already carrying alpha or a+ // non-hex format is left untouched.+ return /^#[0-9a-fA-F]{6}$/.test(color) ? `${color}80` : color+}++/**+ * Reshape a compare-tagged flat STEPS result into one step per order, each carrying a+ * `nested_breakdown` of `[currentSeries, previousSeries]`. This reuses the breakdown rendering+ * path (`StepBars` draws one bar per `nested_breakdown` entry) to draw two grouped bars per step.+ * The series keep their `compare_label` so the previous bar can be desaturated and the tooltip+ * labelled by period.+ */+export function aggregateFunnelCompareResult(results: FunnelStep[]): FunnelStepWithNestedBreakdown[] {+ const current = results.filter((step) => step.compare_label === 'current').sort((a, b) => a.order - b.order)+ const previous = results.filter((step) => step.compare_label === 'previous').sort((a, b) => a.order - b.order)++ return current.map((step, i) => ({+ ...step,+ // Both bars keep the step's `order` so they share the step's color (funnel bars are colored+ // per step); the previous bar is then dimmed via its `compare_label`. The array position+ // (current first, previous second) is what `stepsWithConversionMetrics` uses for per-period+ // conversion rates, and `StepBars` keys the bars on `compare_label`.+ nested_breakdown: [{ ...step }, ...(previous[i] ? [{ ...previous[i] }] : [])],+ }))+}+/** Breakdown parameter could be a string (property breakdown) or object/number (list of cohort ids). */export function hasBreakdownFilterParameter(breakdown: BreakdownKeyType | undefined,@@ -300,6 +385,13 @@ export function stepsWithConversionMetrics(stepReference: FunnelStepReference,optionalSteps: number[] = []): FunnelStepWithConversionMetrics[] {+ const compareBars = steps[0]?.nested_breakdown+ const isCompare = compareBars?.some((b) => b.compare_label != null) ?? false+ // Compare bars share one baseline (the larger period's first step) so both periods sit on a+ // common scale: the previous bar shows its real volume instead of always starting full height,+ // and the tallest bar never exceeds the column.+ const compareBasisCount = isCompare ? Math.max(...(compareBars?.map((b) => b.count) ?? [0])) : 0+let lastNonOptionalStep = 0const stepsWithConversionMetrics = steps.map((step, i) => {// Use lastNonOptionalStep for previousCount calculation (this is the last non-optional step we've seen)@@ -316,17 +408,20 @@ export function stepsWithConversionMetrics(const nestedDroppedOffFromPrevious = Math.max(previousBreakdownCount - breakdown.count, 0)const conversionRates = {fromPrevious: previousBreakdownCount === 0 ? 0 : breakdown.count / previousBreakdownCount,- total: breakdown.count / firstBreakdownCount,+ total: firstBreakdownCount === 0 ? 0 : breakdown.count / firstBreakdownCount,}return {...breakdown,droppedOffFromPrevious: nestedDroppedOffFromPrevious,conversionRates: {...conversionRates,- fromBasisStep:- stepReference === FunnelStepReference.total- ? conversionRates.total- : conversionRates.fromPrevious,+ fromBasisStep: isCompare+ ? compareBasisCount === 0+ ? 0+ : breakdown.count / compareBasisCount+ : stepReference === FunnelStepReference.total+ ? conversionRates.total+ : conversionRates.fromPrevious,},}})diff --git a/frontend/src/scenes/insights/Funnels.stories.tsx b/frontend/src/scenes/insights/Funnels.stories.tsxindex dd282c4ea1c7..65975e7b3ae5 100644--- a/frontend/src/scenes/insights/Funnels.stories.tsx+++ b/frontend/src/scenes/insights/Funnels.stories.tsx@@ -73,6 +73,18 @@ FunnelLeftToRightEdit.parameters = {testOptions: { waitForSelector: ['[data-attr=funnel-steps-bar-chart] canvas[role="img"]', '.PayGateMini'] },}+// Steps viz with "Compare to previous" on: each step renders a current and a (desaturated) previous+// bar. The funnels-compare flag gates the toggle — without it the compare data degrades to a single+// bar per step and the snapshot is wrong.+export const FunnelLeftToRightCompare: Story = createInsightStory(+ require('../../mocks/fixtures/api/projects/team_id/insights/funnelLeftToRightCompare.json')+)+FunnelLeftToRightCompare.parameters = {+ featureFlags: [FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE],+ testOptions: { waitForSelector: ['[data-attr=funnel-steps-bar-chart] canvas[role="img"]', '.PayGateMini'] },+}+FunnelLeftToRightCompare.play = waitForFunnelToStabilize+export const FunnelLeftToRightBreakdown: Story = createInsightStory(require('../../mocks/fixtures/api/projects/team_id/insights/funnelLeftToRightBreakdown.json'))diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.tsindex 8380efec28a8..1c979968f39e 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts@@ -1,6 +1,6 @@import { expectLogic } from 'kea-test-utils'-import { FunnelLayout } from 'lib/constants'+import { FEATURE_FLAGS, FunnelLayout } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { funnelInvalidExclusionError, funnelResult } from 'scenes/funnels/__mocks__/funnelDataLogicMocks'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'@@ -12,6 +12,7 @@ import { initKeaTests } from '~/test/init'import {BaseMathType,ChartDisplayType,+ FunnelVizType,InsightModel,InsightShortId,InsightType,@@ -926,4 +927,37 @@ describe('insightVizDataLogic', () => {}).toMatchValues({ isBreakdownSeries: true })})})++ describe('supportsCompare', () => {+ const setFunnelVizType = (funnelVizType: FunnelVizType): void => {+ builtInsightVizDataLogic.actions.updateQuerySource({+ ...funnelsQueryDefault,+ funnelsFilter: { ...funnelsQueryDefault.funnelsFilter, funnelVizType },+ } as FunnelsQuery)+ }++ it.each([+ [FunnelVizType.Steps, true],+ [FunnelVizType.Trends, true],+ [FunnelVizType.TimeToConvert, true],+ // FLOW is excluded — the backend ignores compare for it.+ [FunnelVizType.Flow, false],+ ] as [FunnelVizType, boolean][])('flag on, %s viz → %s', (funnelVizType, expected) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]: true,+ })+ setFunnelVizType(funnelVizType)++ expect(builtInsightVizDataLogic.values.supportsCompare).toBe(expected)+ })++ it('flag off → compare unsupported even for steps viz', () => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]: false,+ })+ setFunnelVizType(FunnelVizType.Steps)++ expect(builtInsightVizDataLogic.values.supportsCompare).toBe(false)+ })+ })})diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex f5191d41c958..8c1c51ab654c 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -230,14 +230,10 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([if (isTrendsQuery(q) || isStickinessQuery(q) || isWebAnalyticsInsightQuery(q)) {return display !== ChartDisplayType.WorldMap && display !== ChartDisplayType.CalendarHeatmap}- // Funnel compare ships behind a flag, for the TRENDS and TIME_TO_CONVERT viz modes.- if (- isFunnelsQuery(q) &&- !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE] &&- (q.funnelsFilter?.funnelVizType === FunnelVizType.Trends ||- q.funnelsFilter?.funnelVizType === FunnelVizType.TimeToConvert)- ) {- return true+ // Funnel compare ships behind a flag, for the STEPS, TRENDS and TIME_TO_CONVERT viz+ // modes. FLOW is excluded — the backend ignores compare for it (mirrors `_is_compare_active`).+ if (isFunnelsQuery(q) && !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]) {+ return (q.funnelsFilter?.funnelVizType ?? FunnelVizType.Steps) !== FunnelVizType.Flow}return false},diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 073fadb650ff..aa871985a557 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -3355,6 +3355,9 @@ export interface FunnelStep {data?: number[]days?: string[]+ /** Set by the funnel compare orchestrator to tag which period a step belongs to. */+ compare_label?: 'current' | 'previous'+/** Url that you can GET to retrieve the people that converted in this step */converted_people_url: stringdiff --git a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py b/posthog/hogql_queries/insights/funnels/funnels_query_runner.pyindex 3f974341cd8e..05e7b0b48df9 100644--- a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnels_query_runner.py@@ -254,11 +254,27 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):])+ current_results = current_response.results or []+ previous_results = previous_response.results or []++ # STEPS returns an empty list for a period with no matching events. Backfill it with a+ # zeroed step skeleton (cloned from the populated period) so the grouped-bar chart still+ # draws a bar per step on both sides instead of collapsing to a single bar. TRENDS and+ # TIME_TO_CONVERT always return a populated skeleton, so this only fires for STEPS.+ # Breakdown STEPS (list-of-lists) is a later slice; the `isinstance(dict)` guard skips it.+ if self.context.funnelsFilter.funnelVizType == FunnelVizType.STEPS:+ populated = current_results or previous_results+ is_flat_steps = bool(populated) and all(isinstance(row, dict) for row in populated)+ if is_flat_steps and not previous_results:+ previous_results = self._zeroed_steps_skeleton(current_results)+ elif is_flat_steps and not current_results:+ current_results = self._zeroed_steps_skeleton(previous_results)+merged_results = []- for row in current_response.results or []:+ for row in current_results:row["compare_label"] = "current"merged_results.append(row)- for row in previous_response.results or []:+ for row in previous_results:row["compare_label"] = "previous"merged_results.append(row)@@ -275,6 +291,23 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):),)+ def _zeroed_steps_skeleton(self, steps: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Clone a flat list of step dicts with all counts and conversion times zeroed.++ Used for the empty side of a STEPS compare so it mirrors the populated period's step+ names/orders/types while reporting zero conversions.+ """+ return [+ {+ **step,+ "count": 0,+ "people": [],+ "average_conversion_time": None,+ "median_conversion_time": None,+ }+ for step in steps+ ]+def _calculate_compare_time_to_convert(self) -> FunnelsQueryResponse:"""Compare for the TIME_TO_CONVERT viz: both histograms must share an x-axis.@@ -392,8 +425,12 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):compare_filter = self.query.compareFilterif compare_filter is None or not compare_filter.compare:return False- # Compare is supported for the TRENDS and TIME_TO_CONVERT viz modes. STEPS lands in a later slice.- if self.context.funnelsFilter.funnelVizType not in (FunnelVizType.TRENDS, FunnelVizType.TIME_TO_CONVERT):+ # Compare is supported for the STEPS, TRENDS and TIME_TO_CONVERT viz modes. FLOW is excluded.+ if self.context.funnelsFilter.funnelVizType not in (+ FunnelVizType.STEPS,+ FunnelVizType.TRENDS,+ FunnelVizType.TIME_TO_CONVERT,+ ):return Falsereturn self._team_flag_funnels_compare()diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel.py b/posthog/hogql_queries/insights/funnels/test/test_funnel.pyindex bb0b05440b95..9b8c9611b01a 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel.py@@ -1,5 +1,6 @@import uuidfrom datetime import datetime+from typing import Optionalfrom freezegun import freeze_timefrom posthog.test.base import (@@ -12,6 +13,7 @@ from posthog.test.base import (create_person_id_override_by_distinct_id,snapshot_clickhouse_queries,)+from unittest.mock import patchfrom django.test import override_settings@@ -24,6 +26,7 @@ from posthog.schema import (BaseMathType,BreakdownFilter,BreakdownType,+ CompareFilter,DateRange,EventPropertyFilter,EventsNode,@@ -6000,3 +6003,122 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):bing = groups_by_breakdown[("bing.com",)]assert bing[0]["count"] == 1assert bing[1]["count"] == 1+++@override_settings(IN_UNIT_TESTING=True)+class TestFunnelStepsCompareUDF(ClickhouseTestMixin, APIBaseTest):+ """Compare-to-previous on the default funnel STEPS (bar) viz. Reuses the tagged-row contract+ established for TRENDS in slice 1 — each step dict in `results` is tagged with `compare_label`."""++ 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="steps",+ 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_steps(self, _feature_enabled):+ # Current window 2021-06-07 .. 2021-06-13; default previous is the prior 7-day window+ # (2021-05-31 .. 2021-06-06). One full 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++ # No breakdown: results is a flat list of step dicts. With compare on, both periods'+ # steps are present and tagged. Current steps come first, then previous.+ current_steps = [row for row in results if row["compare_label"] == "current"]+ previous_steps = [row for row in results if row["compare_label"] == "previous"]++ self.assertEqual([s["order"] for s in current_steps], [0, 1])+ self.assertEqual([s["order"] for s in previous_steps], [0, 1])++ # One person completed both steps in each period.+ self.assertEqual([s["count"] for s in current_steps], [1, 1])+ self.assertEqual([s["count"] for s in previous_steps], [1, 1])++ @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+ # (2021-05-08 .. 2021-05-14), regardless of window length. Two conversions land there; a+ # third lands in the *default* previous window (2021-05-31 .. 2021-06-06), which `-30d`+ # must exclude. So the previous count is 2, not 1 — proving the offset shifted the window.+ journeys_for(+ {+ "current_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 11)},+ ],+ "offset_user_a": [+ {"event": "step one", "timestamp": datetime(2021, 5, 8, 10)},+ {"event": "step two", "timestamp": datetime(2021, 5, 8, 11)},+ ],+ "offset_user_b": [+ {"event": "step one", "timestamp": datetime(2021, 5, 10, 10)},+ {"event": "step two", "timestamp": datetime(2021, 5, 10, 11)},+ ],+ "noise_user": [+ # In the default previous window but NOT 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_steps = [row for row in results if row["compare_label"] == "previous"]+ self.assertEqual([s["count"] for s in previous_steps], [2, 2])++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_with_empty_previous_period(self, _feature_enabled):+ # Only the current period has events. The previous side must still return a tagged step+ # skeleton (zeroed) so the chart can render two bars per step — a missing previous side+ # would leave steps with a single bar and break the grouped-bar layout.+ 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++ current_steps = [row for row in results if row["compare_label"] == "current"]+ previous_steps = [row for row in results if row["compare_label"] == "previous"]++ self.assertEqual([s["count"] for s in current_steps], [1, 1])+ # Skeleton intact: same steps, zeroed counts.+ self.assertEqual([s["order"] for s in previous_steps], [0, 1])+ self.assertEqual([s["count"] for s in previous_steps], [0, 0])+ self.assertEqual([s["name"] for s in previous_steps], ["step one", "step two"])