: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
chore(retention): make first-time anchor entity-polymorphic (#60110)
Thomas Obermüllerfc4c498a6ea7
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py b/posthog/hogql_queries/insights/retention/retention_base_query_builder.pyindex fb17600a7afc..4b2d424e2342 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_builder.py@@ -4,9 +4,11 @@ from abc import ABC, abstractmethodfrom functools import cached_propertyfrom typing import TYPE_CHECKING, Optional, cast+from posthog.schema import EntityType+from posthog.hogql import astfrom posthog.hogql.parser import parse_expr-from posthog.hogql.property import entity_to_expr+from posthog.hogql.property import entity_to_expr, property_to_exprfrom posthog.hogql_queries.insights.retention.utils import breakdown_extract_expr@@ -48,12 +50,37 @@ class RetentionBaseQueryBuilder(ABC):def start_entity_expr(self) -> ast.Expr:return self.runner.start_entity_expr+ def entity_expr_no_props(self, entity: RetentionEntity) -> ast.Expr:+ # Entity matcher with property filters stripped — used to anchor "first ever" against the unfiltered stream.+ # For a data warehouse entity, "presence in the table" is the unfiltered stream, so the predicate is a truthy constant.+ if entity.type == EntityType.DATA_WAREHOUSE:+ return ast.Constant(value=True)+ clean_entity = entity.model_copy(deep=True)+ clean_entity.properties = []+ return entity_to_expr(clean_entity, self.team)++ def entity_expr_with_props(self, entity: RetentionEntity) -> ast.Expr:+ # For data warehouse entities the table itself IS the type matcher, so the "with properties" predicate is+ # just the property filter (or a truthy constant when no properties are configured).+ if entity.type == EntityType.DATA_WAREHOUSE:+ if entity.properties:+ return property_to_expr(entity.properties, self.team)+ return ast.Constant(value=True)+ return entity_to_expr(entity, self.team)++ def entity_timestamp_field(self, entity: RetentionEntity) -> ast.Expr:+ if entity.type == EntityType.DATA_WAREHOUSE:+ if not entity.table_name or not entity.timestamp_field:+ raise ValueError(+ f"DATA_WAREHOUSE RetentionEntity requires table_name and timestamp_field, "+ f"got table_name={entity.table_name!r}, timestamp_field={entity.timestamp_field!r}"+ )+ return ast.Field(chain=[entity.table_name, entity.timestamp_field])+ return ast.Field(chain=["events", "timestamp"])+@cached_propertydef start_entity_expr_no_props(self) -> ast.Expr:- # Start-event matcher with property filters stripped — used to anchor "first ever" against the unfiltered stream.- clean_start_event = self.start_event.model_copy(deep=True)- clean_start_event.properties = []- return entity_to_expr(clean_start_event, self.team)+ return self.entity_expr_no_props(self.start_event)@propertydef return_entity_expr(self) -> ast.Expr:@@ -164,25 +191,33 @@ class RetentionBaseQueryBuilder(ABC):def events_timestamp_filter(self, field: ast.Expr | None = None) -> ast.Expr:return self.runner.events_timestamp_filter(field=field)- def get_first_time_anchor_expr(self) -> ast.Expr:- if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:- start_entity_with_properties_expr = entity_to_expr(self.start_event, self.team)-- if self.is_first_ever_occurrence:- # First-ever occurrence of the target event, then check filters.- # We find the timestamp of the first event of this type, and the first event of this type that also matches properties.- # If they are the same, this is the user's cohorting event.- min_ts_expr = parse_expr("minIf(events.timestamp, {expr})", {"expr": self.start_entity_expr_no_props})- min_ts_with_props_expr = parse_expr(- "minIf(events.timestamp, {expr})", {"expr": start_entity_with_properties_expr}- )-- return parse_expr(- "if({min_ts} = {min_ts_with_props}, {min_ts}, NULL)",- {"min_ts": min_ts_expr, "min_ts_with_props": min_ts_with_props_expr},- )- else: # is_first_occurrence_matching_filters- # First occurrence of the target event that matches filters.- return parse_expr("minIf(events.timestamp, {expr})", {"expr": start_entity_with_properties_expr})- else:+ def get_first_time_anchor_expr(self, entity: RetentionEntity) -> ast.Expr:+ if not (self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence):return ast.Constant(value=None)++ timestamp_field = self.entity_timestamp_field(entity)+ entity_with_properties_expr = self.entity_expr_with_props(entity)++ if self.is_first_ever_occurrence:+ # First-ever occurrence of the target entity, then check filters.+ # We find the timestamp of the first row of this entity, and the first row that also matches properties.+ # If they are the same, this is the user's cohorting event.+ min_ts_expr = parse_expr(+ "minIf({ts}, {expr})",+ {"ts": timestamp_field, "expr": self.entity_expr_no_props(entity)},+ )+ min_ts_with_props_expr = parse_expr(+ "minIf({ts}, {expr})",+ {"ts": timestamp_field, "expr": entity_with_properties_expr},+ )++ return parse_expr(+ "if({min_ts} = {min_ts_with_props}, {min_ts}, NULL)",+ {"min_ts": min_ts_expr, "min_ts_with_props": min_ts_with_props_expr},+ )++ # is_first_occurrence_matching_filters: first occurrence of the target entity that matches filters.+ return parse_expr(+ "minIf({ts}, {expr})",+ {"ts": timestamp_field, "expr": entity_with_properties_expr},+ )diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.pyindex d31b5f3c1bed..8b6e599ab780 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py@@ -403,7 +403,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):return_event_values = Noneif self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:- min_timestamp_inner_expr = self.get_first_time_anchor_expr()+ min_timestamp_inner_expr = self.get_first_time_anchor_expr(self.start_event)start_event_timestamps = parse_expr("""diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py b/posthog/hogql_queries/insights/retention/retention_base_query_rolling.pyindex ef97f64d210f..bca17f8b4843 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py@@ -22,7 +22,7 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):t0_expr: ast.Exprif self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:- t0_expr = self.get_first_time_anchor_expr()+ t0_expr = self.get_first_time_anchor_expr(self.start_event)else:t0_expr = parse_expr("minIf(events.timestamp, {expr})", {"expr": self.start_entity_expr})diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.py b/posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.pynew file mode 100644index 000000000000..eed49788c4fe--- /dev/null+++ b/posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.py@@ -0,0 +1,199 @@+from collections.abc import Callable+from typing import Any++from unittest import TestCase+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import RetentionEntity++from posthog.hogql import ast++from posthog.hogql_queries.insights.retention.retention_base_query_fixed import RetentionFixedIntervalBaseQueryBuilder+++def _walk_ast(node: Any, visit: Callable[[Any], None]) -> None:+ """Recursively visit every value in an AST tree (dataclass fields + list/tuple items)."""++ def walk(value: Any) -> None:+ visit(value)+ if hasattr(value, "__dataclass_fields__"):+ for field_name in value.__dataclass_fields__:+ walk(getattr(value, field_name))+ elif isinstance(value, list | tuple):+ for item in value:+ walk(item)++ walk(node)+++def _collect_field_chains(node: Any) -> list[list[str | int]]:+ chains: list[list[str | int]] = []++ def visit(value: Any) -> None:+ if isinstance(value, ast.Field):+ chains.append(value.chain)++ _walk_ast(node, visit)+ return chains+++def _collect_constants(node: Any) -> list[Any]:+ consts: list[Any] = []++ def visit(value: Any) -> None:+ if isinstance(value, ast.Constant):+ consts.append(value.value)++ _walk_ast(node, visit)+ return consts+++def _collect_min_if_predicates(node: Any) -> list[ast.Expr]:+ """Collect the second argument of every `minIf(...)` call in the AST."""+ predicates: list[ast.Expr] = []++ def visit(value: Any) -> None:+ if isinstance(value, ast.Call) and value.name == "minIf" and len(value.args) >= 2:+ predicates.append(value.args[1])++ _walk_ast(node, visit)+ return predicates+++def _make_builder(+ *,+ start_event: RetentionEntity,+ is_first_ever: bool = False,+ is_first_matching: bool = False,+) -> RetentionFixedIntervalBaseQueryBuilder:+ """Build a RetentionFixedIntervalBaseQueryBuilder with a stubbed runner.++ The helpers under test only need `team`, `start_event`, and the two first-occurrence+ flags from the runner, so we don't need a real Django Team or a live ClickHouse stack.+ """+ runner = MagicMock()+ runner.team = MagicMock(pk=1)+ runner.start_event = start_event+ runner.is_first_ever_occurrence = is_first_ever+ runner.is_first_occurrence_matching_filters = is_first_matching+ return RetentionFixedIntervalBaseQueryBuilder(runner)+++_EVENTS_FIRST_EVER_ENTITY = RetentionEntity(id="$user_signed_up", name="$user_signed_up", type="events")+_EVENTS_FIRST_MATCHING_ENTITY = RetentionEntity(+ id="$user_signed_up",+ name="$user_signed_up",+ type="events",+ properties=[+ {"key": "$browser", "value": "Chrome", "operator": "exact", "type": "event"},+ ],+)+_DWH_WITH_PROPS_ENTITY = RetentionEntity(+ type="data_warehouse",+ table_name="warehouse_activity",+ timestamp_field="occurred_at",+ aggregation_target_field="person_id",+ id="warehouse_activity",+ name="warehouse_activity",+ properties=[+ {"key": "event_type", "value": "signup", "operator": "exact", "type": "data_warehouse"},+ ],+)+_DWH_NO_PROPS_ENTITY = RetentionEntity(+ type="data_warehouse",+ table_name="warehouse_activity",+ timestamp_field="occurred_at",+ aggregation_target_field="person_id",+ id="warehouse_activity",+ name="warehouse_activity",+ properties=[],+)+++class TestFirstTimeAnchorExpr(TestCase):+ @parameterized.expand(+ [+ (+ "events_first_ever_references_events_timestamp",+ _EVENTS_FIRST_EVER_ENTITY,+ True, # is_first_ever+ False, # is_first_matching+ [["events", "timestamp"]], # expected_chains+ [], # unexpected_chains+ ["$user_signed_up"], # expected_constants+ False, # assert_min_if_predicates_truthy+ ),+ (+ "events_first_time_matching_filters_uses_events_predicate",+ _EVENTS_FIRST_MATCHING_ENTITY,+ False,+ True,+ [["events", "timestamp"]],+ [],+ ["$user_signed_up", "Chrome"],+ False,+ ),+ (+ "dwh_with_properties_uses_property_filter_predicate",+ _DWH_WITH_PROPS_ENTITY,+ False,+ True,+ [["warehouse_activity", "occurred_at"]],+ [["events", "timestamp"]],+ ["signup"],+ False,+ ),+ (+ # First-ever so both no-props and with-props minIf predicates are surfaced.+ "dwh_without_properties_uses_truthy_constant_predicate",+ _DWH_NO_PROPS_ENTITY,+ True,+ False,+ [["warehouse_activity", "occurred_at"]],+ [["events", "timestamp"]],+ [],+ True,+ ),+ ]+ )+ def test_get_first_time_anchor_expr(+ self,+ _name: str,+ entity: RetentionEntity,+ is_first_ever: bool,+ is_first_matching: bool,+ expected_chains: list[list[str | int]],+ unexpected_chains: list[list[str | int]],+ expected_constants: list[Any],+ assert_min_if_predicates_truthy: bool,+ ) -> None:+ builder = _make_builder(+ start_event=entity,+ is_first_ever=is_first_ever,+ is_first_matching=is_first_matching,+ )++ expr = builder.get_first_time_anchor_expr(entity)++ chains = _collect_field_chains(expr)+ for chain in expected_chains:+ self.assertIn(chain, chains)+ for chain in unexpected_chains:+ self.assertNotIn(chain, chains)++ constants = _collect_constants(expr)+ for constant in expected_constants:+ self.assertIn(constant, constants)++ if assert_min_if_predicates_truthy:+ # Every minIf predicate must be a truthy constant — the with-props and no-props branches+ # both collapse to True for a DWH entity without properties.+ # (parse_expr substitution shares nodes so the walker can see more than 2.)+ min_if_predicates = _collect_min_if_predicates(expr)+ self.assertGreaterEqual(len(min_if_predicates), 2)+ for pred in min_if_predicates:+ self.assertIsInstance(pred, ast.Constant)+ assert isinstance(pred, ast.Constant) # narrow for mypy+ self.assertTrue(pred.value)