: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 time-to-convert viz on shared bins (#60157)
Thomas Obermüller347965492f70
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f89a82e69f0e..51db5b9feae7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2212,6 +2212,10 @@ snapshots:hash: v1.k794b7964.0c70fac4deda9be64c8b0c0d06eb0149e9d11176c31ab5861f6657fa80714836.YqZL0Grf9CN71TbXgR_pGO23EfnukP5X-Doi0-Xy48Ainsights-funnelcorrelationtable--default--light:hash: v1.k794b7964.3d6cf3fd19bf7fd2b7f9d822fcd66b7d10557a26bf4bd03b01f32fcc794f880f.jKBKmAVKsMdV2WrUXJtct3l-1dyvr6mOQP_ztF84bk0+ insights-funnelhistogramchart--compare--dark:+ hash: v1.k794b7964.243c25013f1c49bd32748e1942907e66a5167645e28f2e4c0cc5afced3c5bba9.A3DQuQNSU2omhbPK9xJY5JUW-d6pbpWCul3DebkL_Ow+ insights-funnelhistogramchart--compare--light:+ hash: v1.k794b7964.283dab157709f3a7857d3385fd5cbdb5c603a84adc73672c0f2d403793b10193.TkzfWpRiJQlFpynFeQM1CjcO1TBqsDQa1N1V6u5QJxQinsights-funnelhistogramchart--default--dark:hash: v1.k794b7964.90451510061b45383bf84c93d7e9b129a40e4e3e219073cf4ff4b3756ffd169c.0bIz7UkRlCxTeeoUjlJAwRFd9XjTzSvukUdcv3qVcX0insights-funnelhistogramchart--default--light:diff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvertCompare.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvertCompare.jsonnew file mode 100644index 000000000000..567928dd98e5--- /dev/null+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvertCompare.json@@ -0,0 +1,111 @@+{+ "id": 52,+ "short_id": "jEAIVJnE",+ "name": null,+ "derived_name": "Pageview → Pageview → Pageview user conversion time (compare)",+ "filters": {},+ "filters_hash": "cache_139d6f1c62b5d616d3356cc63a068135",+ "order": null,+ "deleted": false,+ "dashboard": null,+ "layouts": {},+ "color": null,+ "last_refresh": null,+ "refreshing": false,+ "result": [+ {+ "compare_label": "current",+ "bins": [+ [0, 4562],+ [14435, 19],+ [28870, 12],+ [43305, 9],+ [57740, 3],+ [72175, 5],+ [86610, 4],+ [101045, 3],+ [115480, 6]+ ],+ "average_conversion_time": 1060.7+ },+ {+ "compare_label": "previous",+ "bins": [+ [0, 3120],+ [14435, 31],+ [28870, 8],+ [43305, 14],+ [57740, 6],+ [72175, 2],+ [86610, 7],+ [101045, 1],+ [115480, 3]+ ],+ "average_conversion_time": 1340.2+ }+ ],+ "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:47:31.202393Z",+ "tags": [],+ "favorited": false,+ "saved": true,+ "last_modified_at": "2022-03-15T21:47:31.193013Z",+ "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": "time_to_convert",+ "layout": "horizontal"+ },+ "compareFilter": {+ "compare": true+ },+ "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 4de5815c34f5..cac8ce750c80 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx@@ -124,7 +124,7 @@ export function InsightDisplayConfig(): JSX.Element {display !== ChartDisplayType.BoxPlot) ||isStickiness ||isWebAnalyticsInsightQuery(querySource) ||- (funnelsCompareEnabled && isTrendsFunnel)+ (funnelsCompareEnabled && (isTrendsFunnel || isTimeToConvertFunnel))const showInterval =isTrendsFunnel ||isLifecycle ||diff --git a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.tsindex 363b39fca061..3ea14103763b 100644--- a/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts+++ b/frontend/src/scenes/funnels/__mocks__/funnelDataLogicMocks.ts@@ -305,6 +305,36 @@ export const funnelResultTimeToConvertWithoutConversions: FunnelAPIResponse = {is_cached: false,}+// 1. Add step "Pageview"+// 2. Select graph type "Time to convert"+// 3. Toggle "Compare to previous"+// Both periods carry the same bin boundaries (shared bins); only the counts differ.+export const funnelResultTimeToConvertCompare: FunnelAPIResponse = {+ result: [+ {+ compare_label: 'current',+ bins: [+ [4.0, 74],+ [73591.0, 24],+ [147178.0, 10],+ ],+ average_conversion_time: 86456.76,+ },+ {+ compare_label: 'previous',+ bins: [+ [4.0, 52],+ [73591.0, 31],+ [147178.0, 17],+ ],+ average_conversion_time: 91230.5,+ },+ ] as any,+ timezone: 'UTC',+ last_refresh: '2023-02-22T17:32:24.245364Z',+ is_cached: false,+}+// 1. Add step "Pageview"// 2. Select graph type "Trends"export const funnelResultTrends = {diff --git a/frontend/src/scenes/funnels/funnelDataLogic.test.ts b/frontend/src/scenes/funnels/funnelDataLogic.test.tsindex 4e488b1561bf..d63b87bdb9d1 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.test.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.test.ts@@ -12,6 +12,7 @@ import { FunnelConversionWindowTimeUnit, FunnelVizType, InsightLogicProps, Insigimport {funnelResult,funnelResultTimeToConvert,+ funnelResultTimeToConvertCompare,funnelResultTimeToConvertWithoutConversions,funnelResultTrends,funnelResultTrendsCompare,@@ -941,6 +942,64 @@ describe('funnelDataLogic', () => {],})})++ it('splits the current and previous periods when comparing', async () => {+ const query: FunnelsQuery = {+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: {+ funnelVizType: FunnelVizType.TimeToConvert,+ },+ compareFilter: { compare: true },+ }+ const insight: Partial<InsightModel> = {+ filters: {+ insight: InsightType.FUNNELS,+ },+ result: funnelResultTimeToConvertCompare.result,+ }++ await expectLogic(logic, () => {+ logic.actions.updateQuerySource(query)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toMatchValues({+ // Current period: the 'current'-tagged bins, on the shared boundaries.+ histogramGraphData: [+ expect.objectContaining({ bin0: 4, count: 74 }),+ expect.objectContaining({ bin0: 73591, count: 24 }),+ expect.objectContaining({ bin0: 147178, count: 10 }),+ ],+ // Previous period: the 'previous'-tagged bins, on the same boundaries.+ histogramGraphDataPrevious: [+ expect.objectContaining({ bin0: 4, count: 52 }),+ expect.objectContaining({ bin0: 73591, count: 31 }),+ expect.objectContaining({ bin0: 147178, count: 17 }),+ ],+ })+ })++ it('has no previous-period data when not comparing', async () => {+ const query: FunnelsQuery = {+ kind: NodeKind.FunnelsQuery,+ series: [],+ funnelsFilter: {+ funnelVizType: FunnelVizType.TimeToConvert,+ },+ }+ const insight: Partial<InsightModel> = {+ filters: {+ insight: InsightType.FUNNELS,+ },+ result: funnelResultTimeToConvert.result,+ }++ await expectLogic(logic, () => {+ logic.actions.updateQuerySource(query)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toMatchValues({+ histogramGraphDataPrevious: null,+ })+ })})})diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.tsindex da165093a073..e335d6c07a87 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts@@ -58,6 +58,37 @@ import {const DEFAULT_FUNNEL_LOGIC_KEY = 'default_funnel_key'+/** A time-to-convert bins payload tagged with its compare period (present only when comparing). */+type TimeToConvertCompareBins = FunnelsTimeConversionBins & { compare_label?: 'current' | 'previous' }++/** Maps a time-to-convert bins payload onto histogram data. Returns null for too-few bins, [] when+ * nobody converted. Shared between the current and previous (compare) periods. */+function timeConversionBinsToHistogramData(+ timeConversionResults: FunnelsTimeConversionBins | null+): HistogramGraphDatum[] | null {+ if ((timeConversionResults?.bins?.length ?? 0) < 2) {+ return null // There are no results+ }++ const totalCount = sum(timeConversionResults!.bins.map(([, count]) => count))+ if (totalCount === 0) {+ return [] // Nobody has converted in the time period+ }++ const binSize = timeConversionResults!.bins[1][0] - timeConversionResults!.bins[0][0]+ return timeConversionResults!.bins.map(([id, count]: [id: number, count: number]) => {+ const value = Math.max(0, id)+ const percent = count / totalCount+ return {+ id: value,+ bin0: value,+ bin1: value + binSize,+ count,+ label: percent === 0 ? '' : percentage(percent, 1, true),+ }+ })+}+function getStepMetric(step: FunnelStepWithConversionMetrics | undefined, metric: string): number {if (!step) {return 0@@ -473,37 +504,43 @@ export const funnelDataLogic = kea<funnelDataLogicType>([timeConversionResults: [(s) => [s.results, s.funnelsFilter],(results, funnelsFilter): FunnelsTimeConversionBins | null => {- return funnelsFilter?.funnelVizType === FunnelVizType.TimeToConvert- ? (results as FunnelsTimeConversionBins)- : null+ if (funnelsFilter?.funnelVizType !== FunnelVizType.TimeToConvert) {+ return null+ }+ // Compare returns a two-element list tagged with compare_label; take the current period.+ if (Array.isArray(results)) {+ return (+ (results as unknown as TimeToConvertCompareBins[]).find(+ (row) => row.compare_label === 'current'+ ) ?? null+ )+ }+ return results as FunnelsTimeConversionBins},],- histogramGraphData: [- (s) => [s.timeConversionResults],- (timeConversionResults: FunnelsTimeConversionBins): HistogramGraphDatum[] | null => {- if ((timeConversionResults?.bins?.length ?? 0) < 2) {- return null // There are no results- }-- const totalCount = sum(timeConversionResults.bins.map(([, count]) => count))- if (totalCount === 0) {- return [] // Nobody has converted in the time period+ timeConversionResultsPrevious: [+ (s) => [s.results, s.funnelsFilter],+ (results, funnelsFilter): FunnelsTimeConversionBins | null => {+ if (funnelsFilter?.funnelVizType !== FunnelVizType.TimeToConvert || !Array.isArray(results)) {+ return null}-- const binSize = timeConversionResults.bins[1][0] - timeConversionResults.bins[0][0]- return timeConversionResults.bins.map(([id, count]: [id: number, count: number]) => {- const value = Math.max(0, id)- const percent = totalCount === 0 ? 0 : count / totalCount- return {- id: value,- bin0: value,- bin1: value + binSize,- count,- label: percent === 0 ? '' : percentage(percent, 1, true),- }- })+ return (+ (results as unknown as TimeToConvertCompareBins[]).find(+ (row) => row.compare_label === 'previous'+ ) ?? null+ )},],+ histogramGraphData: [+ (s) => [s.timeConversionResults],+ (timeConversionResults): HistogramGraphDatum[] | null =>+ timeConversionBinsToHistogramData(timeConversionResults),+ ],+ histogramGraphDataPrevious: [+ (s) => [s.timeConversionResultsPrevious],+ (timeConversionResultsPrevious): HistogramGraphDatum[] | null =>+ timeConversionBinsToHistogramData(timeConversionResultsPrevious),+ ],hasFunnelResults: [(s) => [s.insightData, s.funnelsFilter, s.steps, s.histogramGraphData, s.querySource, s.stepNames],(insightData, funnelsFilter, steps, histogramGraphData, querySource, stepNames) => {diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 811c863f95b5..7635dedfb6dd 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -230,11 +230,12 @@ 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, and only for the TRENDS viz mode in slice 1.+ // 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.Trends ||+ q.funnelsFilter?.funnelVizType === FunnelVizType.TimeToConvert)) {return true}diff --git a/posthog/hogql_queries/insights/funnels/funnel_time_to_convert.py b/posthog/hogql_queries/insights/funnels/funnel_time_to_convert.pyindex 770f290ec8f5..b0f28cef8bdd 100644--- a/posthog/hogql_queries/insights/funnels/funnel_time_to_convert.py+++ b/posthog/hogql_queries/insights/funnels/funnel_time_to_convert.py@@ -28,65 +28,110 @@ class FunnelTimeToConvertUDF(FunnelBase):average_conversion_time=results[0][2],)- def get_query(self) -> ast.SelectQuery:+ def _from_to_steps(self) -> tuple[int, int]:query, funnelsFilter = self.context.query, self.context.funnelsFilter-# Conversion from which step should be calculatedfrom_step = funnelsFilter.funnelFromStep or 0# Conversion to which step should be calculatedto_step = funnelsFilter.funnelToStep or len(query.series) - 1- # Use custom bin_count if provided by user, otherwise infer an automatic one based on the number of samples- binCount = funnelsFilter.binCount- if binCount is not None:- # Custom count is clamped between 1 and 90- if binCount < 1:- binCount = 1- elif binCount > 90:- binCount = 90- bin_count_expression = f"""{binCount}"""- else:- # Auto count is clamped between 1 and 60- bin_count_expression = f"""toInt(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))))"""-if not (0 < to_step < len(query.series)):raise ValidationError(f"Filter parameter {FUNNEL_TO_STEP} can only be one of {', '.join(map(str, range(1, len(query.series))))} for time to convert!")+ return from_step, to_step+ def _conversion_timings_query(self) -> ast.SelectQuery:+ """The per-person conversion times (`timings` array) for the from→to step range."""+ from_step, to_step = self._from_to_steps()inner_select = self.funnel_order._inner_aggregation_query()+ return cast(+ ast.SelectQuery,+ parse_select(+ f"""+ SELECT+ groupArray(arraySum(arraySlice(timings, {from_step + 1}, {to_step - from_step}))) as timings+ FROM {{inner_select}}+ WHERE step_reached >= {to_step}""",+ {"inner_select": inner_select},+ ),+ )- timings = parse_select(- f"""- SELECT- groupArray(arraySum(arraySlice(timings, {from_step + 1}, {to_step - from_step}))) as timings,+ def get_bounds_query(self) -> ast.SelectQuery:+ """Sample count and min/max conversion time for this period — feeds the shared-bin computer."""+ return cast(+ ast.SelectQuery,+ parse_select(+ """+ SELECT+ length(timings) as sample_count,+ if(sample_count > 0, floor(arrayMin(timings)), 0) as min_timing,+ if(sample_count > 0, ceil(arrayMax(timings)), 0) as max_timing+ FROM {timings}""",+ {"timings": self._conversion_timings_query()},+ ),+ )++ def get_query(self, explicit_bins: list[int] | None = None) -> ast.SelectQuery:+ funnelsFilter = self.context.funnelsFilter+ timings_query = self._conversion_timings_query()++ if explicit_bins is not None:+ # Compare passes shared boundaries so both periods land on the same x-axis. Derive the+ # equal-width parameters from them and skip the per-period min/max inference below.+ bin_count = len(explicit_bins) - 1+ min_timing = explicit_bins[0]+ bin_width = explicit_bins[1] - explicit_bins[0] if bin_count > 0 else 60+ bin_setup = f"""+ {bin_count} as bin_count,+ {min_timing} as min_timing,+ {bin_width} as bin_width_seconds,"""+ else:+ # Use custom bin_count if provided by user, otherwise infer one from the number of samples+ binCount = funnelsFilter.binCount+ if binCount is not None:+ # Custom count is clamped between 1 and 90+ if binCount < 1:+ binCount = 1+ elif binCount > 90:+ binCount = 90+ bin_count_expression = f"""{binCount}"""+ else:+ # Auto count is clamped between 1 and 60+ bin_count_expression = f"""toInt(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))))"""+ bin_setup = f"""{bin_count_expression} as bin_count,floor(arrayMin(timings)) as min_timing,ceil(arrayMax(timings)) as max_timing,ceil((max_timing - min_timing) / bin_count) as bin_width_seconds_raw,- if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds,+ if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds,"""++ # nosemgrep: hogql-fstring-audit (interpolated values are internal ints; {{timings}} is a HogQL placeholder)+ bins = parse_select(+ f"""+ SELECT+ timings,+ {bin_setup}arrayMap(n -> toInt(round(min_timing + n * bin_width_seconds)), range(0, bin_count + 1)) as buckets,arrayMap(timing -> toInt(floor((timing - min_timing) / bin_width_seconds)), timings) as indices,arrayMap(x -> countEqual(indices, x-1), range(1, bin_count + 2)) as counts- FROM {{inner_select}}- WHERE step_reached >= {to_step}""",- {"inner_select": inner_select},+ FROM {{timings}}""",+ {"timings": timings_query},)return cast(ast.SelectQuery,- # nosemgrep: hogql-fstring-audit (only HogQL placeholder {{timings}}, no Python interpolation)parse_select(- f"""+ """SELECTbin_from_seconds,person_count,arrayAvg(timings) as averageConversionTime- FROM {{timings}}+ FROM {bins}ARRAY JOINcounts as person_count,buckets as bin_from_seconds""",- {"timings": timings},+ {"bins": bins},),)diff --git a/posthog/hogql_queries/insights/funnels/funnel_time_to_convert_bins.py b/posthog/hogql_queries/insights/funnels/funnel_time_to_convert_bins.pynew file mode 100644index 000000000000..ddfde53a8ef6--- /dev/null+++ b/posthog/hogql_queries/insights/funnels/funnel_time_to_convert_bins.py@@ -0,0 +1,42 @@+from dataclasses import dataclass+from math import ceil, floor+++@dataclass(frozen=True)+class ConversionTimeRange:+ """Observed conversion-time summary for a single period."""++ min_timing: float+ max_timing: float+ sample_count: int+++def compute_shared_bin_boundaries(+ current: ConversionTimeRange | None,+ previous: ConversionTimeRange | None,+ bin_count_override: int | None = None,+) -> list[int]:+ """Bin boundaries shared by both compare periods, so their histograms share an x-axis.++ Mirrors the bin math in ``FunnelTimeToConvertUDF.get_query`` but over the *union* of the two+ periods' observed conversion times instead of a single period's. Returns the bucket lower+ bounds (``bin_count + 1`` values); an empty list means neither period had any conversions.+ """+ ranges = [r for r in (current, previous) if r is not None and r.sample_count > 0]+ if not ranges:+ return []++ min_timing = floor(min(r.min_timing for r in ranges))+ max_timing = ceil(max(r.max_timing for r in ranges))+ total_samples = sum(r.sample_count for r in ranges)++ if bin_count_override is not None:+ bin_count = min(90, max(1, bin_count_override))+ else:+ # round before ceil so perfect cubes (e.g. 27 -> 3) don't tip over on float error.+ bin_count = min(60, max(1, ceil(round(total_samples ** (1 / 3), 9))))++ bin_width_raw = ceil((max_timing - min_timing) / bin_count)+ bin_width = bin_width_raw if bin_width_raw > 0 else 60++ return [round(min_timing + n * bin_width) for n in range(bin_count + 1)]diff --git a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py b/posthog/hogql_queries/insights/funnels/funnels_query_runner.pyindex 158458b75db9..3f974341cd8e 100644--- a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnels_query_runner.py@@ -1,8 +1,8 @@import threading-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom datetime import datetime, timedeltafrom math import ceil-from typing import Any, Optional+from typing import Any, Optional, TypeVar, castfrom django.conf import settings@@ -14,6 +14,7 @@ from posthog.schema import (DateRange,FunnelsQuery,FunnelsQueryResponse,+ FunnelTimeToConvertResults,FunnelVizType,HogQLQueryModifiers,ResolvedDateRangeResponse,@@ -31,6 +32,10 @@ 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+from posthog.hogql_queries.insights.funnels.funnel_time_to_convert_bins import (+ ConversionTimeRange,+ compute_shared_bin_boundaries,+)from posthog.hogql_queries.insights.funnels.funnel_validation_rules import (RequireAtLeastTwoFunnelSteps,ValidateFunnelExclusions,@@ -49,6 +54,8 @@ from posthog.models.user import Userlogger = structlog.get_logger(__name__)+_T = TypeVar("_T")+class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):query: FunnelsQuery@@ -163,21 +170,14 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):),)- def _calculate_compare(self) -> FunnelsQueryResponse:- """Run current + previous period queries and merge tagged rows.+ def _run_in_parallel(self, tasks: list[Callable[[HogQLTimings], "_T"]], index_offset: int = 0) -> list["_T"]:+ """Run sub-query callables concurrently and return their results in order.- 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.+ Each task receives its own cloned `HogQLTimings` (not thread-safe to share). In unit tests+ we run serially because Django + threads is flaky there — trends compare uses the same bypass."""- previous_funnel = self._build_previous_funnel()- responses: list[Optional[FunnelsQueryResponse]] = [None, None]+ results: list[Optional[_T]] = [None] * len(tasks)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:@@ -185,11 +185,7 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):# 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],- )+ results[index] = tasks[index](timings)except Exception as exc: # noqa: BLE001errors.append(exc)finally:@@ -200,17 +196,16 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):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))+ for index in range(len(tasks)):+ run(index, self.timings.clone_for_subquery(index_offset + 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),+ args=(index, self.timings.clone_for_subquery(index_offset + index), parent_tags),)- for index in range(len(funnels))+ for index in range(len(tasks))]for job in jobs:job.start()@@ -224,8 +219,40 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):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+ return cast(list["_T"], results)++ def _calculate_compare(self) -> FunnelsQueryResponse:+ if self.context.funnelsFilter.funnelVizType == FunnelVizType.TIME_TO_CONVERT:+ return self._calculate_compare_time_to_convert()+ return self._calculate_compare_tagged_rows()++ def _calculate_compare_tagged_rows(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()++ # Each lambda passes its own period's date range through `date_range_override` so the+ # sub-response's resolved_date_range matches the period it computed, instead of leaking+ # the current-period range into the previous-period response.+ current_response, previous_response = self._run_in_parallel(+ [+ lambda timings: self._calculate_single_period(+ self.funnel_class,+ timings_override=timings,+ date_range_override=self.query_date_range,+ ),+ lambda timings: self._calculate_single_period(+ previous_funnel,+ timings_override=timings,+ date_range_override=self.query_previous_date_range,+ ),+ ]+ )merged_results = []for row in current_response.results or []:@@ -248,8 +275,85 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):),)- def _build_previous_funnel(self) -> FunnelTrendsUDF:- """Construct a FunnelTrendsUDF pinned to the previous-period date range.+ def _calculate_compare_time_to_convert(self) -> FunnelsQueryResponse:+ """Compare for the TIME_TO_CONVERT viz: both histograms must share an x-axis.++ Step 1 computes the bin boundaries from the union of conversion times observed across+ both periods. Step 2 runs both `FunnelTimeToConvertUDF` queries in parallel, each pinned+ to those shared boundaries. The merged result is a two-element list (current + previous),+ each tagged with `compare_label` and carrying `bins`/`average_conversion_time` aligned on+ the shared boundaries.+ """+ current_funnel = self.funnel_class+ previous_funnel = self._build_previous_funnel()++ current_bounds, previous_bounds = self._run_in_parallel(+ [+ lambda timings: self._run_time_to_convert_bounds(current_funnel, timings),+ lambda timings: self._run_time_to_convert_bounds(previous_funnel, timings),+ ]+ )+ boundaries = compute_shared_bin_boundaries(current_bounds, previous_bounds, self.context.funnelsFilter.binCount)++ current_result, previous_result = self._run_in_parallel(+ [+ lambda timings: self._run_time_to_convert_histogram(current_funnel, boundaries, timings),+ lambda timings: self._run_time_to_convert_histogram(previous_funnel, boundaries, timings),+ ],+ index_offset=2,+ )++ merged_results = [+ {**current_result.model_dump(), "compare_label": "current"},+ {**previous_result.model_dump(), "compare_label": "previous"},+ ]++ return FunnelsQueryResponse(+ results=merged_results,+ modifiers=self.modifiers,+ resolved_date_range=ResolvedDateRangeResponse(+ date_from=self.query_date_range.date_from(),+ date_to=self.query_date_range.date_to(),+ ),+ )++ def _run_time_to_convert_bounds(+ self, funnel: FunnelTimeToConvertUDF, timings: HogQLTimings+ ) -> Optional[ConversionTimeRange]:+ response = self._execute_funnel_query(funnel.get_bounds_query(), timings)+ if not response.results:+ return None+ sample_count, min_timing, max_timing = response.results[0]+ if not sample_count:+ return None+ return ConversionTimeRange(min_timing=min_timing, max_timing=max_timing, sample_count=sample_count)++ def _run_time_to_convert_histogram(+ self, funnel: FunnelTimeToConvertUDF, boundaries: list[int], timings: HogQLTimings+ ) -> FunnelTimeToConvertResults:+ if not boundaries:+ # Neither period converted — return an empty histogram skeleton.+ return FunnelTimeToConvertResults(bins=[], average_conversion_time=None)+ response = self._execute_funnel_query(funnel.get_query(explicit_bins=boundaries), timings)+ return funnel._format_results(response.results)++ def _execute_funnel_query(self, query: ast.SelectQuery, timings: HogQLTimings):+ return execute_hogql_query(+ query_type="FunnelsQuery",+ query=query,+ team=self.team,+ user=self.user,+ timings=timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ settings=HogQLGlobalSettings(+ # Make sure funnel queries never OOM+ max_bytes_before_external_group_by=MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY,+ ),+ )++ def _build_previous_funnel(self):+ """Construct a funnel (matching the current viz mode) pinned to the previous-period range.The previous query is a clone of `self.query` with its `dateRange` swapped for theshifted range and `compareFilter` cleared (to prevent infinite recursion if the cloned@@ -274,14 +378,22 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):modifiers=self.modifiers,limit_context=self.limit_context,)- return FunnelTrendsUDF(context=previous_context, just_summarize=self.just_summarize)+ return self._funnel_class_for_context(previous_context)++ def _funnel_class_for_context(self, context: FunnelQueryContext):+ funnelVizType = context.funnelsFilter.funnelVizType+ if funnelVizType == FunnelVizType.TRENDS:+ return FunnelTrendsUDF(context=context, just_summarize=self.just_summarize)+ elif funnelVizType == FunnelVizType.TIME_TO_CONVERT:+ return FunnelTimeToConvertUDF(context=context)+ return FunnelUDF(context=context)def _is_compare_active(self) -> bool:compare_filter = self.query.compareFilterif 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:+ # 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):return Falsereturn self._team_flag_funnels_compare()diff --git a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_time_to_convert.ambrindex 0e5f298752e1..741434908951 100644--- a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr+++ b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr@@ -5,7 +5,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -15,40 +15,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,@@ -71,7 +73,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -81,40 +83,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'strict', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'strict', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,@@ -137,7 +141,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -147,40 +151,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'unordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 604800, 'first_touch', 'unordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert.pyindex 90f663e3a964..bc32729d884c 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert.py@@ -1,3 +1,5 @@+from datetime import datetime+from posthog.test.base import (APIBaseTest,ClickhouseTestMixin,@@ -6,8 +8,10 @@ from posthog.test.base import (snapshot_clickhouse_queries,)from unittest.case import skip+from unittest.mock import patchfrom posthog.schema import (+ CompareFilter,DateRange,EventsNode,FunnelConversionWindowTimeUnit,@@ -20,6 +24,7 @@ from posthog.schema import ()from posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunner+from posthog.test.test_journeys import journeys_forFORMAT_TIME = "%Y-%m-%d %H:%M:%S"FORMAT_TIME_DAY_END = "%Y-%m-%d 23:59:59"@@ -632,3 +637,70 @@ class TestFunnelTimeToConvert(ClickhouseTestMixin, APIBaseTest):average_conversion_time=29540,),)+++class TestFunnelTimeToConvertCompare(ClickhouseTestMixin, APIBaseTest):+ """Compare-to-previous on funnel TIME_TO_CONVERT viz: two histograms on shared bin boundaries."""++ 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=None,+ bin_count=None,+ ) -> FunnelsQuery:+ return FunnelsQuery(+ series=[EventsNode(event="step one"), EventsNode(event="step two")],+ dateRange=DateRange(date_from=date_from, date_to=date_to),+ interval=IntervalType.DAY,+ funnelsFilter=FunnelsFilter(+ funnelVizType=FunnelVizType.TIME_TO_CONVERT,+ funnelFromStep=0,+ funnelToStep=1,+ funnelWindowInterval=7,+ funnelWindowIntervalUnit=FunnelConversionWindowTimeUnit.DAY,+ binCount=bin_count,+ ),+ compareFilter=CompareFilter(compare=compare, compare_to=compare_to),+ )++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_compare_returns_two_histograms_on_shared_bins(self, _feature_enabled):+ # Current window 2021-06-07..06-13: one 600 s conversion.+ # Default previous window 2021-05-31..06-06: one 3600 s conversion.+ journeys_for(+ {+ "current_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 8, 10, 0, 0)},+ {"event": "step two", "timestamp": datetime(2021, 6, 8, 10, 10, 0)},+ ],+ "previous_user": [+ {"event": "step one", "timestamp": datetime(2021, 6, 1, 10, 0, 0)},+ {"event": "step two", "timestamp": datetime(2021, 6, 1, 11, 0, 0)},+ ],+ },+ self.team,+ )++ results = FunnelsQueryRunner(query=self._build_query(), team=self.team).calculate().results++ self.assertEqual([row["compare_label"] for row in results], ["current", "previous"])++ current = next(r for r in results if r["compare_label"] == "current")+ previous = next(r for r in results if r["compare_label"] == "previous")++ # Both periods are bucketed on the SAME boundaries (union range [600, 3600]).+ current_boundaries = [b[0] for b in current["bins"]]+ previous_boundaries = [b[0] for b in previous["bins"]]+ self.assertEqual(current_boundaries, previous_boundaries)+ self.assertEqual(current_boundaries, [600, 2100, 3600])++ # Current 600 s conversion lands in the first bin; previous 3600 s in the last.+ self.assertEqual([count for _, count in current["bins"]], [1, 0, 0])+ self.assertEqual([count for _, count in previous["bins"]], [0, 0, 1])++ self.assertEqual(current["average_conversion_time"], 600)+ self.assertEqual(previous["average_conversion_time"], 3600)diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert_bins.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert_bins.pynew file mode 100644index 000000000000..57889cfeff68--- /dev/null+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_time_to_convert_bins.py@@ -0,0 +1,52 @@+from django.test import SimpleTestCase++from posthog.hogql_queries.insights.funnels.funnel_time_to_convert_bins import (+ ConversionTimeRange,+ compute_shared_bin_boundaries,+)+++class TestSharedBinComputer(SimpleTestCase):+ def test_spans_union_of_both_period_ranges(self):+ current = ConversionTimeRange(min_timing=100, max_timing=200, sample_count=8)+ previous = ConversionTimeRange(min_timing=50, max_timing=300, sample_count=19)++ boundaries = compute_shared_bin_boundaries(current, previous)++ # Union range [50, 300], 27 samples -> ceil(cbrt(27)) = 3 bins, width ceil(250/3) = 84.+ self.assertEqual(boundaries, [50, 134, 218, 302])++ def test_falls_back_to_the_only_populated_period(self):+ # Previous period has no conversions; boundaries come from the current period alone.+ current = ConversionTimeRange(min_timing=100, max_timing=200, sample_count=8)+ previous = ConversionTimeRange(min_timing=0, max_timing=0, sample_count=0)++ boundaries = compute_shared_bin_boundaries(current, previous)++ # 8 samples -> ceil(cbrt(8)) = 2 bins over [100, 200], width ceil(100/2) = 50.+ self.assertEqual(boundaries, [100, 150, 200])++ def test_treats_missing_period_like_empty_period(self):+ current = ConversionTimeRange(min_timing=100, max_timing=200, sample_count=8)++ self.assertEqual(+ compute_shared_bin_boundaries(current, None),+ compute_shared_bin_boundaries(current, ConversionTimeRange(0, 0, 0)),+ )++ def test_returns_no_boundaries_when_neither_period_converted(self):+ self.assertEqual(compute_shared_bin_boundaries(None, None), [])+ self.assertEqual(+ compute_shared_bin_boundaries(ConversionTimeRange(0, 0, 0), ConversionTimeRange(0, 0, 0)),+ [],+ )++ def test_bin_count_override_replaces_the_auto_count(self):+ current = ConversionTimeRange(min_timing=0, max_timing=100, sample_count=8)+ previous = ConversionTimeRange(min_timing=0, max_timing=100, sample_count=8)++ boundaries = compute_shared_bin_boundaries(current, previous, bin_count_override=4)++ # 4 bins over [0, 100], width ceil(100/4) = 25 -> 5 boundaries.+ self.assertEqual(boundaries, [0, 25, 50, 75, 100])+ self.assertEqual(len(boundaries), 5)diff --git a/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambrindex b0581782a31b..62fc6db73260 100644--- a/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambr+++ b/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambr@@ -6,7 +6,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -16,40 +16,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,@@ -73,7 +75,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -83,40 +85,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'strict', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'strict', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,@@ -140,7 +144,7 @@person_count,arrayAvg(timings) AS averageConversionTimeFROM- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings,+ (SELECT timings AS timings,accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,floor(arrayMin(timings)) AS min_timing,ceil(arrayMax(timings)) AS max_timing,@@ -150,40 +154,42 @@arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS countsFROM- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,- [''] AS prop,- arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'unordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)- and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)- and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)- and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)- and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,- af_tuple.1 AS step_reached,- plus(af_tuple.1, 1) AS steps,- af_tuple.2 AS breakdown,- af_tuple.3 AS timings,- af_tuple.5 AS steps_bitfield,- aggregation_target AS aggregation_target+ (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timingsFROM- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,- e.uuid AS uuid,- e.`$session_id` AS `$session_id`,- e.`$window_id` AS `$window_id`,- if(equals(e.event, 'step one'), 1, 0) AS step_0,- if(equals(e.event, 'step two'), 1, 0) AS step_1,- if(equals(e.event, 'step three'), 1, 0) AS step_2- FROM events AS e- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))- GROUP BY aggregation_target- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))- WHERE ifNull(greaterOrEquals(step_reached, 1), 0)) ARRAY+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,+ [''] AS prop,+ arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'unordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'step one'), 1, 0) AS step_0,+ if(equals(e.event, 'step two'), 1, 0) AS step_1,+ if(equals(e.event, 'step three'), 1, 0) AS step_2+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two'))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAYJOIN counts AS person_count,buckets AS bin_from_secondsLIMIT 100 SETTINGS readonly=2,diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.stories.tsx b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.stories.tsxindex c62e3e5e7750..a3a75a9ea156 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.stories.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.stories.tsx@@ -5,6 +5,7 @@ import { useState } from 'react'import { insightLogic } from 'scenes/insights/insightLogic'import funnelTimeToConvertFixture from '~/mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvert.json'+import funnelTimeToConvertCompareFixture from '~/mocks/fixtures/api/projects/team_id/insights/funnelTimeToConvertCompare.json'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'@@ -62,3 +63,7 @@ function renderFunnelHistogramChart(insightFixture: any): JSX.Element {export const Default: Story = {render: () => renderFunnelHistogramChart(funnelTimeToConvertFixture),}++export const Compare: Story = {+ render: () => renderFunnelHistogramChart(funnelTimeToConvertCompareFixture),+}diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsxindex 07ce3276aa4c..579dd1f8ac6b 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx@@ -6,7 +6,7 @@ import { BarChart, ValueLabels } from '@posthog/quill-charts'import type { BarChartConfig } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'-import { humanFriendlyNumber } from 'lib/utils'+import { hexToRGBA, humanFriendlyNumber } from 'lib/utils'import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'@@ -23,6 +23,9 @@ const CHART_CONFIG: BarChartConfig = {tooltip: { enabled: false },}+// Matches the trends compare convention of dimming the previous period to 50% alpha.+const PREVIOUS_PERIOD_ALPHA = 0.5+const handleChartError = (error: Error, info: ErrorInfo): void => {posthog.captureException(error, {feature: 'funnels-histogram-chart',@@ -34,12 +37,29 @@ export function FunnelHistogramChart(): JSX.Element | null {const { isDarkModeOn } = useValues(themeLogic)const theme = useMemo(() => buildTheme(), [isDarkModeOn])const { insightProps } = useValues(insightLogic)- const { histogramGraphData } = useValues(funnelDataLogic(insightProps))+ const { histogramGraphData, histogramGraphDataPrevious } = useValues(funnelDataLogic(insightProps))const { theme: dataColorTheme } = useValues(insightVizDataLogic(insightProps))+ const currentColor = dataColorTheme?.['preset-1']+ const isComparing = !!histogramGraphDataPrevious+const histogramData = useMemo(- () => buildFunnelHistogramData(histogramGraphData ?? [], { color: dataColorTheme?.['preset-1'] }),- [histogramGraphData, dataColorTheme]+ () =>+ buildFunnelHistogramData(histogramGraphData ?? [], {+ color: currentColor,+ previous: histogramGraphDataPrevious+ ? {+ data: histogramGraphDataPrevious,+ color: currentColor ? hexToRGBA(currentColor, PREVIOUS_PERIOD_ALPHA) : undefined,+ }+ : undefined,+ }),+ [histogramGraphData, histogramGraphDataPrevious, currentColor]+ )++ const config = useMemo<BarChartConfig>(+ () => (isComparing ? { ...CHART_CONFIG, barLayout: 'grouped' } : CHART_CONFIG),+ [isComparing])if (!histogramGraphData || histogramGraphData.length === 0) {@@ -51,14 +71,18 @@ export function FunnelHistogramChart(): JSX.Element | null {series={histogramData.series}labels={histogramData.labels}theme={theme}- config={CHART_CONFIG}+ config={config}className="FunnelHistogramChart"dataAttr="funnel-histogram"onError={handleChartError}>- <ValueLabels- valueFormatter={(_value, _seriesIndex, dataIndex) => histogramData.barLabels[dataIndex] ?? ''}- />+ {/* Per-bar percentage labels only read cleanly with a single series; the grouped+ compare view relies on tooltips (which label each period) instead. */}+ {!isComparing && (+ <ValueLabels+ valueFormatter={(_value, _seriesIndex, dataIndex) => histogramData.barLabels[dataIndex] ?? ''}+ />+ )}</BarChart>)}diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.test.ts b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.test.tsindex 687ad92b0744..17b59dfd0c39 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.test.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.test.ts@@ -2,6 +2,9 @@ import type { HistogramGraphDatum } from '~/types'import {buildFunnelHistogramData,+ FUNNEL_HISTOGRAM_CURRENT_SERIES_LABEL,+ FUNNEL_HISTOGRAM_PREVIOUS_SERIES_KEY,+ FUNNEL_HISTOGRAM_PREVIOUS_SERIES_LABEL,FUNNEL_HISTOGRAM_SERIES_KEY,FUNNEL_HISTOGRAM_SERIES_LABEL,} from './funnelHistogramTransforms'@@ -12,6 +15,12 @@ const bins: HistogramGraphDatum[] = [{ id: 120, bin0: 120, bin1: 180, count: 2, label: '10%' },]+const previousBins: HistogramGraphDatum[] = [+ { id: 0, bin0: 0, bin1: 60, count: 4, label: '40%' },+ { id: 60, bin0: 60, bin1: 120, count: 5, label: '50%' },+ { id: 120, bin0: 120, bin1: 180, count: 1, label: '10%' },+]+describe('buildFunnelHistogramData', () => {it('maps the bins onto a single conversion bar series', () => {const { series } = buildFunnelHistogramData(bins)@@ -53,4 +62,28 @@ describe('buildFunnelHistogramData', () => {expect(barLabels).toEqual([])expect(series[0].data).toEqual([])})++ it('emits a second desaturated series for the previous period when comparing', () => {+ const { series, labels } = buildFunnelHistogramData(bins, {+ color: '#1d4aff',+ previous: { data: previousBins, color: '#cccccc' },+ })++ expect(series).toHaveLength(2)+ expect(series[0].key).toBe(FUNNEL_HISTOGRAM_SERIES_KEY)+ expect(series[0].label).toBe(FUNNEL_HISTOGRAM_CURRENT_SERIES_LABEL)+ expect(series[0].data).toEqual([12, 6, 2])+ expect(series[1].key).toBe(FUNNEL_HISTOGRAM_PREVIOUS_SERIES_KEY)+ expect(series[1].label).toBe(FUNNEL_HISTOGRAM_PREVIOUS_SERIES_LABEL)+ expect(series[1].data).toEqual([4, 5, 1])+ expect(series[1].color).toBe('#cccccc')+ // Shared bins: labels come from the (current) period's boundaries.+ expect(labels).toEqual(['0s', '1m', '2m'])+ })++ it('stays single-series when no previous period is provided', () => {+ const { series } = buildFunnelHistogramData(bins, { color: '#1d4aff' })++ expect(series).toHaveLength(1)+ })})diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.tsindex ba1b79f1339a..e785a1aff54b 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts@@ -6,9 +6,13 @@ import type { HistogramGraphDatum } from '~/types'export const FUNNEL_HISTOGRAM_SERIES_KEY = 'funnel-histogram-conversions'export const FUNNEL_HISTOGRAM_SERIES_LABEL = 'Conversions'+/** When comparing, the current period is relabelled to disambiguate it from the previous one. */+export const FUNNEL_HISTOGRAM_CURRENT_SERIES_LABEL = 'Current'+export const FUNNEL_HISTOGRAM_PREVIOUS_SERIES_KEY = 'funnel-histogram-conversions-previous'+export const FUNNEL_HISTOGRAM_PREVIOUS_SERIES_LABEL = 'Previous'export interface FunnelHistogramData {- /** Single bar series; `data[i]` is the conversion count for bin `i`. */+ /** One bar series per period; `data[i]` is the conversion count for bin `i`. */series: Series[]/** Category labels — the lower bound of each duration bin, one per bar. */labels: string[]@@ -16,21 +20,36 @@ export interface FunnelHistogramData {barLabels: string[]}-/** Maps the funnel time-to-convert bins onto a categorical hog-charts bar series. */+/** Maps the funnel time-to-convert bins onto categorical hog-charts bar series.+ *+ * When `options.previous` is provided (compare-to-previous), a second desaturated series is+ * emitted. Both periods share the current period's bin boundaries, so the previous series is+ * indexed positionally against the same `labels`. */export function buildFunnelHistogramData(histogramGraphData: HistogramGraphDatum[],- options?: { color?: string }+ options?: { color?: string; previous?: { data: HistogramGraphDatum[]; color?: string } }): FunnelHistogramData {+ const series: Series[] = [+ {+ key: FUNNEL_HISTOGRAM_SERIES_KEY,+ label: options?.previous ? FUNNEL_HISTOGRAM_CURRENT_SERIES_LABEL : FUNNEL_HISTOGRAM_SERIES_LABEL,+ data: histogramGraphData.map((datum) => datum.count),+ color: options?.color,+ },+ ]++ if (options?.previous) {+ series.push({+ key: FUNNEL_HISTOGRAM_PREVIOUS_SERIES_KEY,+ label: FUNNEL_HISTOGRAM_PREVIOUS_SERIES_LABEL,+ data: options.previous.data.map((datum) => datum.count),+ color: options.previous.color,+ })+ }+return {labels: histogramGraphData.map((datum) => humanFriendlyDuration(datum.bin0, { maxUnits: 2 })),barLabels: histogramGraphData.map((datum) => datum.label),- series: [- {- key: FUNNEL_HISTOGRAM_SERIES_KEY,- label: FUNNEL_HISTOGRAM_SERIES_LABEL,- data: histogramGraphData.map((datum) => datum.count),- color: options?.color,- },- ],+ series,}}