: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): hide incomplete conversion-window periods in trends (#61682)
Georgis Andonis78e129a88918
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 11f1433d92a7..c2cfbd980964 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -21132,6 +21132,11 @@},"type": "array"},+ "hideIncompleteConversionWindowPeriods": {+ "default": false,+ "description": "Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert.",+ "type": "boolean"+ },"layout": {"$ref": "#/definitions/FunnelLayout","default": "vertical"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex cbc37f70b415..fd0f881e7272 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1685,6 +1685,12 @@ export type FunnelsFilter = {* @default true*/showAnnotations?: boolean+ /**+ * Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent+ * tail of the trend isn't dragged down by entrants who still have time to convert.+ * @default false+ */+ hideIncompleteConversionWindowPeriods?: boolean}export interface FunnelsQuery extends InsightsQueryBase<FunnelsQueryResponse> {diff --git a/posthog/hogql_queries/insights/funnels/funnel_trends.py b/posthog/hogql_queries/insights/funnels/funnel_trends.pyindex 3a51d80e7688..83c9fbb8f37e 100644--- a/posthog/hogql_queries/insights/funnels/funnel_trends.py+++ b/posthog/hogql_queries/insights/funnels/funnel_trends.py@@ -1,4 +1,4 @@-from datetime import datetime+from datetime import datetime, timedeltafrom itertools import groupbyfrom typing import Any, Optional, cast@@ -504,6 +504,32 @@ class FunnelTrendsUDF(FunnelUDFMixin, FunnelBase):select=fill_select,select_from=fill_select_from,)++ if self.context.funnelsFilter.hideIncompleteConversionWindowPeriods:+ # Drop periods whose conversion window hasn't fully elapsed yet (relative to now), so the+ # recent tail of the trend isn't dragged down by entrants who still have time to convert.+ # A period is kept only once its whole interval has cleared the window, i.e. even its last+ # possible entrant has had the full window: entrance_period_start + interval <= now - window.+ cutoff = date_range.now_with_timezone - timedelta(seconds=self.conversion_window_limit())+ cutoff_as_hogql = ast.Call(+ name="assumeNotNull",+ args=[ast.Call(name="toDateTime", args=[ast.Constant(value=cutoff.strftime("%Y-%m-%d %H:%M:%S"))])],+ )+ period_end = ast.ArithmeticOperation(+ left=ast.ArithmeticOperation(+ left=get_start_of_interval_hogql(interval.value, team=team, source=date_from_as_hogql),+ right=ast.Call(name=interval_func, args=[ast.Field(chain=["number"])]),+ op=ast.ArithmeticOperationOp.Add,+ ),+ right=ast.Call(name=interval_func, args=[ast.Constant(value=1)]),+ op=ast.ArithmeticOperationOp.Add,+ )+ fill_query.where = ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=period_end,+ right=cutoff_as_hogql,+ )+return fill_querydef get_step_counts_without_aggregation_query(diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.pyindex 2e0a1d1a0aba..a075f80151de 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py@@ -131,6 +131,66 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(results), 7)self.assertEqual(formatted_results[0]["days"][0], "2021-06-07")+ def _run_conversion_window_trends(self, *, hide_incomplete_periods: bool) -> list[dict]:+ # user_a enters twice: once well in the past (06-07, window long elapsed) and once recently+ # (06-12, window still open). A single later step-two event (06-13) converts BOTH entrances,+ # since each is within the 7-day window. recent_entrant only just entered and hasn't converted.+ journeys_for(+ {+ "user_a": [+ {"event": "step one", "timestamp": datetime(2021, 6, 7)},+ {"event": "step one", "timestamp": datetime(2021, 6, 12)},+ {"event": "step two", "timestamp": datetime(2021, 6, 13)},+ ],+ "recent_entrant": [+ {"event": "step one", "timestamp": datetime(2021, 6, 15)},+ ],+ },+ self.team,+ )++ query = FunnelsQuery(+ dateRange=DateRange(date_from="2021-06-07 00:00:00", date_to="2021-06-18 23:59:59"),+ interval="day",+ series=[EventsNode(event="step one"), EventsNode(event="step two")],+ funnelsFilter=FunnelsFilter(+ funnelVizType="trends",+ funnelWindowInterval=7,+ funnelWindowIntervalUnit="day",+ hideIncompleteConversionWindowPeriods=hide_incomplete_periods,+ ),+ )+ return FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results++ @freeze_time("2021-06-18 12:00:00")+ def test_keeps_incomplete_conversion_window_periods_by_default(self):+ results = self._run_conversion_window_trends(hide_incomplete_periods=False)+ by_day = {row["timestamp"].date(): row for row in results}++ # every daily period in range is present, including the recent incomplete ones+ self.assertEqual([row["timestamp"].date() for row in results], [date(2021, 6, day) for day in range(7, 19)])+ # both of user_a's entrances converted+ self.assertEqual(by_day[date(2021, 6, 7)]["reached_to_step_count"], 1)+ self.assertEqual(by_day[date(2021, 6, 12)]["reached_to_step_count"], 1)+ # recent entrant shows as a non-converter, which is what drags the recent trend down+ self.assertEqual(by_day[date(2021, 6, 15)]["reached_from_step_count"], 1)+ self.assertEqual(by_day[date(2021, 6, 15)]["reached_to_step_count"], 0)++ @freeze_time("2021-06-18 12:00:00")+ def test_hides_incomplete_conversion_window_periods_when_enabled(self):+ results = self._run_conversion_window_trends(hide_incomplete_periods=True)+ by_day = {row["timestamp"].date(): row for row in results}++ # now=2021-06-18 12:00, window=7d -> cutoff=2021-06-11 12:00. A period is kept only once its+ # whole day has cleared the window (entrance_period_start + 1 day <= cutoff), i.e. entrances+ # on or before 2021-06-10.+ self.assertEqual([row["timestamp"].date() for row in results], [date(2021, 6, day) for day in range(7, 11)])+ # the old entrance that converted is retained, even though its conversion event is recent+ self.assertEqual(by_day[date(2021, 6, 7)]["reached_to_step_count"], 1)+ # the recent entrance (06-12) and the recent non-converter (06-15) are hidden+ self.assertNotIn(date(2021, 6, 12), by_day)+ self.assertNotIn(date(2021, 6, 15), by_day)+@parameterized.expand(["US/Pacific", "UTC"])def test_only_one_user_reached_one_step(self, timezone):self.team.timezone = timezonediff --git a/posthog/schema.py b/posthog/schema.pyindex 9045a9a45fd5..27ee0d5027f4 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -22784,6 +22784,14 @@ class FunnelsFilter(BaseModel):funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit | None = FunnelConversionWindowTimeUnit.DAYgoalLines: list[GoalLine] | None = Field(default=None, description="Goal Lines")hiddenLegendBreakdowns: list[str] | None = None+ hideIncompleteConversionWindowPeriods: bool | None = Field(+ default=False,+ description=(+ "Trends only: hide periods whose conversion window has not fully elapsed"+ " yet, so the recent tail of the trend isn't dragged down by entrants who"+ " still have time to convert."+ ),+ )layout: FunnelLayout | None = FunnelLayout.VERTICALresultCustomizations: dict[str, ResultCustomizationByValue] | None = Field(default=None,diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 3a143a00957d..d4b3e43f4294 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2188,6 +2188,8 @@ export interface FunnelsFilterApi {/** Goal Lines */goalLines?: GoalLineApi[] | nullhiddenLegendBreakdowns?: string[] | null+ /** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */+ hideIncompleteConversionWindowPeriods?: boolean | nulllayout?: FunnelLayoutApi | null/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterApiResultCustomizationsdiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex ae501b751aa8..a27959031a7c 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1881,6 +1881,8 @@ export interface FunnelsFilterApi {/** Goal Lines */goalLines?: GoalLineApi[] | nullhiddenLegendBreakdowns?: string[] | null+ /** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */+ hideIncompleteConversionWindowPeriods?: boolean | nulllayout?: FunnelLayoutApi | null/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterApiResultCustomizationsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b2270eb81b65..43f1a8d05da2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2372,6 +2372,8 @@ export namespace Schemas {/** Goal Lines */goalLines?: GoalLine[] | null;hiddenLegendBreakdowns?: string[] | null;+ /** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */+ hideIncompleteConversionWindowPeriods?: boolean | null;layout?: FunnelLayout | null;/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterResultCustomizations;