: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): add feature flag for variant and compare in tests (#57119)
Thomas Obermüller1dc283df9827
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex bc59cd970607..d7f8a68683db 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4733,7 +4733,7 @@ snapshots:scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.URrKOLP9uUjbKWcui2yOA7hm_JsXsbkAlOcWJshoQrIscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:- hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.KSiw8WpvjWXIDh87ExL4cPnopVJlTXvzU8N8ruh6Hi8+ hash: v1.k794b7964.6c391cbc05b64230fbd8defdbb960b131fd433409817497873fb9ffc705cd360.EIwByuofuT77yP259A9ffqfjSFwW9MrUDOvsZNA_aZMscenes-app-insights-funnels--funnel-time-to-convert--dark:hash: v1.k794b7964.d64808d2bfc36017f89b57feeaa373e20188738a622801207fa1beb59d02fdd9.cFuKF_Ow887Z3X3BoNhtTvkUWY2vips9HDBe-B02eQEscenes-app-insights-funnels--funnel-time-to-convert--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 467e1de96995..8fdac21822db 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -3141,7 +3141,7 @@"aggregationPropertyType": {"default": "event","description": "The type of property to aggregate on (event or person). Defaults to event.",- "enum": ["event", "person"],+ "enum": ["event", "person", "data_warehouse"],"type": "string"},"aggregationType": {diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.tsindex 17495281ea98..4ba1f2862c20 100644--- a/frontend/src/queries/schema/schema-assistant-queries.ts+++ b/frontend/src/queries/schema/schema-assistant-queries.ts@@ -888,7 +888,7 @@ export interface AssistantRetentionFilter {* The type of property to aggregate on (event or person). Defaults to event.* @default event*/- aggregationPropertyType?: 'event' | 'person'+ aggregationPropertyType?: 'event' | 'person' | 'data_warehouse'}export interface AssistantRetentionQuery extends AssistantInsightsQueryBase {diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.pyindex c0a5616a0ee9..d31b5f3c1bed 100644--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py@@ -1,4 +1,6 @@-from typing import Literal+from typing import TYPE_CHECKING, Literal++import posthoganalyticsfrom posthog.schema import EntityType, RetentionEntity@@ -9,6 +11,35 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql_queries.insights.retention.retention_base_query_builder import RetentionBaseQueryBuilderfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID+if TYPE_CHECKING:+ from posthog.models import Team+++RETENTION_FIXED_INTERVAL_BASE_QUERY_DWH_VARIANT_FLAG = "retention-fixed-interval-base-query-dwh-variant"+++def retention_fixed_interval_base_query_use_dwh_variant(team: "Team") -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ RETENTION_FIXED_INTERVAL_BASE_QUERY_DWH_VARIANT_FLAG,+ str(team.uuid),+ groups={+ "organization": str(team.organization_id),+ "project": str(team.id),+ },+ group_properties={+ "organization": {+ "id": str(team.organization_id),+ },+ "project": {+ "id": str(team.id),+ },+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):def build_base_query(@@ -20,7 +51,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):self.start_event.type == EntityType.DATA_WAREHOUSE or self.return_event.type == EntityType.DATA_WAREHOUSE)- if has_data_warehouse_series:+ if has_data_warehouse_series or retention_fixed_interval_base_query_use_dwh_variant(self.team):return self.build_base_query_dwh(start_interval_index_filter=start_interval_index_filter,selected_breakdown_value=selected_breakdown_value,diff --git a/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py b/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.pynew file mode 100644index 000000000000..3893cf7ff443--- /dev/null+++ b/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py@@ -0,0 +1,76 @@+from collections.abc import Callable+from copy import deepcopy+from typing import Any, TypeVar, cast++from unittest.mock import patch++from posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS++RETENTION_BASE_QUERY_VARIANT_PATCH_PATH = (+ "posthog.hogql_queries.insights.retention.retention_base_query_fixed."+ "retention_fixed_interval_base_query_use_dwh_variant"+)+SKIP_RETENTION_BASE_QUERY_VARIANT_COMPARISON_ATTR = "_skip_retention_base_query_variant_comparison"++Result = TypeVar("Result")+TestFunction = TypeVar("TestFunction", bound=Callable[..., Any])+++def skip_retention_base_query_variant_comparison(test_fn: TestFunction) -> TestFunction:+ setattr(test_fn, SKIP_RETENTION_BASE_QUERY_VARIANT_COMPARISON_ATTR, True)+ return test_fn+++class RetentionBaseQueryVariantComparisonMixin:+ retention_base_query_variant_comparison_excluded_tests: set[str] = set()++ def calculate_with_retention_base_query_variant_comparison(+ self,+ query: dict[str, Any],+ calculate: Callable[[dict[str, Any]], Result],+ ) -> Result:+ legacy_query = deepcopy(query)+ with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=False):+ legacy_result = calculate(legacy_query)++ if not self.should_compare_retention_base_query_variants(query):+ return legacy_result++ dwh_variant_query = deepcopy(query)+ with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=True):+ dwh_variant_result = calculate(dwh_variant_query)++ cast(Any, self).assertEqual(dwh_variant_result, legacy_result)+ return legacy_result++ def should_compare_retention_base_query_variants(self, query: dict[str, Any]) -> bool:+ test_method_name = getattr(self, "_testMethodName", "")+ if test_method_name in self.retention_base_query_variant_comparison_excluded_tests:+ return False++ test_method = getattr(self, test_method_name, None)+ if getattr(test_method, SKIP_RETENTION_BASE_QUERY_VARIANT_COMPARISON_ATTR, False):+ return False++ return not self._query_uses_known_retention_base_query_variant_gap(query)++ def _query_uses_known_retention_base_query_variant_gap(self, query: dict[str, Any]) -> bool:+ retention_filter = cast(dict[str, Any], query.get("retentionFilter") or {})++ minimum_occurrences = retention_filter.get("minimumOccurrences") or 1+ if minimum_occurrences > 1:+ return True++ if retention_filter.get("retentionType") in {+ RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,+ RETENTION_FIRST_EVER_OCCURRENCE,+ }:+ return True++ if query.get("breakdownFilter"):+ return True++ if query.get("samplingFactor") is not None:+ return True++ return Falsediff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.pyindex 03f497cd0044..2aaa8ad5694d 100644--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py@@ -35,6 +35,9 @@ from posthog.constants import ()from posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner+from posthog.hogql_queries.insights.retention.test.retention_base_query_variant import (+ RetentionBaseQueryVariantComparisonMixin,+)from posthog.hogql_queries.insights.retention.test.utils import pad, pluckfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABELfrom posthog.models import Cohort@@ -78,7 +81,17 @@ def _create_events(team, user_and_timestamps, event="$pageview"):i += 1-class TestRetention(ClickhouseTestMixin, APIBaseTest):+class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixin, APIBaseTest):+ retention_base_query_variant_comparison_excluded_tests = {+ "test_month_interval_with_person_on_events_v2",+ "test_week_interval",+ "test_retention_event_action",+ "test_retention_with_user_properties_via_action",+ "test_timezones",+ "test_retention_aggregation_sum",+ "test_retention_aggregation_different_events_ignores_start_event_property_value",+ }+def teardown_method(self, method) -> None:if getattr(self, "cleanUpDataWarehouse", None):self.cleanUpDataWarehouse()@@ -99,28 +112,36 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):def run_query(self, query):if not query.get("retentionFilter"):query["retentionFilter"] = {}- runner = RetentionQueryRunner(team=self.team, query=query)- return runner.calculate().model_dump()["results"]++ def calculate(query_for_variant):+ runner = RetentionQueryRunner(team=self.team, query=query_for_variant)+ return runner.calculate().model_dump()["results"]++ return self.calculate_with_retention_base_query_variant_comparison(query, calculate)def run_actors_query(self, interval, query, select=None, search=None, breakdown=None):query["kind"] = "RetentionQuery"if not query.get("retentionFilter"):query["retentionFilter"] = {}- runner = ActorsQueryRunner(- team=self.team,- query={- "search": search,- "select": ["person", "appearances", *(select or [])],- "orderBy": ["length(appearances) DESC", "actor_id"],- "source": {- "kind": "InsightActorsQuery",- "interval": interval,- "source": query,- "breakdown": breakdown,++ def calculate(query_for_variant):+ runner = ActorsQueryRunner(+ team=self.team,+ query={+ "search": search,+ "select": ["person", "appearances", *(select or [])],+ "orderBy": ["length(appearances) DESC", "actor_id"],+ "source": {+ "kind": "InsightActorsQuery",+ "interval": interval,+ "source": query_for_variant,+ "breakdown": breakdown,+ },},- },- )- return runner.calculate().model_dump()["results"]+ )+ return runner.calculate().model_dump()["results"]++ return self.calculate_with_retention_base_query_variant_comparison(query, calculate)def test_retention_default(self):_create_person(team_id=self.team.pk, distinct_ids=["person1", "alias1"])@@ -5446,31 +5467,48 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):self.assertIn("properties", sql)-class TestClickhouseRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTest):+class TestClickhouseRetentionGroupAggregation(+ RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixin, APIBaseTest+):+ retention_base_query_variant_comparison_excluded_tests = {+ "test_groups_aggregating",+ "test_groups_aggregating_person_on_events",+ "test_limit_is_context_aware",+ "test_retention_24h_window_calculation",+ }+def run_query(self, query, *, limit_context: Optional[LimitContext] = None):if not query.get("retentionFilter"):query["retentionFilter"] = {}- runner = RetentionQueryRunner(team=self.team, query=query, limit_context=limit_context)- return runner.calculate().model_dump()["results"]++ def calculate(query_for_variant):+ runner = RetentionQueryRunner(team=self.team, query=query_for_variant, limit_context=limit_context)+ return runner.calculate().model_dump()["results"]++ return self.calculate_with_retention_base_query_variant_comparison(query, calculate)def run_actors_query(self, interval, query, select=None, actor="person", breakdown=None):query["kind"] = "RetentionQuery"if not query.get("retentionFilter"):query["retentionFilter"] = {}- runner = ActorsQueryRunner(- team=self.team,- query={- "select": [actor, "appearances", *(select or [])],- "orderBy": ["length(appearances) DESC", "actor_id"],- "source": {- "kind": "InsightActorsQuery",- "interval": interval,- "source": query,- "breakdown": breakdown,++ def calculate(query_for_variant):+ runner = ActorsQueryRunner(+ team=self.team,+ query={+ "select": [actor, "appearances", *(select or [])],+ "orderBy": ["length(appearances) DESC", "actor_id"],+ "source": {+ "kind": "InsightActorsQuery",+ "interval": interval,+ "source": query_for_variant,+ "breakdown": breakdown,+ },},- },- )- return runner.calculate().model_dump()["results"]+ )+ return runner.calculate().model_dump()["results"]++ return self.calculate_with_retention_base_query_variant_comparison(query, calculate)def _create_groups_and_events(self):create_group_type_mapping_without_created_at(diff --git a/posthog/schema.py b/posthog/schema.pyindex 493161c5c444..9aa7c904c1fc 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -641,6 +641,7 @@ class AssistantRecordingPropertyFilter4(BaseModel):class AggregationPropertyType(StrEnum):EVENT = "event"PERSON = "person"+ DATA_WAREHOUSE = "data_warehouse"class AggregationType(StrEnum):@@ -4238,12 +4239,6 @@ class RetentionEntityKind(StrEnum):EVENTS_NODE = "EventsNode"-class AggregationPropertyType1(StrEnum):- EVENT = "event"- PERSON = "person"- DATA_WAREHOUSE = "data_warehouse"--class RetentionPeriod(StrEnum):HOUR = "Hour"DAY = "Day"@@ -18001,8 +17996,8 @@ class RetentionFilter(BaseModel):default=None,description="The property to aggregate when aggregationType is sum or avg",)- aggregationPropertyType: AggregationPropertyType1 | None = Field(- default=AggregationPropertyType1.EVENT,+ aggregationPropertyType: AggregationPropertyType | None = Field(+ default=AggregationPropertyType.EVENT,description=("The type of property to aggregate on (event, person or data_warehouse). Defaults to event."),)aggregationType: AggregationType | None = Field(diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 1998dc2130e0..6bb568bda425 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -2046,9 +2046,9 @@ export interface RetentionQueryResponseApi {timings?: QueryTimingApi[] | null}-export type AggregationPropertyType1Api = (typeof AggregationPropertyType1Api)[keyof typeof AggregationPropertyType1Api]+export type AggregationPropertyTypeApi = (typeof AggregationPropertyTypeApi)[keyof typeof AggregationPropertyTypeApi]-export const AggregationPropertyType1Api = {+export const AggregationPropertyTypeApi = {Event: 'event',Person: 'person',DataWarehouse: 'data_warehouse',@@ -2172,7 +2172,7 @@ export interface RetentionFilterApi {/** The property to aggregate when aggregationType is sum or avg */aggregationProperty?: string | null/** The type of property to aggregate on (event, person or data_warehouse). Defaults to event. */- aggregationPropertyType?: AggregationPropertyType1Api | null+ aggregationPropertyType?: AggregationPropertyTypeApi | null/** The aggregation type to use for retention */aggregationType?: AggregationTypeApi | null/** Starting index used when labeling cohort columns (e.g. 0 for D0/D1/D2, 1 for D1/D2/D3). Display-only — does not affect retention calculations. */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex be41d70dde96..0d420865e314 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2398,10 +2398,10 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export type AggregationPropertyType1 = typeof AggregationPropertyType1[keyof typeof AggregationPropertyType1];+ export type AggregationPropertyType = typeof AggregationPropertyType[keyof typeof AggregationPropertyType];- export const AggregationPropertyType1 = {+ export const AggregationPropertyType = {Event: 'event',Person: 'person',DataWarehouse: 'data_warehouse',@@ -2510,7 +2510,7 @@ export namespace Schemas {/** The property to aggregate when aggregationType is sum or avg */aggregationProperty?: string | null;/** The type of property to aggregate on (event, person or data_warehouse). Defaults to event. */- aggregationPropertyType?: AggregationPropertyType1 | null;+ aggregationPropertyType?: AggregationPropertyType | null;/** The aggregation type to use for retention */aggregationType?: AggregationType | null;/** Starting index used when labeling cohort columns (e.g. 0 for D0/D1/D2, 1 for D1/D2/D3). Display-only — does not affect retention calculations. */diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex 0f1cf7404862..0e95fd46fa7e 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -804,7 +804,7 @@ const AssistantRetentionFilter = z.object({.describe('The event or person property to aggregate when aggregationType is sum or avg.').optional(),aggregationPropertyType: z- .enum(['event', 'person'])+ .enum(['event', 'person', 'data_warehouse']).describe('The type of property to aggregate on (event or person). Defaults to event.').default('event').optional(),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-retention.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-retention.jsonindex 139b6243e1fa..d38b8abd09da 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-retention.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-retention.json@@ -556,7 +556,7 @@"aggregationPropertyType": {"default": "event","description": "The type of property to aggregate on (event or person). Defaults to event.",- "enum": ["event", "person"],+ "enum": ["event", "person", "data_warehouse"],"type": "string"},"aggregationType": {