Skip to content

: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.

fix(insights): prune scan for first_matching_event_for_user trends math (#61930)

Sam Pennington10b5df71d662
diff --git a/posthog/hogql_queries/insights/utils/aggregations.py b/posthog/hogql_queries/insights/utils/aggregations.py
index b8a8e8eba6d9..a01ab8119654 100644
--- a/posthog/hogql_queries/insights/utils/aggregations.py
+++ b/posthog/hogql_queries/insights/utils/aggregations.py
@@ -76,7 +76,7 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):
self._is_first_matching_event = is_first_matching_event
query.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)
+ query.where = self._where_expr(date_to, event_or_action_filter, self._matching_event_prefilter())
query.group_by = self._group_by_expr()
query.having = self._having_expr()
super().__init__(query)
@@ -92,9 +92,9 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):
)
min_timestamp_expr = (
- ast.Call(name="min", args=[ast.Field(chain=["timestamp"])])
- if not self._is_first_matching_event or self._filters is None
- else ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), self._filters])
+ ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), cast(ast.Expr, self._filters)])
+ if self._uses_conditional_aggregation()
+ else ast.Call(name="min", args=[ast.Field(chain=["timestamp"])])
)
return [
@@ -115,10 +115,25 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):
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)
- def _where_expr(self, date_to: ast.Expr, event_or_action_filter: ast.Expr | None = None) -> ast.Expr:
+ def _uses_conditional_aggregation(self) -> bool:
+ # first_matching_event_for_user wraps the series filters in conditional aggregates (minIf/argMinIf).
+ return self._is_first_matching_event and self._filters is not None
+
+ def _matching_event_prefilter(self) -> ast.Expr | None:
+ # Only a first_matching_event can push series filters into WHERE; plain first_time must scan full history.
+ return self._filters if self._uses_conditional_aggregation() else None
+
+ def _where_expr(
+ self,
+ date_to: ast.Expr,
+ event_or_action_filter: ast.Expr | None = None,
+ prefilter: ast.Expr | None = None,
+ ) -> ast.Expr:
where_filters = [date_to]
if event_or_action_filter is not None:
where_filters.append(event_or_action_filter)
+ if prefilter is not None:
+ where_filters.append(prefilter)
if len(where_filters) > 1:
where_filters_expr = cast(ast.Expr, ast.And(exprs=where_filters))
@@ -145,12 +160,12 @@ class FirstTimeForUserEventsQueryAlternator(QueryAlternator):
def _transform_column(self, column: ast.Expr):
return (
- ast.Call(name="argMin", args=[column, ast.Field(chain=["timestamp"])])
- if not self._is_first_matching_event or self._filters is None
- else ast.Call(
+ ast.Call(
name="argMinIf",
- args=[column, ast.Field(chain=["timestamp"]), self._filters],
+ args=[column, ast.Field(chain=["timestamp"]), cast(ast.Expr, self._filters)],
)
+ if self._uses_conditional_aggregation()
+ else ast.Call(name="argMin", args=[column, ast.Field(chain=["timestamp"])])
)
def append_select(self, expr: ast.Expr, aggregate: bool = False):
diff --git a/posthog/hogql_queries/insights/utils/test/test_aggregations.py b/posthog/hogql_queries/insights/utils/test/test_aggregations.py
index 5dc3b927d58e..3adff9af156c 100644
--- a/posthog/hogql_queries/insights/utils/test/test_aggregations.py
+++ b/posthog/hogql_queries/insights/utils/test/test_aggregations.py
@@ -148,6 +148,71 @@ class TestFirstTimeForUserEventsQueryAlternator:
assert query.where.exprs[0] == date_to
assert query.where.exprs[1] == event_filter
+ def test_filters_pushed_into_where_for_first_matching_event(self):
+ query = ast.SelectQuery(select=[])
+ date_from, date_to, filters = parse_expr("1 = 1"), parse_expr("2 = 2"), parse_expr("3 = 3")
+
+ builder = FirstTimeForUserEventsQueryAlternator(
+ query, date_from, date_to, filters=filters, is_first_matching_event=True
+ )
+ builder.build()
+
+ assert isinstance(query.where, ast.And)
+ assert filters in query.where.exprs
+
+ assert isinstance(query.select[0], ast.Alias)
+ assert query.select[0].alias == "min_timestamp"
+ assert isinstance(query.select[0].expr, ast.Call)
+ assert query.select[0].expr.name == "minIf"
+
+ def test_filters_stay_out_of_where_for_first_time_for_user(self):
+ query = ast.SelectQuery(select=[])
+ date_from, date_to, filters = parse_expr("1 = 1"), parse_expr("2 = 2"), parse_expr("3 = 3")
+
+ builder = FirstTimeForUserEventsQueryAlternator(
+ query, date_from, date_to, filters=filters, is_first_matching_event=False
+ )
+ builder.build()
+
+ assert query.where == date_to
+
+ assert isinstance(query.select[0], ast.Alias)
+ assert query.select[0].alias == "min_timestamp"
+ assert isinstance(query.select[0].expr, ast.Call)
+ assert query.select[0].expr.name == "min"
+
+ def test_first_matching_event_pushes_only_filters_not_breakdown_into_where(self):
+ query = ast.SelectQuery(select=[])
+ date_from, date_to, filters, filters_with_breakdown = (
+ parse_expr("1 = 1"),
+ parse_expr("2 = 2"),
+ parse_expr("3 = 3"),
+ parse_expr("4 = 4"),
+ )
+
+ builder = FirstTimeForUserEventsQueryAlternator(
+ query,
+ date_from,
+ date_to,
+ filters=filters,
+ is_first_matching_event=True,
+ filters_with_breakdown=filters_with_breakdown,
+ )
+ builder.build()
+
+ assert isinstance(query.where, ast.And)
+ assert filters in query.where.exprs
+ assert filters_with_breakdown not in query.where.exprs
+
+ assert isinstance(query.select[1], ast.Alias)
+ assert query.select[1].alias == "min_timestamp_with_condition"
+ assert isinstance(query.select[1].expr, ast.Call)
+ assert query.select[1].expr.name == "minIf"
+ assert query.select[1].expr.args == [
+ ast.Field(chain=["timestamp"]),
+ ast.And(exprs=[date_from, filters_with_breakdown]),
+ ]
+
def test_query_with_ratio_expr(self):
query = ast.SelectQuery(select=[])
date_from, date_to, ratio_expr = (