:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(funnels): make first-time-for-user math work for data warehouse steps (#63633)
Thomas Obermüllera392ceb1a5b8
diff --git a/posthog/hogql_queries/insights/funnels/funnel_aggregation_operations.py b/posthog/hogql_queries/insights/funnels/funnel_aggregation_operations.pyindex f31acf12c181..f78a3e927b0d 100644--- a/posthog/hogql_queries/insights/funnels/funnel_aggregation_operations.py+++ b/posthog/hogql_queries/insights/funnels/funnel_aggregation_operations.py@@ -3,7 +3,10 @@ from typing import castfrom posthog.hogql import astfrom posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContext-from posthog.hogql_queries.insights.utils.aggregations import FirstTimeForUserEventsQueryAlternator+from posthog.hogql_queries.insights.utils.aggregations import (+ FirstTimeForUserDataWarehouseConfig,+ FirstTimeForUserEventsQueryAlternator,+)from posthog.hogql_queries.utils.query_date_range import QueryDateRange@@ -11,16 +14,19 @@ class FirstTimeForUserAggregationQuery:_context: FunnelQueryContext_filters: ast.Expr | None_event_or_action_filter: ast.Expr | None+ _dwh_config: FirstTimeForUserDataWarehouseConfig | Nonedef __init__(self,context: FunnelQueryContext,filters: ast.Expr | None = None,event_or_action_filter: ast.Expr | None = None,+ dwh_config: FirstTimeForUserDataWarehouseConfig | None = None,):self._context = contextself._filters = filtersself._event_or_action_filter = event_or_action_filter+ self._dwh_config = dwh_configdef to_query(self) -> ast.SelectQuery:query = ast.SelectQuery(@@ -38,14 +44,16 @@ class FirstTimeForUserAggregationQuery:self._filters,self._event_or_action_filter,self._ratio_expr(),+ dwh_config=self._dwh_config,)builder.append_select(self._select_expr(), aggregate=True)return cast(ast.SelectQuery, builder.build())def _select_expr(self):+ expr = self._dwh_config.id_select_expr if self._dwh_config is not None else ast.Field(chain=["uuid"])return ast.Alias(alias="uuid",- expr=ast.Field(chain=["uuid"]),+ expr=expr,)def _date_range(self) -> QueryDateRange:@@ -58,17 +66,22 @@ class FirstTimeForUserAggregationQuery:)return date_range+ def _timestamp_expr(self) -> ast.Expr:+ if self._dwh_config is not None:+ return self._dwh_config.timestamp_expr+ return ast.Field(chain=["timestamp"])+def _date_to_expr(self) -> ast.Expr:return ast.CompareOperation(op=ast.CompareOperationOp.LtEq,- left=ast.Field(chain=["timestamp"]),+ left=self._timestamp_expr(),right=ast.Constant(value=self._date_range().date_to()),)def _date_from_expr(self) -> ast.Expr:return ast.CompareOperation(op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["timestamp"]),+ left=self._timestamp_expr(),right=ast.Constant(value=self._date_range().date_from()),)diff --git a/posthog/hogql_queries/insights/funnels/funnel_event_query.py b/posthog/hogql_queries/insights/funnels/funnel_event_query.pyindex 7ff59e602d95..78e7863c0052 100644--- a/posthog/hogql_queries/insights/funnels/funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/funnel_event_query.py@@ -37,6 +37,7 @@ from posthog.hogql_queries.insights.funnels.utils import (entity_config_mismatch,get_breakdown_expr,)+from posthog.hogql_queries.insights.utils.aggregations import FirstTimeForUserDataWarehouseConfigfrom posthog.hogql_queries.insights.utils.breakdowns import NOT_IN_COHORT_ID, strip_user_aliasesfrom posthog.hogql_queries.insights.utils.data_warehouse_schema_mixin import DataWarehouseSchemaMixinfrom posthog.hogql_queries.insights.utils.properties import Properties@@ -221,23 +222,13 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):)return stmt- def _build_data_warehouse_table_query(- self,- table_config_index: int,- steps_with_index: Sequence[tuple[int, FunnelsDataWarehouseNode]],- skip_step_filter: bool,- ) -> ast.SelectQuery:- table_entity = steps_with_index[0][1]-- all_step_cols = self._get_funnel_cols(table_entity, table_config_index)-+ def _warehouse_timestamp_expr(self, table_entity: FunnelsDataWarehouseNode) -> ast.Expr:field = self.get_warehouse_field(table_entity.table_name, table_entity.timestamp_field)- timestamp_expr: ast.Exprif isinstance(field, DateTimeDatabaseField) or isinstance(field, DateDatabaseField):- timestamp_expr = ast.Field(chain=[self.EVENT_TABLE_ALIAS, table_entity.timestamp_field])+ return ast.Field(chain=[self.EVENT_TABLE_ALIAS, table_entity.timestamp_field])elif isinstance(field, StringDatabaseField):- timestamp_expr = ast.Call(+ return ast.Call(name="toDateTime", args=[ast.Field(chain=[self.EVENT_TABLE_ALIAS, table_entity.timestamp_field])])else:@@ -245,6 +236,18 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):detail=f"Unsupported timestamp field type for {table_entity.table_name}.{table_entity.timestamp_field}")+ def _build_data_warehouse_table_query(+ self,+ table_config_index: int,+ steps_with_index: Sequence[tuple[int, FunnelsDataWarehouseNode]],+ skip_step_filter: bool,+ ) -> ast.SelectQuery:+ table_entity = steps_with_index[0][1]++ all_step_cols = self._get_funnel_cols(table_entity, table_config_index)++ timestamp_expr = self._warehouse_timestamp_expr(table_entity)+tag_contains_user_hogql()select: list[ast.Expr] = [ast.Alias(@@ -382,23 +385,39 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):filters.append(filter_expr)if step_entity.math == FunnelMathType.FIRST_TIME_FOR_USER:- subquery = FirstTimeForUserAggregationQuery(self.context, filter_expr, event_expr).to_query()- first_time_filter = ast.CompareOperation(- left=ast.Field(chain=["e", "uuid"]), right=subquery, op=ast.CompareOperationOp.GlobalIn- )+ dwh_config, lhs = self._first_time_config_and_lhs(table_entity)+ subquery = FirstTimeForUserAggregationQuery(+ self.context, filter_expr, event_expr, dwh_config=dwh_config+ ).to_query()+ first_time_filter = ast.CompareOperation(left=lhs, right=subquery, op=ast.CompareOperationOp.GlobalIn)return ast.And(exprs=[*filters, first_time_filter])elif step_entity.math == FunnelMathType.FIRST_TIME_FOR_USER_WITH_FILTERS:+ dwh_config, lhs = self._first_time_config_and_lhs(table_entity)subquery = FirstTimeForUserAggregationQuery(- self.context, ast.Constant(value=1), ast.And(exprs=filters)+ self.context, ast.Constant(value=1), ast.And(exprs=filters), dwh_config=dwh_config).to_query()- first_time_filter = ast.CompareOperation(- left=ast.Field(chain=["e", "uuid"]), right=subquery, op=ast.CompareOperationOp.GlobalIn- )+ first_time_filter = ast.CompareOperation(left=lhs, right=subquery, op=ast.CompareOperationOp.GlobalIn)return ast.And(exprs=[*filters, first_time_filter])elif len(filters) > 1:return ast.And(exprs=filters)return filters[0]+ def _first_time_config_and_lhs(+ self, table_entity: FunnelsDataWarehouseNode | None+ ) -> tuple[FirstTimeForUserDataWarehouseConfig | None, ast.Expr]:+ # The first-time-for-user subquery defaults to the events table; for a data warehouse step it+ # must target the DWH table, timestamp, aggregation target, and id field instead.+ if isinstance(table_entity, FunnelsDataWarehouseNode):+ dwh_config = FirstTimeForUserDataWarehouseConfig(+ table_expr=ast.Field(chain=[table_entity.table_name]),+ timestamp_expr=self._warehouse_timestamp_expr(table_entity),+ group_by_expr=parse_expr(table_entity.aggregation_target_field),+ id_select_expr=ast.Field(chain=[table_entity.id_field]),+ )+ lhs: ast.Expr = ast.Field(chain=[self.EVENT_TABLE_ALIAS, table_entity.id_field])+ return dwh_config, lhs+ return None, ast.Field(chain=[self.EVENT_TABLE_ALIAS, "uuid"])+def _get_steps_conditions(self, steps_with_index: Sequence[tuple[int, FunnelEntityNode]]) -> ast.Expr:step_conditions: list[ast.Expr] = []diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_aggregation_operations.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_aggregation_operations.pyindex 5136e79fb773..ca9d23c46c55 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_aggregation_operations.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_aggregation_operations.py@@ -12,6 +12,16 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql_queries.insights.funnels.funnel_aggregation_operations import FirstTimeForUserAggregationQueryfrom posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContext+from posthog.hogql_queries.insights.utils.aggregations import FirstTimeForUserDataWarehouseConfig+++def _dwh_config(timestamp_expr: ast.Expr | None = None) -> FirstTimeForUserDataWarehouseConfig:+ return FirstTimeForUserDataWarehouseConfig(+ table_expr=ast.Field(chain=["payments"]),+ timestamp_expr=timestamp_expr or ast.Field(chain=["e", "created_at"]),+ group_by_expr=parse_expr("user_id"),+ id_select_expr=ast.Field(chain=["payment_id"]),+ )class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):@@ -230,3 +240,99 @@ class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):assert query.select_from.sample is Noneassert isinstance(query.select_from.table, ast.Field)assert query.select_from.table.chain == ["events"]++ def test_first_time_for_user_aggregation_data_warehouse_select_from(self):+ funnels_query = FunnelsQuery(+ series=[EventsNode(event="$pageview")],+ funnelsFilter=FunnelsFilter(funnelWindowInterval=14),+ dateRange=DateRange(date_from="-14d"),+ )+ ctx = FunnelQueryContext(funnels_query, self.team)++ builder = FirstTimeForUserAggregationQuery(context=ctx, dwh_config=_dwh_config())+ query = builder.to_query()++ assert query.select_from is not None+ inner = cast(ast.SelectQuery, query.select_from.table)+ assert inner.select_from is not None+ assert isinstance(inner.select_from.table, ast.Field)+ assert inner.select_from.table.chain == ["payments"]++ def test_first_time_for_user_aggregation_data_warehouse_group_by(self):+ funnels_query = FunnelsQuery(+ series=[EventsNode(event="$pageview")],+ funnelsFilter=FunnelsFilter(funnelWindowInterval=14),+ dateRange=DateRange(date_from="-14d"),+ )+ ctx = FunnelQueryContext(funnels_query, self.team)++ builder = FirstTimeForUserAggregationQuery(context=ctx, dwh_config=_dwh_config())+ query = builder.to_query()++ assert query.select_from is not None+ inner = cast(ast.SelectQuery, query.select_from.table)+ assert inner.group_by is not None+ assert inner.group_by[0] == parse_expr("user_id")++ def test_first_time_for_user_aggregation_data_warehouse_timestamp_and_id(self):+ funnels_query = FunnelsQuery(+ series=[EventsNode(event="$pageview")],+ funnelsFilter=FunnelsFilter(funnelWindowInterval=14),+ dateRange=DateRange(date_from="-14d"),+ )++ with freeze_time("2024-07-31"):+ ctx = FunnelQueryContext(funnels_query, self.team)+ builder = FirstTimeForUserAggregationQuery(context=ctx, dwh_config=_dwh_config())+ query = builder.to_query()++ # outer query still projects the "uuid" alias+ assert isinstance(query.select[0], ast.Field)+ assert query.select[0].chain == ["uuid"]++ assert query.select_from is not None+ inner = cast(ast.SelectQuery, query.select_from.table)++ timestamp_expr = ast.Field(chain=["e", "created_at"])++ # min_timestamp is computed over the data warehouse timestamp field+ min_timestamp = inner.select[0]+ assert isinstance(min_timestamp, ast.Alias)+ assert min_timestamp.alias == "min_timestamp"+ assert isinstance(min_timestamp.expr, ast.Call)+ assert min_timestamp.expr.name == "min"+ assert min_timestamp.expr.args[0] == timestamp_expr++ # the matching key is argMin(<id_field>, <timestamp_field>), aliased to uuid+ uuid_select = inner.select[2]+ assert isinstance(uuid_select, ast.Alias)+ assert uuid_select.alias == "uuid"+ assert isinstance(uuid_select.expr, ast.Call)+ assert uuid_select.expr.name == "argMin"+ assert uuid_select.expr.args[0] == ast.Field(chain=["payment_id"])+ assert uuid_select.expr.args[1] == timestamp_expr++ # the date range is filtered on the data warehouse timestamp field+ assert isinstance(inner.where, ast.CompareOperation)+ assert inner.where.left == timestamp_expr++ def test_first_time_for_user_aggregation_data_warehouse_string_timestamp(self):+ funnels_query = FunnelsQuery(+ series=[EventsNode(event="$pageview")],+ funnelsFilter=FunnelsFilter(funnelWindowInterval=14),+ dateRange=DateRange(date_from="-14d"),+ )+ ctx = FunnelQueryContext(funnels_query, self.team)++ # String timestamp columns are wrapped in toDateTime() by the caller; the wrapped+ # expression must thread through every timestamp reference in the subquery.+ timestamp_expr = ast.Call(name="toDateTime", args=[ast.Field(chain=["e", "created_at_str"])])+ builder = FirstTimeForUserAggregationQuery(context=ctx, dwh_config=_dwh_config(timestamp_expr))+ query = builder.to_query()++ assert query.select_from is not None+ inner = cast(ast.SelectQuery, query.select_from.table)++ min_timestamp = inner.select[0]+ assert isinstance(min_timestamp, ast.Alias)+ assert min_timestamp.expr == ast.Call(name="min", args=[timestamp_expr])diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_data_warehouse.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_data_warehouse.pyindex c5236067726a..27a33de77794 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_data_warehouse.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_data_warehouse.py@@ -18,6 +18,7 @@ from posthog.schema import (DataWarehousePropertyFilter,DateRange,EventsNode,+ FunnelMathType,FunnelsActorsQuery,FunnelsDataWarehouseNode,FunnelsFilter,@@ -622,3 +623,70 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):results = response.resultsassert results[0]["count"] == 2assert results[1]["count"] == 2++ def test_funnels_data_warehouse_first_time_for_user(self):+ # cf6a408b's first-ever row is 2025-11-02, before the 2025-11-03 window start, so+ # first-time-for-user must exclude that user from step 0 while a plain (total) funnel+ # still counts their later 2025-11-06 row.+ table_name = self.setup_data_warehouse()++ def _query(first_time: bool) -> FunnelsQuery:+ node = FunnelsDataWarehouseNode(+ id=table_name,+ table_name=table_name,+ id_field="uuid",+ aggregation_target_field="user_id",+ timestamp_field="created",+ math=FunnelMathType.FIRST_TIME_FOR_USER if first_time else None,+ )+ return FunnelsQuery(+ kind="FunnelsQuery",+ dateRange=DateRange(date_from="2025-11-03"),+ series=[node, node],+ )++ with freeze_time("2025-11-07"):+ total = FunnelsQueryRunner(query=_query(False), team=self.team, just_summarize=True).calculate()+ first_time = FunnelsQueryRunner(query=_query(True), team=self.team, just_summarize=True).calculate()++ # 4 distinct users have a row in the window; first-time-for-user drops cf6a408b,+ # whose first-ever occurrence falls before the window.+ assert total.results[0]["count"] == 4+ assert first_time.results[0]["count"] == 3++ def test_funnels_first_time_for_user_two_different_tables(self):+ table_one_name, table_two_name = self.setup_same_config_different_tables_data_warehouse()++ funnels_query = FunnelsQuery(+ kind="FunnelsQuery",+ dateRange=DateRange(date_from="2025-11-01"),+ series=[+ FunnelsDataWarehouseNode(+ id=table_one_name,+ table_name=table_one_name,+ id_field="id",+ aggregation_target_field="user_id",+ timestamp_field="created",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ ),+ FunnelsDataWarehouseNode(+ id=table_two_name,+ table_name=table_two_name,+ id_field="id",+ aggregation_target_field="user_id",+ timestamp_field="created",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ ),+ ],+ funnelsFilter=FunnelsFilter(funnelOrderType=StepOrderValue.UNORDERED),+ )++ with freeze_time("2025-11-07"):+ response = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True).calculate()++ # Each user appears once per table, so first-time-for-user leaves the counts unchanged —+ # but the funnel must still run with an independent first-time subquery per table+ # (a config bleed between the two tables would error or miscount).+ results = response.results+ assert results[0]["count"] == 2+ assert results[1]["count"] == 2diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.pyindex 57e5e496bf1f..79bc61a5a117 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py@@ -15,6 +15,7 @@ from posthog.schema import (EventPropertyFilter,EventsNode,FilterLogicalOperator,+ FunnelMathType,FunnelsDataWarehouseNode,FunnelsQuery,GroupNode,@@ -31,8 +32,13 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTabledef format_query(query: ast.SelectQuery):- sql = str(query)[4:-1]- return sqlparse.format(sql, keyword_case="upper", reindent=True)+ return sqlparse.format(query.to_hogql(), keyword_case="upper", reindent=True)+++def raw_query(query: ast.SelectQuery) -> str:+ # The single-line HogQL string, without sqlparse reindentation, so substring+ # assertions don't break on line wrapping.+ return query.to_hogql()class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):@@ -271,6 +277,159 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):""").strip()self.assertEqual(select_3, expected_3)+ @freeze_time("2025-11-12")+ def test_dwh_first_time_for_user(self):+ dwh_node = FunnelsDataWarehouseNode(+ aggregation_target_field="user_id",+ timestamp_field="created_at",+ table_name="payments",+ id="payments",+ id_field="id",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ )+ query = FunnelsQuery(series=[dwh_node, dwh_node])+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ # The first-time subquery must target the data warehouse table/timestamp/aggregation+ # target/id field — not the events table, person_id, or uuid.+ self.assertIn("FROM payments AS e", sql)+ self.assertIn("globalIn(e.id,", sql)+ self.assertIn("argMin(id, e.created_at) AS uuid", sql)+ self.assertIn("min(e.created_at) AS min_timestamp", sql)+ self.assertIn("GROUP BY user_id", sql)+ # the events-table concepts must NOT leak into the data warehouse subquery+ self.assertNotIn("FROM events", sql)+ self.assertNotIn("person_id", sql)++ @freeze_time("2025-11-12")+ def test_dwh_first_time_for_user_string_timestamp(self):+ dwh_node = FunnelsDataWarehouseNode(+ aggregation_target_field="user_id",+ timestamp_field="created_at_str",+ table_name="payments_string_timestamp",+ id="payments_string_timestamp",+ id_field="id",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ )+ query = FunnelsQuery(series=[dwh_node, dwh_node])+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ # String timestamp columns are wrapped in toDateTime() everywhere they're referenced.+ self.assertIn("FROM payments_string_timestamp AS e", sql)+ self.assertIn("argMin(id, toDateTime(e.created_at_str)) AS uuid", sql)+ self.assertIn("min(toDateTime(e.created_at_str)) AS min_timestamp", sql)+ self.assertIn("globalIn(e.id,", sql)++ @freeze_time("2025-11-12")+ def test_dwh_first_time_for_user_with_filters(self):+ dwh_node = FunnelsDataWarehouseNode(+ id="table_one",+ table_name="table_one",+ id_field="id",+ aggregation_target_field="user_id",+ timestamp_field="created_at",+ properties=[DataWarehousePropertyFilter(key="some_prop", value="some_value", operator="exact")],+ math=FunnelMathType.FIRST_TIME_FOR_USER_WITH_FILTERS,+ )+ query = FunnelsQuery(series=[dwh_node, dwh_node])+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ self.assertIn("FROM table_one AS e", sql)+ self.assertIn("globalIn(e.id,", sql)+ # the step's property filter resolves against the data warehouse table inside the subquery+ self.assertIn("equals(some_prop, 'some_value')", sql)++ @freeze_time("2025-11-12")+ def test_dwh_first_time_for_user_non_uuid_id_field(self):+ dwh_node = FunnelsDataWarehouseNode(+ id="table_two",+ table_name="table_two",+ id_field="some_id",+ aggregation_target_field="some_user_id",+ timestamp_field="ts",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ )+ query = FunnelsQuery(series=[dwh_node, dwh_node])+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ self.assertIn("FROM table_two AS e", sql)+ self.assertIn("globalIn(e.some_id,", sql)+ self.assertIn("argMin(some_id, e.ts) AS uuid", sql)+ self.assertIn("GROUP BY some_user_id", sql)++ @freeze_time("2025-11-12")+ def test_dwh_first_time_for_user_two_different_tables(self):+ query = FunnelsQuery(+ kind="FunnelsQuery",+ series=[+ FunnelsDataWarehouseNode(+ id="table_one",+ table_name="table_one",+ id_field="id",+ aggregation_target_field="user_id",+ timestamp_field="created_at",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ ),+ FunnelsDataWarehouseNode(+ id="table_two",+ table_name="table_two",+ id_field="some_id",+ aggregation_target_field="some_user_id",+ timestamp_field="ts",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ ),+ ],+ )+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ # Each table's first-time subquery is built independently against its own+ # table / aggregation target / id field — no cross-bleed between configs.+ self.assertIn("globalIn(e.id,", sql)+ self.assertIn("argMin(id, e.created_at) AS uuid", sql)+ self.assertIn("globalIn(e.some_id,", sql)+ self.assertIn("argMin(some_id, e.ts) AS uuid", sql)+ self.assertIn("GROUP BY user_id", sql)+ self.assertIn("GROUP BY some_user_id", sql)++ @freeze_time("2025-11-12")+ def test_mixed_events_and_dwh_first_time_for_user(self):+ query = FunnelsQuery(+ kind="FunnelsQuery",+ series=[+ EventsNode(event="$pageview", math=FunnelMathType.FIRST_TIME_FOR_USER),+ FunnelsDataWarehouseNode(+ id="payments",+ table_name="payments",+ id_field="id",+ aggregation_target_field="user_id",+ timestamp_field="created_at",+ math=FunnelMathType.FIRST_TIME_FOR_USER,+ ),+ ],+ )+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context).to_query())++ # The events-table branch keeps its original first-time shape (events / person_id / uuid)…+ self.assertIn("globalIn(e.uuid,", sql)+ self.assertIn("argMin(uuid, timestamp) AS uuid", sql)+ self.assertIn("GROUP BY person_id", sql)+ # …while the data warehouse branch targets the warehouse table.+ self.assertIn("globalIn(e.id,", sql)+ self.assertIn("argMin(id, e.created_at) AS uuid", sql)+ self.assertIn("GROUP BY user_id", sql)+@freeze_time("2025-11-12")def test_group_node_two_events(self):group = GroupNode(diff --git a/posthog/hogql_queries/insights/utils/aggregations.py b/posthog/hogql_queries/insights/utils/aggregations.pyindex a01ab8119654..d0e2b0f4727b 100644--- a/posthog/hogql_queries/insights/utils/aggregations.py+++ b/posthog/hogql_queries/insights/utils/aggregations.py@@ -1,8 +1,23 @@+from dataclasses import dataclassfrom typing import castfrom posthog.hogql import ast+@dataclass+class FirstTimeForUserDataWarehouseConfig:+ """Retargets the first-time-for-user subquery from the events table to a data warehouse table."""++ table_expr: ast.Field+ """The data warehouse table, e.g. ast.Field(chain=[table_name])."""+ timestamp_expr: ast.Expr+ """The timestamp column, e.g. e.<timestamp_field> (wrapped in toDateTime() for String columns)."""+ group_by_expr: ast.Expr+ """The aggregation target, e.g. parse_expr(aggregation_target_field)."""+ id_select_expr: ast.Expr+ """The row identifier, e.g. ast.Field(chain=[id_field]); becomes argMin(<id_field>, timestamp)."""++class QueryAlternator:"""Allows query_builder to modify the query without having to expose the whole AST interface"""@@ -70,10 +85,12 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):ratio: ast.RatioExpr | None = None,is_first_matching_event: bool = False,filters_with_breakdown: ast.Expr | None = None,+ dwh_config: FirstTimeForUserDataWarehouseConfig | None = None,):self._filters = filtersself._filters_with_breakdown = filters_with_breakdownself._is_first_matching_event = is_first_matching_event+ self._dwh_config = dwh_configquery.select = self._select_expr(date_from)query.select_from = self._select_from_expr(ratio)query.where = self._where_expr(date_to, event_or_action_filter, self._matching_event_prefilter())@@ -92,9 +109,9 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):)min_timestamp_expr = (- ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), cast(ast.Expr, self._filters)])+ ast.Call(name="minIf", args=[self._timestamp_field(), cast(ast.Expr, self._filters)])if self._uses_conditional_aggregation()- else ast.Call(name="min", args=[ast.Field(chain=["timestamp"])])+ else ast.Call(name="min", args=[self._timestamp_field()]))return [@@ -106,14 +123,20 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):alias="min_timestamp_with_condition",expr=ast.Call(name="minIf",- args=[ast.Field(chain=["timestamp"]), aggregation_filters],+ args=[self._timestamp_field(), aggregation_filters],),),]+ def _timestamp_field(self) -> ast.Expr:+ if self._dwh_config is not None:+ return self._dwh_config.timestamp_expr+ return ast.Field(chain=["timestamp"])+def _select_from_expr(self, ratio: ast.RatioExpr | None = None) -> ast.JoinExpr:sample_value = ast.SampleExpr(sample_value=ratio) if ratio is not None else None- return ast.JoinExpr(table=ast.Field(chain=["events"]), alias="e", sample=sample_value)+ table_expr = self._dwh_config.table_expr if self._dwh_config is not None else ast.Field(chain=["events"])+ return ast.JoinExpr(table=table_expr, alias="e", sample=sample_value)def _uses_conditional_aggregation(self) -> bool:# first_matching_event_for_user wraps the series filters in conditional aggregates (minIf/argMinIf).@@ -142,6 +165,8 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):return where_filters_exprdef _group_by_expr(self) -> list[ast.Expr]:+ if self._dwh_config is not None:+ return [self._dwh_config.group_by_expr]return [ast.Field(chain=["person_id"])]def _having_expr(self) -> ast.Expr:@@ -162,10 +187,10 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):return (ast.Call(name="argMinIf",- args=[column, ast.Field(chain=["timestamp"]), cast(ast.Expr, self._filters)],+ args=[column, self._timestamp_field(), cast(ast.Expr, self._filters)],)if self._uses_conditional_aggregation()- else ast.Call(name="argMin", args=[column, ast.Field(chain=["timestamp"])])+ else ast.Call(name="argMin", args=[column, self._timestamp_field()]))def append_select(self, expr: ast.Expr, aggregate: bool = False):