: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(retention): support data warehouse tables in 24h-window retention (#65139)
Thomas Obermüller48143956a73e
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.pyindex 6cbd7972ebf5..7bc58f781e4d 100644--- a/posthog/hogql_queries/access_controlled_resources.py+++ b/posthog/hogql_queries/access_controlled_resources.py@@ -2,7 +2,13 @@ from typing import TYPE_CHECKING, Optionalfrom pydantic import BaseModel-from posthog.schema import DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode+from posthog.schema import (+ DataWarehouseNode,+ EntityType,+ FunnelsDataWarehouseNode,+ LifecycleDataWarehouseNode,+ RetentionEntity,+)if TYPE_CHECKING:from posthog.models import Team@@ -131,10 +137,12 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strdef _references_data_warehouse(value) -> bool:- """True if a structured query reads a data-warehouse source via a DataWarehouseNode anywhere in- its tree (series, sub-queries, exclusions, ...)"""+ """True if a structured query reads a data-warehouse source via a DataWarehouseNode — or a+ data-warehouse RetentionEntity — anywhere in its tree (series, sub-queries, exclusions, ...)"""if isinstance(value, (DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode)):return True+ if isinstance(value, RetentionEntity) and value.type == EntityType.DATA_WAREHOUSE:+ return Trueif isinstance(value, BaseModel):return any(_references_data_warehouse(field) for field in value.__dict__.values())if isinstance(value, (list, tuple)):diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py b/posthog/hogql_queries/insights/retention/retention_base_query_builder.pyindex fd834220599d..8fc14fcf4d97 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_builder.py@@ -4,6 +4,8 @@ from abc import ABC, abstractmethodfrom functools import cached_propertyfrom typing import TYPE_CHECKING, Optional, cast+from rest_framework.exceptions import ValidationError+from posthog.schema import EntityTypefrom posthog.hogql import ast@@ -71,13 +73,20 @@ class RetentionBaseQueryBuilder(ABC):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}"- )+ # ValidationError so a half-configured entity surfaces as HTTP 400; a bare ValueError becomes a 500.+ raise ValidationError("A data warehouse retention series requires table_name and timestamp_field.")return ast.Field(chain=[entity.table_name, entity.timestamp_field])return ast.Field(chain=["events", "timestamp"])+ def entity_actor_id_column(self, entity: RetentionEntity) -> str:+ # The column that identifies the actor (person or group) for an entity: the configured join field+ # for a data warehouse entity, or the runner's resolved person/group column for events.+ if entity.type == EntityType.DATA_WAREHOUSE:+ if not entity.aggregation_target_field:+ raise ValidationError("A data warehouse retention series requires aggregation_target_field.")+ return entity.aggregation_target_field+ return self.aggregation_target_events_column+@cached_propertydef start_entity_expr_no_props(self) -> ast.Expr:return self.entity_expr_no_props(self.start_event)diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.pyindex ecf32347a9d2..418b3a1c5bc1 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py@@ -506,8 +506,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):) -> ast.SelectQuery:entity_is_dwh = entity.type == EntityType.DATA_WAREHOUSE- actor_column_name = entity.aggregation_target_field if entity_is_dwh else self.aggregation_target_events_column- assert actor_column_name+ actor_column_name = self.entity_actor_id_column(entity)actor_field = ast.Field(chain=[actor_column_name])timestamp_column_name = entity.timestamp_field if entity_is_dwh else "timestamp"diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py b/posthog/hogql_queries/insights/retention/retention_base_query_rolling.pyindex bca17f8b4843..cf0ac40d25cf 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py@@ -1,3 +1,5 @@+from posthog.schema import EntityType+from posthog.hogql import astfrom posthog.hogql.parser import parse_expr@@ -20,6 +22,53 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):else: # Dayunit, count = "hour", 24+ has_data_warehouse_series = (+ self.start_event.type == EntityType.DATA_WAREHOUSE or self.return_event.type == EntityType.DATA_WAREHOUSE+ )+ if has_data_warehouse_series:+ return self._build_base_query_data_warehouse(+ unit, count, start_interval_index_filter, selected_breakdown_value+ )+ return self._build_base_query_events(unit, count, start_interval_index_filter, selected_breakdown_value)++ def _cell_selection_having(+ self,+ start_interval_index_filter: int | None,+ selected_breakdown_value: str | list[str] | int | None,+ ) -> ast.Expr | None:+ # Actors-modal drill-down: restrict the base query to one grid cell. The conditions go in HAVING because+ # both operands are select aliases; breakdown_value in particular is only appended to this same query+ # object later, by apply_breakdown.+ exprs: list[ast.Expr] = []+ if start_interval_index_filter is not None:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["start_interval_index"]),+ right=ast.Constant(value=start_interval_index_filter),+ )+ )+ if selected_breakdown_value is not None:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["breakdown_value"]),+ right=ast.Constant(value=selected_breakdown_value),+ )+ )+ if not exprs:+ return None+ if len(exprs) == 1:+ return exprs[0]+ return ast.And(exprs=exprs)++ def _build_base_query_events(+ self,+ unit: str,+ count: int,+ start_interval_index_filter: int | None,+ selected_breakdown_value: str | list[str] | int | None,+ ) -> ast.SelectQuery:t0_expr: ast.Exprif self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:t0_expr = self.get_first_time_anchor_expr(self.start_event)@@ -102,6 +151,172 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):),where=ast.And(exprs=[*self.global_event_filters, parse_expr("timestamp >= t_0")]),group_by=[ast.Field(chain=["actors_with_t0", "actor_id"]), ast.Field(chain=["actors_with_t0", "t_0"])],+ having=self._cell_selection_having(start_interval_index_filter, selected_breakdown_value),)return inner_query++ def _build_base_query_data_warehouse(+ self,+ unit: str,+ count: int,+ start_interval_index_filter: int | None,+ selected_breakdown_value: str | list[str] | int | None,+ ) -> ast.SelectQuery:+ # Breakdowns are rejected upstream by DisallowBreakdownsWithDataWarehouse24HourWindows: apply_breakdown+ # references events / person columns, which aren't in scope in this query shape. Group aggregation is+ # rejected by DisallowGroupAggregationWithDataWarehouse24HourWindows: these scans identify actors by each+ # entity's aggregation_target_field, which has no group counterpart to join against. Global property+ # filters, test-account filters, and sampling are rejected by DisallowUnsupportedDataWarehouseSettings.+ first_event_cte = self._build_data_warehouse_first_event_cte()+ return_scan = self._build_return_scan()++ return_ts = ast.Field(chain=["return_events", "timestamp"])+ # The return scan already restricts its rows to the return entity inside the analysis window, so the only+ # outer condition is >= t_0. That comparison doubles as the discriminator that drops the NULL-filled+ # unmatched LEFT-join row: against a NULL timestamp it evaluates falsy.+ return_match = ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=return_ts,+ right=ast.Field(chain=["actors_with_t0", "t_0"]),+ )++ return ast.SelectQuery(+ select=[+ ast.Alias(alias="actor_id", expr=ast.Field(chain=["actors_with_t0", "actor_id"])),+ ast.Alias(+ alias="start_interval_index",+ expr=parse_expr(+ "floor(dateDiff({unit}, {date_from}, actors_with_t0.t_0) / {count})",+ {+ "unit": ast.Constant(value=unit),+ "count": ast.Constant(value=count),+ "date_from": self.query_date_range.date_from_as_hogql(),+ },+ ),+ ),+ ast.Alias(+ alias="intervals_from_base",+ expr=parse_expr(+ """+ arrayJoin(+ arrayDistinct(+ arrayConcat(+ [0],+ arrayFilter(+ x -> x >= 0,+ groupUniqArray(+ if(+ {return_match},+ floor(dateDiff({unit}, actors_with_t0.t_0, {return_ts}) / {count}),+ -1+ )+ )+ )+ )+ )+ )+ """,+ {+ "return_match": return_match,+ "return_ts": return_ts,+ "unit": ast.Constant(value=unit),+ "count": ast.Constant(value=count),+ },+ ),+ ),+ ],+ select_from=ast.JoinExpr(+ table=first_event_cte,+ alias="actors_with_t0",+ next_join=ast.JoinExpr(+ table=return_scan,+ alias="return_events",+ join_type="LEFT JOIN",+ constraint=ast.JoinConstraint(+ expr=ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["actors_with_t0", "actor_id"]),+ right=ast.Field(chain=["return_events", "actor_id"]),+ ),+ constraint_type="ON",+ ),+ ),+ ),+ group_by=[ast.Field(chain=["actors_with_t0", "actor_id"]), ast.Field(chain=["actors_with_t0", "t_0"])],+ having=self._cell_selection_having(start_interval_index_filter, selected_breakdown_value),+ )++ def _build_return_scan(self) -> ast.SelectQuery:+ # The return scan is its own subquery with the return table primary, because entity property filters emit+ # bare field chains (e.g. `properties.plan`): with `events` joined directly on the right side instead, the+ # lazy-table wrap that person-id resolution applies to a joined events table projects only alias-prefixed+ # references, so those bare chains fail to resolve. Filtering inside the scan sidesteps that entirely.+ return_is_dwh = self.return_event.type == EntityType.DATA_WAREHOUSE+ return_table_name = self.return_event.table_name if return_is_dwh else "events"+ assert return_table_name+ return_ts_field = self.entity_timestamp_field(self.return_event)+ return_actor_column = self.entity_actor_id_column(self.return_event)++ return ast.SelectQuery(+ select=[+ ast.Alias(alias="actor_id", expr=ast.Field(chain=[return_table_name, return_actor_column])),+ ast.Alias(alias="timestamp", expr=return_ts_field),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=[return_table_name])),+ where=ast.And(+ exprs=[+ self.entity_expr_with_props(self.return_event),+ self.events_timestamp_filter(field=return_ts_field),+ ]+ ),+ )++ def _build_data_warehouse_first_event_cte(self) -> ast.SelectQuery:+ start_is_dwh = self.start_event.type == EntityType.DATA_WAREHOUSE+ start_ts_field = self.entity_timestamp_field(self.start_event)+ start_table_name = self.start_event.table_name if start_is_dwh else "events"+ assert start_table_name+ start_actor_column = self.entity_actor_id_column(self.start_event)+ actor_id_expr = ast.Field(chain=[start_table_name, start_actor_column])++ where: ast.Expr | None+ having: ast.Expr | None+ if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:+ # The anchor must see the actor's true-earliest row, so the start table is scanned unwindowed; an+ # out-of-window anchor is then excluded by the window guard + HAVING (mirrors the fixed-interval DWH+ # variant's _first_time_start_event_timestamps_expr).+ anchor_expr = self.get_first_time_anchor_expr(self.start_event)+ t0_expr: ast.Expr = parse_expr(+ "if({within_window}, {anchor}, NULL)",+ {"within_window": self.events_timestamp_filter(field=anchor_expr), "anchor": anchor_expr},+ )+ # An events-typed start still gets the entity matcher as WHERE: both anchor variants condition on the+ # entity, so rows outside it never feed the aggregates, and without the pre-filter this scan reads the+ # team's entire events table.+ where = None if start_is_dwh else self.entity_expr_no_props(self.start_event)+ having = ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq, left=ast.Field(chain=["t_0"]), right=ast.Constant(value=None)+ )+ else:+ # Recurring: t_0 is the earliest qualifying start row inside the analysis window. The WHERE restricts the+ # group to qualifying rows so min() over a non-empty set is the cohorting timestamp (no HAVING needed).+ t0_expr = ast.Call(name="min", args=[start_ts_field])+ where = ast.And(+ exprs=[+ self.entity_expr_with_props(self.start_event),+ self.events_timestamp_filter(field=start_ts_field),+ ]+ )+ having = None++ return ast.SelectQuery(+ select=[+ ast.Alias(alias="actor_id", expr=actor_id_expr),+ ast.Alias(alias="t_0", expr=t0_expr),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=[start_table_name])),+ where=where,+ group_by=[ast.Field(chain=["actor_id"])],+ having=having,+ )diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/posthog/hogql_queries/insights/retention/retention_query_runner.pyindex 4786f9a23d95..95d2f15007c9 100644--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/retention_query_runner.py@@ -38,7 +38,12 @@ from posthog.hogql_queries.insights.retention.retention_base_query_fixed importfrom posthog.hogql_queries.insights.retention.retention_base_query_rolling import (RetentionRollingIntervalBaseQueryBuilder,)-from posthog.hogql_queries.insights.retention.retention_validation_rules import DisallowCumulativeWith24HourWindows+from posthog.hogql_queries.insights.retention.retention_validation_rules import (+ DisallowBreakdownsWithDataWarehouse24HourWindows,+ DisallowCumulativeWith24HourWindows,+ DisallowGroupAggregationWithDataWarehouse24HourWindows,+ DisallowPropertyAggregationWith24HourWindows,+)from posthog.hogql_queries.insights.utils.breakdowns import (ALL_USERS_COHORT_ID,BREAKDOWN_OTHER_STRING_LABEL,@@ -138,7 +143,13 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):self.modifiers.inCohortVia = InCohortVia.LEFTJOINdef validators(self) -> Sequence[QueryValidationRule[RetentionQuery]]:- return (DisallowCumulativeWith24HourWindows(), DisallowUnsupportedDataWarehouseSettings())+ return (+ DisallowCumulativeWith24HourWindows(),+ DisallowBreakdownsWithDataWarehouse24HourWindows(),+ DisallowGroupAggregationWithDataWarehouse24HourWindows(),+ DisallowPropertyAggregationWith24HourWindows(),+ DisallowUnsupportedDataWarehouseSettings(),+ )@cached_propertydef property_aggregation_expr(self) -> ast.Expr | None:diff --git a/posthog/hogql_queries/insights/retention/retention_validation_rules.py b/posthog/hogql_queries/insights/retention/retention_validation_rules.pyindex 2f09dae1af45..77fd39ca3c84 100644--- a/posthog/hogql_queries/insights/retention/retention_validation_rules.py+++ b/posthog/hogql_queries/insights/retention/retention_validation_rules.py@@ -1,7 +1,8 @@from rest_framework.exceptions import ValidationError-from posthog.schema import RetentionQuery+from posthog.schema import AggregationType, EntityType, RetentionQuery+from posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filterfrom posthog.hogql_queries.validation.validation import QueryValidationContext@@ -12,3 +13,72 @@ class DisallowCumulativeWith24HourWindows:retention_filter = context.query.retentionFilterif retention_filter.timeWindowMode == "24_hour_windows" and retention_filter.cumulative:raise ValidationError("Cumulative retention is not supported for 24 hour windows.", code=self.code)+++class DisallowBreakdownsWithDataWarehouse24HourWindows:+ """The 24-hour-window builder resolves a data warehouse series without an events scan in its outer query,+ so breakdown expressions (which read events / person columns) have nothing to resolve against."""++ code = "retention_data_warehouse_24_hour_windows_breakdowns_unsupported"++ def validate(self, context: QueryValidationContext[RetentionQuery]) -> None:+ retention_filter = context.query.retentionFilter+ if retention_filter.timeWindowMode != "24_hour_windows":+ return+ if not has_breakdown_filter(context.query.breakdownFilter):+ return+ has_data_warehouse_series = any(+ entity is not None and entity.type == EntityType.DATA_WAREHOUSE+ for entity in (retention_filter.targetEntity, retention_filter.returningEntity)+ )+ if has_data_warehouse_series:+ raise ValidationError(+ "Breakdowns are not supported for 24 hour windows with a data warehouse series.",+ code=self.code,+ )+++class DisallowGroupAggregationWithDataWarehouse24HourWindows:+ """The 24-hour-window data warehouse scans identify actors by each entity's aggregation_target_field and join+ the arms on it directly, so a group-typed events side contributes its $group_N key: the join keys mismatch in+ type and empty group keys are not filtered out. The fixed-interval builder resolves group actors per arm and+ stays allowed."""++ code = "retention_data_warehouse_24_hour_windows_group_aggregation_unsupported"++ def validate(self, context: QueryValidationContext[RetentionQuery]) -> None:+ if context.query.aggregation_group_type_index is None:+ return+ retention_filter = context.query.retentionFilter+ if retention_filter.timeWindowMode != "24_hour_windows":+ return+ has_data_warehouse_series = any(+ entity is not None and entity.type == EntityType.DATA_WAREHOUSE+ for entity in (retention_filter.targetEntity, retention_filter.returningEntity)+ )+ if has_data_warehouse_series:+ raise ValidationError(+ "Group aggregation is not supported for 24 hour windows with a data warehouse series.",+ code=self.code,+ )+++class DisallowPropertyAggregationWith24HourWindows:+ """The 24-hour-window builder never emits the retention_value column that sum/avg aggregation reads in the+ outer query."""++ code = "retention_24_hour_windows_property_aggregation_unsupported"++ def validate(self, context: QueryValidationContext[RetentionQuery]) -> None:+ retention_filter = context.query.retentionFilter+ if retention_filter.timeWindowMode != "24_hour_windows":+ return+ has_property_aggregation = (+ retention_filter.aggregationType in (AggregationType.SUM, AggregationType.AVG)+ and retention_filter.aggregationProperty+ )+ if has_property_aggregation:+ raise ValidationError(+ "Sum and average aggregation are not supported for 24 hour windows.",+ code=self.code,+ )diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambrnew file mode 100644index 000000000000..dcabadec30d8--- /dev/null+++ b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr@@ -0,0 +1,91 @@+# serializer version: 1+# name: TestRetentionDataWarehouse24hWindow.test_first_time_events_start_dwh_return_24h_window+ '''+ SELECT actor_activity.start_interval_index AS start_event_matching_interval,+ actor_activity.intervals_from_base AS intervals_from_base,+ count(DISTINCT actor_activity.actor_id) AS count+ FROM+ (SELECT actors_with_t0.actor_id AS actor_id,+ floor(divide(dateDiff('hour', assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), actors_with_t0.t_0), 24)) AS start_interval_index,+ arrayJoin(arrayDistinct(arrayConcat([0], arrayFilter(x -> ifNull(greaterOrEquals(x, 0), 0), groupUniqArray(if(ifNull(greaterOrEquals(return_events.timestamp, actors_with_t0.t_0), 0), floor(divide(dateDiff('hour', actors_with_t0.t_0, return_events.timestamp), 24)), -1)))))) AS intervals_from_base+ FROM+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,+ if(and(greaterOrEquals(minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$signup')), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$signup')), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$signup')), NULL) AS t_0+ FROM events+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) 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(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$signup'))+ GROUP BY actor_id+ HAVING isNotNull(t_0)) AS actors_with_t0+ LEFT JOIN+ (SELECT posthog_test_warehouse_renewals_ft.person_id AS actor_id,+ toTimeZone(posthog_test_warehouse_renewals_ft.occurred_at, 'UTC') AS timestamp+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse_24h_window/posthog_test_warehouse_renewals_ft/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_renewals_ft+ WHERE and(greaterOrEquals(posthog_test_warehouse_renewals_ft.occurred_at, toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(posthog_test_warehouse_renewals_ft.occurred_at, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))) AS return_events ON equals(actors_with_t0.actor_id, return_events.actor_id)+ GROUP BY actors_with_t0.actor_id,+ actors_with_t0.t_0) AS actor_activity+ GROUP BY start_event_matching_interval,+ intervals_from_base+ ORDER BY start_event_matching_interval ASC,+ intervals_from_base ASC+ LIMIT 100000 SETTINGS format_csv_allow_double_quotes=1,+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=23622320128,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestRetentionDataWarehouse24hWindow.test_same_table_dwh_start_and_return_24h_window+ '''+ SELECT actor_activity.start_interval_index AS start_event_matching_interval,+ actor_activity.intervals_from_base AS intervals_from_base,+ count(DISTINCT actor_activity.actor_id) AS count+ FROM+ (SELECT actors_with_t0.actor_id AS actor_id,+ floor(divide(dateDiff('hour', assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), actors_with_t0.t_0), 24)) AS start_interval_index,+ arrayJoin(arrayDistinct(arrayConcat([0], arrayFilter(x -> ifNull(greaterOrEquals(x, 0), 0), groupUniqArray(if(greaterOrEquals(return_events.timestamp, actors_with_t0.t_0), floor(divide(dateDiff('hour', actors_with_t0.t_0, return_events.timestamp), 24)), -1)))))) AS intervals_from_base+ FROM+ (SELECT posthog_test_warehouse_activity.person_id AS actor_id,+ min(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC')) AS t_0+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse_24h_window/posthog_test_warehouse_activity/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity+ WHERE and(equals(posthog_test_warehouse_activity.activity_type, 'signed_up'), and(greaterOrEquals(posthog_test_warehouse_activity.occurred_at, toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(posthog_test_warehouse_activity.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))+ GROUP BY actor_id) AS actors_with_t0+ LEFT JOIN+ (SELECT posthog_test_warehouse_activity.person_id AS actor_id,+ toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC') AS timestamp+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse_24h_window/posthog_test_warehouse_activity/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity+ WHERE and(equals(posthog_test_warehouse_activity.activity_type, 'renewed'), and(greaterOrEquals(posthog_test_warehouse_activity.occurred_at, toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(posthog_test_warehouse_activity.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))) AS return_events ON equals(actors_with_t0.actor_id, return_events.actor_id)+ GROUP BY actors_with_t0.actor_id,+ actors_with_t0.t_0) AS actor_activity+ GROUP BY start_event_matching_interval,+ intervals_from_base+ ORDER BY start_event_matching_interval ASC,+ intervals_from_base ASC+ LIMIT 100000 SETTINGS format_csv_allow_double_quotes=1,+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=23622320128,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.py b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.pynew file mode 100644index 000000000000..23b38aa5af8e--- /dev/null+++ b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.py@@ -0,0 +1,582 @@+import csv+import tempfile+from pathlib import Path++from posthog.test.base import (+ APIBaseTest,+ ClickhouseTestMixin,+ _create_event,+ _create_person,+ flush_persons_and_events,+ snapshot_clickhouse_queries,+)++from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.hogql.query import execute_hogql_query++from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner++from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv++TEST_BUCKET = "test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse_24h_window"++ACTIVITY_TABLE_COLUMNS = {+ "id": "Int64",+ "person_id": "UUID",+ "activity_type": "String",+ "occurred_at": "DateTime64(3, 'UTC')",+}+++def _signed_up_entity(table_name: str) -> dict:+ return {+ "id": table_name,+ "name": table_name,+ "type": "data_warehouse",+ "table_name": table_name,+ "aggregation_target_field": "person_id",+ "timestamp_field": "occurred_at",+ "properties": [{"key": "activity_type", "value": "signed_up", "operator": "exact", "type": "data_warehouse"}],+ }+++def _renewed_entity(table_name: str) -> dict:+ return {+ "id": table_name,+ "name": table_name,+ "type": "data_warehouse",+ "table_name": table_name,+ "aggregation_target_field": "person_id",+ "timestamp_field": "occurred_at",+ "properties": [{"key": "activity_type", "value": "renewed", "operator": "exact", "type": "data_warehouse"}],+ }+++class TestRetentionDataWarehouse24hWindow(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.cleanup_fns = []+ self.temp_dirs = []++ def tearDown(self):+ for cleanup in self.cleanup_fns:+ cleanup()+ for temp_dir in self.temp_dirs:+ temp_dir.cleanup()+ super().tearDown()++ def _write_csv(self, filename: str, header: list[str], rows: list[list[object]]) -> Path:+ temp_dir = tempfile.TemporaryDirectory()+ self.temp_dirs.append(temp_dir)+ path = Path(temp_dir.name) / filename+ with open(path, "w", newline="") as csv_file:+ writer = csv.writer(csv_file)+ writer.writerow(header)+ writer.writerows(rows)+ return path++ def _create_people(self) -> dict[str, str]:+ person_ids = {+ "user-1": "00000000-0000-0000-0000-000000000001",+ "user-2": "00000000-0000-0000-0000-000000000002",+ "user-3": "00000000-0000-0000-0000-000000000003",+ "user-4": "00000000-0000-0000-0000-000000000004",+ }+ for distinct_id, person_id in person_ids.items():+ _create_person(team=self.team, distinct_ids=[distinct_id], uuid=person_id)+ flush_persons_and_events()+ return person_ids++ def _create_data_warehouse_table(+ self,+ *,+ filename: str,+ table_name: str,+ header: list[str],+ rows: list[list[object]],+ table_columns: dict[str, str],+ ) -> str:+ csv_path = self._write_csv(filename, header, rows)+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(+ csv_path=csv_path,+ table_name=table_name,+ table_columns=table_columns,+ test_bucket=TEST_BUCKET,+ team=self.team,+ )+ self.cleanup_fns.append(cleanup)+ return table.name++ def run_query(self, query: dict) -> list[dict]:+ runner = RetentionQueryRunner(team=self.team, query=query)+ return runner.calculate().model_dump()["results"]++ @staticmethod+ def _row(result: list[dict], label: str) -> dict:+ return next(row for row in result if row["label"] == label)++ @snapshot_clickhouse_queries+ def test_same_table_dwh_start_and_return_24h_window(self):+ person_ids = self._create_people()+ activity_table = self._create_data_warehouse_table(+ filename="warehouse_activity.csv",+ table_name="warehouse_activity",+ header=["id", "person_id", "activity_type", "occurred_at"],+ rows=[+ [1, person_ids["user-1"], "signed_up", "2025-01-01 09:00:00"],+ [2, person_ids["user-2"], "signed_up", "2025-01-01 10:00:00"],+ [3, person_ids["user-3"], "signed_up", "2025-01-02 09:00:00"],+ [4, person_ids["user-4"], "signed_up", "2025-01-02 10:00:00"],+ [5, person_ids["user-1"], "renewed", "2025-01-02 12:00:00"], # 27h after t_0 -> interval 1+ [6, person_ids["user-2"], "renewed", "2025-01-03 12:00:00"], # 50h after t_0 -> interval 2+ [7, person_ids["user-3"], "renewed", "2025-01-03 13:00:00"], # 28h after t_0 -> interval 1+ # user-4 signs up but never renews -> must still appear in interval 0 (LEFT JOIN preservation)+ ],+ table_columns=ACTIVITY_TABLE_COLUMNS,+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": _signed_up_entity(activity_table),+ "returningEntity": _renewed_entity(activity_table),+ },+ }+ )++ # Day 0 cohort = user-1 (t_0 09:00) + user-2 (t_0 10:00), both signed up on 2025-01-01.+ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], 2) # interval 0: both+ self.assertEqual(day_0["values"][1]["count"], 1) # interval 1: user-1 (renewed +27h)+ self.assertEqual(day_0["values"][2]["count"], 1) # interval 2: user-2 (renewed +50h)+ self.assertEqual(day_0["values"][3]["count"], 0)++ # Day 1 cohort = user-3 (t_0 09:00) + user-4 (t_0 10:00), both signed up on 2025-01-02.+ day_1 = self._row(result, "Day 1")+ self.assertEqual(day_1["values"][0]["count"], 2) # interval 0: both (user-4 has no renewal but still counts)+ self.assertEqual(day_1["values"][1]["count"], 1) # interval 1: user-3 (renewed +28h)+ self.assertEqual(day_1["values"][2]["count"], 0)++ def _create_events(self, rows: list[tuple[str, str, str]]) -> None:+ for distinct_id, event, timestamp in rows:+ _create_event(team=self.team, event=event, distinct_id=distinct_id, timestamp=timestamp)+ flush_persons_and_events()++ def _create_renewals_table(self, table_name: str, rows: list[list[object]]) -> str:+ # Single-purpose table (every row is a renewal), so the retention entity needs no property filter — exercises+ # the no-property data warehouse return predicate (constant True) where >= t_0 is the only join discriminator.+ return self._create_data_warehouse_table(+ filename=f"{table_name}.csv",+ table_name=table_name,+ header=["id", "person_id", "occurred_at"],+ rows=rows,+ table_columns={"id": "Int64", "person_id": "UUID", "occurred_at": "DateTime64(3, 'UTC')"},+ )++ @staticmethod+ def _renewals_entity(table_name: str) -> dict:+ return {+ "id": table_name,+ "name": table_name,+ "type": "data_warehouse",+ "table_name": table_name,+ "aggregation_target_field": "person_id",+ "timestamp_field": "occurred_at",+ }++ def test_events_start_dwh_return_24h_window(self):+ person_ids = self._create_people()+ self._create_events(+ [+ ("user-1", "$signup", "2025-01-01 09:00:00"),+ ("user-2", "$signup", "2025-01-01 10:00:00"),+ ]+ )+ renewals_table = self._create_renewals_table(+ "warehouse_renewals_a",+ rows=[+ [1, person_ids["user-1"], "2025-01-02 12:00:00"], # 27h after t_0 -> interval 1+ # user-2 never renews -> still counts in interval 0 (no-property DWH return + LEFT JOIN)+ ],+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": {"id": "$signup", "name": "$signup", "type": "events"},+ "returningEntity": self._renewals_entity(renewals_table),+ },+ }+ )++ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], 2) # interval 0: user-1 + user-2+ self.assertEqual(day_0["values"][1]["count"], 1) # interval 1: user-1+ self.assertEqual(day_0["values"][2]["count"], 0)++ def test_dwh_start_events_return_24h_window(self):+ person_ids = self._create_people()+ signups_table = self._create_renewals_table(+ "warehouse_signups_b",+ rows=[+ [1, person_ids["user-1"], "2025-01-01 09:00:00"],+ [2, person_ids["user-2"], "2025-01-02 09:00:00"],+ ],+ )+ self._create_events(+ [+ ("user-1", "$renewed", "2025-01-02 12:00:00"), # 27h after t_0 -> interval 1+ # user-2 never renews+ ]+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": self._renewals_entity(signups_table),+ "returningEntity": {"id": "$renewed", "name": "$renewed", "type": "events"},+ },+ }+ )++ day_0 = self._row(result, "Day 0") # user-1 signed up 2025-01-01+ self.assertEqual(day_0["values"][0]["count"], 1)+ self.assertEqual(day_0["values"][1]["count"], 1) # renewed +27h++ day_1 = self._row(result, "Day 1") # user-2 signed up 2025-01-02, never renews+ self.assertEqual(day_1["values"][0]["count"], 1)+ self.assertEqual(day_1["values"][1]["count"], 0)++ def test_dwh_start_events_return_with_property_filter_24h_window(self):+ person_ids = self._create_people()+ signups_table = self._create_renewals_table(+ "warehouse_signups_d",+ rows=[+ [1, person_ids["user-1"], "2025-01-01 09:00:00"],+ [2, person_ids["user-2"], "2025-01-01 10:00:00"],+ ],+ )+ _create_event(+ team=self.team,+ event="$renewed",+ distinct_id="user-1",+ timestamp="2025-01-02 12:00:00", # 27h after t_0 -> interval 1+ properties={"plan": "pro"},+ )+ _create_event(+ team=self.team,+ event="$renewed",+ distinct_id="user-2",+ timestamp="2025-01-02 12:00:00", # matches the event but not the property filter+ properties={"plan": "free"},+ )+ flush_persons_and_events()++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": self._renewals_entity(signups_table),+ "returningEntity": {+ "id": "$renewed",+ "name": "$renewed",+ "type": "events",+ "properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "event"}],+ },+ },+ }+ )++ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], 2) # interval 0: both signed up on 2025-01-01+ self.assertEqual(day_0["values"][1]["count"], 1) # interval 1: only user-1's plan=pro renewal counts+ self.assertEqual(day_0["values"][2]["count"], 0)++ def test_two_different_dwh_tables_24h_window(self):+ person_ids = self._create_people()+ signups_table = self._create_renewals_table(+ "warehouse_signups_c",+ rows=[+ [1, person_ids["user-1"], "2025-01-01 09:00:00"],+ [2, person_ids["user-2"], "2025-01-02 09:00:00"],+ ],+ )+ renewals_table = self._create_renewals_table(+ "warehouse_renewals_c",+ rows=[+ [1, person_ids["user-1"], "2025-01-02 12:00:00"], # 27h after t_0 -> interval 1+ ],+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": self._renewals_entity(signups_table),+ "returningEntity": self._renewals_entity(renewals_table),+ },+ }+ )++ day_0 = self._row(result, "Day 0") # user-1+ self.assertEqual(day_0["values"][0]["count"], 1)+ self.assertEqual(day_0["values"][1]["count"], 1)++ day_1 = self._row(result, "Day 1") # user-2, no renewal+ self.assertEqual(day_1["values"][0]["count"], 1)+ self.assertEqual(day_1["values"][1]["count"], 0)++ @parameterized.expand(+ [+ # first-ever excludes user-2: their earliest activity is a renewal, not a signup, so they never+ # qualify as a first-ever signup. first-time cohorts user-2 on their first signup regardless.+ ("retention_first_ever_occurrence", 1, 1),+ ("retention_first_time", 2, 2),+ ]+ )+ def test_first_time_modes_dwh_start_24h_window(+ self, retention_type: str, expected_interval_0: int, expected_interval_1: int+ ):+ person_ids = self._create_people()+ activity_table = self._create_data_warehouse_table(+ filename="warehouse_ft_activity.csv",+ table_name="warehouse_ft_activity",+ header=["id", "person_id", "activity_type", "occurred_at"],+ rows=[+ [1, person_ids["user-1"], "signed_up", "2025-01-01 09:00:00"],+ [2, person_ids["user-1"], "renewed", "2025-01-02 12:00:00"], # +27h from 09:00 -> interval 1+ [3, person_ids["user-2"], "renewed", "2025-01-01 08:00:00"], # pre-signup activity+ [4, person_ids["user-2"], "signed_up", "2025-01-01 10:00:00"],+ [5, person_ids["user-2"], "renewed", "2025-01-02 11:00:00"], # +25h from 10:00 -> interval 1+ ],+ table_columns=ACTIVITY_TABLE_COLUMNS,+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "retentionType": retention_type,+ "targetEntity": _signed_up_entity(activity_table),+ "returningEntity": _renewed_entity(activity_table),+ },+ }+ )++ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], expected_interval_0)+ self.assertEqual(day_0["values"][1]["count"], expected_interval_1)++ def test_first_time_dwh_start_excludes_anchor_before_window_24h(self):+ person_ids = self._create_people()+ activity_table = self._create_data_warehouse_table(+ filename="warehouse_ft_guard.csv",+ table_name="warehouse_ft_guard",+ header=["id", "person_id", "activity_type", "occurred_at"],+ rows=[+ [1, person_ids["user-1"], "signed_up", "2024-12-30 09:00:00"], # anchor before date_from+ [2, person_ids["user-1"], "renewed", "2025-01-02 12:00:00"],+ [3, person_ids["user-2"], "signed_up", "2025-01-01 09:00:00"], # anchor in window+ [4, person_ids["user-2"], "renewed", "2025-01-02 12:00:00"], # +27h -> interval 1+ ],+ table_columns=ACTIVITY_TABLE_COLUMNS,+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "retentionType": "retention_first_time",+ "targetEntity": _signed_up_entity(activity_table),+ "returningEntity": _renewed_entity(activity_table),+ },+ }+ )++ # user-1's first signup (2024-12-30) is before date_from, so the window guard nulls their anchor and they+ # are excluded entirely — only user-2 is cohorted, and no spurious cohort appears from a negative interval.+ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], 1)+ self.assertEqual(day_0["values"][1]["count"], 1)+ self.assertEqual(sum(row["values"][0]["count"] for row in result), 1)++ @parameterized.expand(+ [+ (+ "cumulative",+ {"cumulative": True},+ {},+ "Cumulative retention is not supported for 24 hour windows.",+ ),+ (+ "breakdown",+ {},+ {"breakdownFilter": {"breakdown": "$browser", "breakdown_type": "event"}},+ "Breakdowns are not supported for 24 hour windows with a data warehouse series.",+ ),+ (+ "group_aggregation",+ {},+ {"aggregation_group_type_index": 0},+ "Group aggregation is not supported for 24 hour windows with a data warehouse series.",+ ),+ (+ "property_aggregation",+ {"aggregationType": "sum", "aggregationProperty": "amount"},+ {},+ "Sum and average aggregation are not supported for 24 hour windows.",+ ),+ ]+ )+ def test_unsupported_dwh_24h_window_combinations_are_rejected(+ self, name: str, retention_filter_extra: dict, query_extra: dict, expected_error: str+ ):+ activity_table = self._create_renewals_table(f"warehouse_rejected_{name}", rows=[])+ with self.assertRaisesMessage(ValidationError, expected_error):+ self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": self._renewals_entity(activity_table),+ "returningEntity": self._renewals_entity(activity_table),+ **retention_filter_extra,+ },+ **query_extra,+ }+ )++ @parameterized.expand(+ [+ ("missing_aggregation_target_field", "aggregation_target_field", "requires aggregation_target_field"),+ ("missing_timestamp_field", "timestamp_field", "requires table_name and timestamp_field"),+ ]+ )+ def test_incomplete_dwh_entity_is_rejected_with_validation_error(+ self, _name: str, missing_field: str, expected_error: str+ ):+ # The exception type is the contract: ValidationError maps to HTTP 400 at the API, a bare ValueError to a+ # 500. The error raises while building the query, so no warehouse table fixture is needed.+ entity = self._renewals_entity("warehouse_incomplete")+ del entity[missing_field]++ runner = RetentionQueryRunner(+ team=self.team,+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": entity,+ "returningEntity": self._renewals_entity("warehouse_incomplete"),+ },+ },+ )++ with self.assertRaisesMessage(ValidationError, expected_error):+ runner.to_query()++ def test_actors_query_filters_to_selected_interval_24h_window(self):+ person_ids = self._create_people()+ activity_table = self._create_data_warehouse_table(+ filename="warehouse_actors_activity.csv",+ table_name="warehouse_actors_activity",+ header=["id", "person_id", "activity_type", "occurred_at"],+ rows=[+ [1, person_ids["user-1"], "signed_up", "2025-01-01 09:00:00"],+ [2, person_ids["user-2"], "signed_up", "2025-01-01 10:00:00"],+ [3, person_ids["user-3"], "signed_up", "2025-01-02 09:00:00"],+ [4, person_ids["user-4"], "signed_up", "2025-01-02 10:00:00"],+ [5, person_ids["user-1"], "renewed", "2025-01-02 12:00:00"],+ ],+ table_columns=ACTIVITY_TABLE_COLUMNS,+ )++ runner = RetentionQueryRunner(+ team=self.team,+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "targetEntity": _signed_up_entity(activity_table),+ "returningEntity": _renewed_entity(activity_table),+ },+ },+ )+ response = execute_hogql_query(query=runner.to_actors_query(interval=1), team=self.team)++ # Only the Day 1 cohort (user-3 and user-4); without the start_interval_index filter every cohort leaks in.+ self.assertEqual(+ sorted(str(row[0]) for row in response.results),+ [person_ids["user-3"], person_ids["user-4"]],+ )++ @snapshot_clickhouse_queries+ def test_first_time_events_start_dwh_return_24h_window(self):+ person_ids = self._create_people()+ self._create_events(+ [+ ("user-1", "$browse", "2024-12-28 08:00:00"), # unrelated activity must not affect the anchor+ ("user-1", "$signup", "2024-12-30 09:00:00"), # first signup, before the window+ ("user-1", "$signup", "2025-01-03 09:00:00"), # repeat signup in window must not re-cohort+ ("user-2", "$signup", "2025-01-01 10:00:00"), # first signup, in window+ ]+ )+ renewals_table = self._create_renewals_table(+ "warehouse_renewals_ft",+ rows=[+ [1, person_ids["user-2"], "2025-01-02 13:00:00"], # 27h after t_0 -> interval 1+ ],+ )++ result = self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": {+ "period": "Day",+ "totalIntervals": 4,+ "timeWindowMode": "24_hour_windows",+ "retentionType": "retention_first_time",+ "targetEntity": {"id": "$signup", "name": "$signup", "type": "events"},+ "returningEntity": self._renewals_entity(renewals_table),+ },+ }+ )++ # user-1's first matching signup predates the window, so the guard nulls their anchor and the repeat+ # signup inside the window must not resurrect them. Only user-2 is cohorted (Day 0, returning +27h).+ day_0 = self._row(result, "Day 0")+ self.assertEqual(day_0["values"][0]["count"], 1)+ self.assertEqual(day_0["values"][1]["count"], 1)+ self.assertEqual(sum(row["values"][0]["count"] for row in result), 1)diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py b/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.pyindex 3a23aa2f4263..bf6646b2d4fb 100644--- a/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py+++ b/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py@@ -4,9 +4,14 @@ from unittest.mock import MagicMockfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError-from posthog.schema import AggregationType, EntityType, RetentionFilter, RetentionQuery, TimeWindowMode+from posthog.schema import AggregationType, BreakdownFilter, EntityType, RetentionFilter, RetentionQuery, TimeWindowMode-from posthog.hogql_queries.insights.retention.retention_validation_rules import DisallowCumulativeWith24HourWindows+from posthog.hogql_queries.insights.retention.retention_validation_rules import (+ DisallowBreakdownsWithDataWarehouse24HourWindows,+ DisallowCumulativeWith24HourWindows,+ DisallowGroupAggregationWithDataWarehouse24HourWindows,+ DisallowPropertyAggregationWith24HourWindows,+)from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettingsfrom posthog.hogql_queries.validation.validation import QueryValidationContext@@ -47,6 +52,44 @@ class TestRetentionValidationRules(BaseTest):self.assertIn("Cumulative retention is not supported for 24 hour windows.", str(context.exception))+ @parameterized.expand(+ [+ ("dwh_24h_windows_breakdown", True, TimeWindowMode.FIELD_24_HOUR_WINDOWS, True, True),+ ("dwh_24h_windows_no_breakdown", True, TimeWindowMode.FIELD_24_HOUR_WINDOWS, False, False),+ ("dwh_default_window_breakdown", True, None, True, False),+ ("events_24h_windows_breakdown", False, TimeWindowMode.FIELD_24_HOUR_WINDOWS, True, False),+ ]+ )+ def test_disallow_breakdowns_with_data_warehouse_24h_windows(+ self,+ _name: str,+ use_data_warehouse_entity: bool,+ time_window_mode: TimeWindowMode | None,+ has_breakdown: bool,+ raises_error: bool,+ ) -> None:+ query = RetentionQuery(+ retentionFilter=RetentionFilter(+ timeWindowMode=time_window_mode,+ targetEntity=self._data_warehouse_entity() if use_data_warehouse_entity else None,+ ),+ breakdownFilter=BreakdownFilter(breakdown="$browser", breakdown_type="event") if has_breakdown else None,+ )++ if not raises_error:+ DisallowBreakdownsWithDataWarehouse24HourWindows().validate(self._context(query))+ return++ with self.assertRaises(ValidationError) as context:+ DisallowBreakdownsWithDataWarehouse24HourWindows().validate(self._context(query))++ self.assertIn(+ "Breakdowns are not supported for 24 hour windows with a data warehouse series.", str(context.exception)+ )+ self.assertEqual(+ context.exception.get_codes(), ["retention_data_warehouse_24_hour_windows_breakdowns_unsupported"]+ )+@parameterized.expand([(@@ -91,3 +134,80 @@ class TestRetentionValidationRules(BaseTest):)DisallowUnsupportedDataWarehouseSettings().validate(self._context(query))++ @parameterized.expand(+ [+ ("groups_with_dwh_target_24h", 0, True, False, TimeWindowMode.FIELD_24_HOUR_WINDOWS, True),+ ("groups_with_dwh_return_24h", 0, False, True, TimeWindowMode.FIELD_24_HOUR_WINDOWS, True),+ ("groups_without_dwh_series_24h", 0, False, False, TimeWindowMode.FIELD_24_HOUR_WINDOWS, False),+ ("no_groups_with_dwh_series_24h", None, True, True, TimeWindowMode.FIELD_24_HOUR_WINDOWS, False),+ ("groups_with_dwh_series_default_window", 0, True, True, None, False),+ ]+ )+ def test_disallow_group_aggregation_with_data_warehouse_24h_windows(+ self,+ _name: str,+ group_type_index: int | None,+ dwh_target: bool,+ dwh_return: bool,+ time_window_mode: TimeWindowMode | None,+ raises_error: bool,+ ) -> None:+ query = RetentionQuery(+ aggregation_group_type_index=group_type_index,+ retentionFilter=RetentionFilter(+ timeWindowMode=time_window_mode,+ targetEntity=self._data_warehouse_entity() if dwh_target else None,+ returningEntity=self._data_warehouse_entity() if dwh_return else None,+ ),+ )++ if not raises_error:+ DisallowGroupAggregationWithDataWarehouse24HourWindows().validate(self._context(query))+ return++ with self.assertRaises(ValidationError) as context:+ DisallowGroupAggregationWithDataWarehouse24HourWindows().validate(self._context(query))++ self.assertIn(+ "Group aggregation is not supported for 24 hour windows with a data warehouse series.",+ str(context.exception),+ )+ self.assertEqual(+ context.exception.get_codes(), ["retention_data_warehouse_24_hour_windows_group_aggregation_unsupported"]+ )++ @parameterized.expand(+ [+ ("sum_24h_windows", AggregationType.SUM, "amount", TimeWindowMode.FIELD_24_HOUR_WINDOWS, True),+ ("avg_24h_windows", AggregationType.AVG, "amount", TimeWindowMode.FIELD_24_HOUR_WINDOWS, True),+ ("count_24h_windows", AggregationType.COUNT, None, TimeWindowMode.FIELD_24_HOUR_WINDOWS, False),+ ("sum_without_property_24h", AggregationType.SUM, None, TimeWindowMode.FIELD_24_HOUR_WINDOWS, False),+ ("sum_default_window", AggregationType.SUM, "amount", None, False),+ ]+ )+ def test_disallow_property_aggregation_with_24h_windows(+ self,+ _name: str,+ aggregation_type: AggregationType,+ aggregation_property: str | None,+ time_window_mode: TimeWindowMode | None,+ raises_error: bool,+ ) -> None:+ query = RetentionQuery(+ retentionFilter=RetentionFilter(+ timeWindowMode=time_window_mode,+ aggregationType=aggregation_type,+ aggregationProperty=aggregation_property,+ )+ )++ if not raises_error:+ DisallowPropertyAggregationWith24HourWindows().validate(self._context(query))+ return++ with self.assertRaises(ValidationError) as context:+ DisallowPropertyAggregationWith24HourWindows().validate(self._context(query))++ self.assertIn("Sum and average aggregation are not supported for 24 hour windows.", str(context.exception))+ self.assertEqual(context.exception.get_codes(), ["retention_24_hour_windows_property_aggregation_unsupported"])diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex 72f81d3e284a..48f88edbe700 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -4,11 +4,15 @@ from parameterized import parameterizedfrom posthog.schema import (DataWarehouseNode,+ EntityType,EventsNode,FunnelsDataWarehouseNode,HogQLQuery,InsightActorsQuery,LifecycleDataWarehouseNode,+ RetentionEntity,+ RetentionFilter,+ RetentionQuery,TrendsQuery,)@@ -44,6 +48,16 @@ class TestQueriedAccessControlledResources(BaseTest):timestamp_field="timestamp",)+ @staticmethod+ def _dw_retention_entity() -> RetentionEntity:+ return RetentionEntity(+ id="some_dw_table",+ type=EntityType.DATA_WAREHOUSE,+ table_name="some_dw_table",+ timestamp_field="timestamp",+ aggregation_target_field="person_id",+ )+@parameterized.expand([("system_table", "select * from system.notebooks", {"notebook"}),@@ -112,6 +126,22 @@ class TestQueriedAccessControlledResources(BaseTest):query = InsightActorsQuery(source=TrendsQuery(series=[self._dw_node()]))assert queried_access_controlled_resources(query, self.team) == {"warehouse_table", "warehouse_view"}+ @parameterized.expand(["targetEntity", "returningEntity"])+ def test_retention_query_with_data_warehouse_entity(self, entity_field):+ # Retention reads warehouse tables through RetentionEntity rather than a DataWarehouseNode; missing+ # it here would serve an allowed user's cached warehouse rows to a denied user on a cache hit.+ query = RetentionQuery(retentionFilter=RetentionFilter(**{entity_field: self._dw_retention_entity()}))+ assert queried_access_controlled_resources(query, self.team) == {"warehouse_table", "warehouse_view"}++ def test_retention_query_without_data_warehouse_entity(self):+ query = RetentionQuery(+ retentionFilter=RetentionFilter(+ targetEntity=RetentionEntity(id="$pageview", type=EntityType.EVENTS),+ returningEntity=RetentionEntity(id="$pageview", type=EntityType.EVENTS),+ )+ )+ assert queried_access_controlled_resources(query, self.team) == set()+def test_references_data_warehouse_covers_all_variants_and_nesting(self):variants = [DataWarehouseNode(id="t", id_field="id", distinct_id_field="d", table_name="t", timestamp_field="ts"),