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.

chore(product-analytics): move retention and lifecycle query runners into the product (#91599)

Thomas Obermüllera7bd53ddc01e
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 37031879cad6..286f7150c5cb 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -21,17 +21,14 @@ from rest_framework import status
from posthog.schema import (
CachedEventsQueryResponse,
CachedHogQLQueryResponse,
- CachedRetentionQueryResponse,
EventPropertyFilter,
EventsQuery,
HogLanguage,
HogQLAutocomplete,
HogQLPropertyFilter,
HogQLQuery,
- MeanRetentionCalculation,
PersonPropertyFilter,
PropertyOperator,
- RetentionQuery,
)
from posthog.hogql.constants import LimitContext
@@ -1168,41 +1165,6 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
response = CachedHogQLQueryResponse.model_validate(api_response)
assert response.results[0][0] == variable_override_value
- @patch("posthog.api.query.process_query_model")
- def test_upgrades_query(self, mock_process_query):
- mock_process_query.return_value = CachedRetentionQueryResponse(
- cache_key="cache_123",
- is_cached=False,
- last_refresh="2023-10-16T12:00:00Z",
- next_allowed_client_refresh="2023-10-16T14:00:00Z",
- results=[],
- timezone="UTC",
- )
-
- self.client.post(
- f"/api/environments/{self.team.id}/query/",
- {
- "query": {
- "kind": "RetentionQuery",
- "retentionFilter": {
- "period": "Day",
- "totalIntervals": 8,
- "targetEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
- "returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
- "retentionType": "retention_first_time",
- "showMean": True,
- },
- },
- "client_query_id": "5d92fb51-5088-45e8-91b2-843aef3d69bd",
- },
- ).json()
-
- mock_process_query.assert_called_once()
- updated_query = mock_process_query.call_args.args[1]
- assert isinstance(updated_query, RetentionQuery)
- assert updated_query.version == 2
- assert updated_query.retentionFilter.meanRetentionCalculation == MeanRetentionCalculation.SIMPLE
-
class TestQueryRetrieve(APIBaseTest):
def setUp(self):
@@ -1372,25 +1334,6 @@ class TestQueryDraftSql(APIBaseTest):
hit_openai_mock.assert_called_once()
-class TestQueryUpgrade(APIBaseTest):
- def test_upgrades_valid_query(self):
- query = {"kind": "RetentionQuery", "retentionFilter": {"period": "Day", "totalIntervals": 7, "showMean": True}}
-
- response = self.client.post(f"/api/environments/{self.team.id}/query/upgrade/", {"query": query})
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(
- response.json(),
- {
- "query": {
- "kind": "RetentionQuery",
- "retentionFilter": {"meanRetentionCalculation": "simple", "period": "Day", "totalIntervals": 7},
- "version": 2,
- }
- },
- )
-
-
class TestQueryLLMFormatting(ClickhouseTestMixin, APIBaseTest):
ENDPOINT = "query"
@@ -1546,10 +1489,11 @@ class TestQueryLLMFormatting(ClickhouseTestMixin, APIBaseTest):
mock_process_query_model.return_value = {"results": [], "is_cached": False}
url = f"/api/environments/{self.team.id}/query/"
+ # `_mark_explicit_date_boundaries` reads `dateRange` off any query, so the kind is incidental.
+ # It only has to be one core owns, or this test drags a product's runners back into core's inputs.
payload = {
"query": {
- "kind": "LifecycleQuery",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "kind": "TracesQuery",
"dateRange": {"date_from": "2026-07-02T00:00:00Z", "date_to": date_to},
}
}
diff --git a/posthog/api/test/test_query_kind_endpoint.py b/posthog/api/test/test_query_kind_endpoint.py
index 2ab586226746..a1a49b034a63 100644
--- a/posthog/api/test/test_query_kind_endpoint.py
+++ b/posthog/api/test/test_query_kind_endpoint.py
@@ -46,7 +46,7 @@ class TestQueryKindEndpoint(APIBaseTest):
def test_reserved_query_routes_are_not_treated_as_query_kind(self, _name: str, url_template: str) -> None:
response = self.client.post(
url_template.format(team_id=self.team.pk),
- {"query": {"kind": "RetentionQuery", "retentionFilter": {"period": "Day", "totalIntervals": 7}}},
+ {"query": {"kind": "HogQLQuery", "query": "select 1"}},
format="json",
)
diff --git a/posthog/hogql_queries/insights/insight_actors_query_options_runner.py b/posthog/hogql_queries/insights/insight_actors_query_options_runner.py
index 66bc4afe7485..8261c062b104 100644
--- a/posthog/hogql_queries/insights/insight_actors_query_options_runner.py
+++ b/posthog/hogql_queries/insights/insight_actors_query_options_runner.py
@@ -8,12 +8,11 @@ from posthog.schema import (
from posthog.hogql import ast
-from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from posthog.hogql_queries.query_runner import QueryRunner, get_query_runner
from posthog.models.filters.mixins.utils import cached_property
-from products.product_analytics.backend.facade.queries import FunnelsQueryRunner
+from products.product_analytics.backend.facade.queries import FunnelsQueryRunner, LifecycleQueryRunner
class InsightActorsQueryOptionsRunner(QueryRunner):
diff --git a/posthog/hogql_queries/insights/insight_actors_query_runner.py b/posthog/hogql_queries/insights/insight_actors_query_runner.py
index 26885ae8e9e7..513c7d29c194 100644
--- a/posthog/hogql_queries/insights/insight_actors_query_runner.py
+++ b/posthog/hogql_queries/insights/insight_actors_query_runner.py
@@ -24,8 +24,6 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.timings import HogQLTimings
-from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
-from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, QueryRunner, get_query_runner
from posthog.models import Team
@@ -37,8 +35,10 @@ from products.experiments.backend.hogql_queries.experiment_query_runner import E
from products.product_analytics.backend.facade.queries import (
FunnelCorrelationQueryRunner,
FunnelsQueryRunner,
+ LifecycleQueryRunner,
PathsQueryRunner,
PathsV2QueryRunner,
+ RetentionQueryRunner,
StickinessQueryRunner,
)
diff --git a/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr b/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr
index 2c42a8c0a7a1..5e81e09b5299 100644
--- a/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr
+++ b/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr
@@ -21,87 +21,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestInsightActorsQueryRunner.test_insight_persons_lifecycle_query
- '''
- SELECT n AS n
- FROM
- (SELECT persons.properties___name AS n
- FROM
- (SELECT DISTINCT actor_id AS actor_id
- FROM
- (SELECT min(toTimeZone(events.person_created_at, 'US/Pacific')) AS created_at,
- arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'US/Pacific'), toIntervalDay(1)))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
- arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'US/Pacific'), toIntervalDay(1)))) AS following_activity,
- arrayMap((previous, current, index) -> if(ifNull(equals(previous, current), isNull(previous)
- and isNull(current)), 'new', if(and(ifNull(equals(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), previous), isNull(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
- and isNull(previous)), ifNull(notEquals(index, 1), 1)), 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) AS initial_status,
- arrayMap((current, next) -> if(ifNull(equals(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), toTimeZone(next, 'US/Pacific')), isNull(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
- and isNull(toTimeZone(next, 'US/Pacific'))), '', 'dormant'), all_activity, following_activity) AS dormant_status,
- arrayMap(x -> plus(toTimeZone(x, 'US/Pacific'), toIntervalDay(1)), arrayFilter((current, is_dormant) -> ifNull(equals(is_dormant, 'dormant'), 0), all_activity, dormant_status)) AS dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) AS dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) AS temp_concat,
- arrayJoin(temp_concat) AS period_status_pairs,
- period_status_pairs.1 AS start_of_period,
- period_status_pairs.2 AS status,
- if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id
- 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), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
- GROUP BY actor_id)
- WHERE and(ifNull(equals(start_of_period, toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1))), isNull(start_of_period)
- and isNull(toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1)))), equals(status, 'returning'))) AS source
- INNER JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
- FROM person
- WHERE and(equals(person.team_id, 99999), globalIn(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE and(equals(person.team_id, 99999), globalIn(person.id,
- (SELECT source.actor_id AS actor_id
- FROM
- (SELECT DISTINCT actor_id AS actor_id
- FROM
- (SELECT min(toTimeZone(events.person_created_at, 'US/Pacific')) AS created_at, arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'US/Pacific'), toIntervalDay(1)))) AS all_activity, arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity, arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'US/Pacific'), toIntervalDay(1)))) AS following_activity, arrayMap((previous, current, index) -> if(ifNull(equals(previous, current), isNull(previous)
- and isNull(current)), 'new', if(and(ifNull(equals(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), previous), isNull(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
- and isNull(previous)), ifNull(notEquals(index, 1), 1)), 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) AS initial_status, arrayMap((current, next) -> if(ifNull(equals(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), toTimeZone(next, 'US/Pacific')), isNull(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
- and isNull(toTimeZone(next, 'US/Pacific'))), '', 'dormant'), all_activity, following_activity) AS dormant_status, arrayMap(x -> plus(toTimeZone(x, 'US/Pacific'), toIntervalDay(1)), arrayFilter((current, is_dormant) -> ifNull(equals(is_dormant, 'dormant'), 0), all_activity, dormant_status)) AS dormant_periods, arrayMap(x -> 'dormant', dormant_periods) AS dormant_label, arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) AS temp_concat, arrayJoin(temp_concat) AS period_status_pairs, period_status_pairs.1 AS start_of_period, period_status_pairs.2 AS status, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id
- 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), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
- GROUP BY actor_id)
- WHERE and(ifNull(equals(start_of_period, toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1))), isNull(start_of_period)
- and isNull(toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1)))), equals(status, 'returning'))) AS source)))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)
- ORDER BY persons.properties___name ASC SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')
- LIMIT 100 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- 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: TestInsightActorsQueryRunner.test_insight_persons_trends_groups_query
'''
SELECT name AS name
diff --git a/posthog/hogql_queries/insights/test/test_insight_actors_query_runner.py b/posthog/hogql_queries/insights/test/test_insight_actors_query_runner.py
index 77024d6c4b9c..fd48dad791fc 100644
--- a/posthog/hogql_queries/insights/test/test_insight_actors_query_runner.py
+++ b/posthog/hogql_queries/insights/test/test_insight_actors_query_runner.py
@@ -24,13 +24,11 @@ from posthog.schema import (
TrendsQuery,
)
-from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.models.group.util import create_group
-from posthog.models.team import WeekStartDay
from posthog.test.test_utils import create_group_type_mapping_without_created_at
@@ -100,89 +98,6 @@ class TestInsightActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
modifiers=HogQLQueryModifiers(**modifiers) if modifiers else None,
)
- @snapshot_clickhouse_queries
- def test_insight_persons_lifecycle_query(self):
- self._create_test_events()
- self.team.timezone = "US/Pacific"
- self.team.save()
-
- date_from = "2020-01-09"
- date_to = "2020-01-19"
-
- response = self.select(
- """
- select * from (
- <ActorsQuery select={['properties.name as n']}>
- <InsightActorsQuery day='2020-01-12' status='returning'>
- <LifecycleQuery
- dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
- series={[<EventsNode event='$pageview' math='total' />]}
- />
- </InsightActorsQuery>
- </ActorsQuery>
- )
- """,
- {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
- )
-
- self.assertEqual([("p1",)], response.results)
-
- def test_insight_persons_lifecycle_query_week_monday(self):
- self._create_test_events()
- self.team.timezone = "US/Pacific"
- self.team.week_start_day = WeekStartDay.MONDAY
- self.team.save()
-
- date_from = "2020-01-09"
- date_to = "2020-01-19"
-
- response = self.select(
- """
- select * from (
- <ActorsQuery select={['properties.name as n']}>
- <InsightActorsQuery day='2020-01-13' status='returning'>
- <LifecycleQuery
- interval='week'
- dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
- series={[<EventsNode event='$pageview' math='total' />]}
- />
- </InsightActorsQuery>
- </ActorsQuery>
- )
- """,
- {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
- )
-
- self.assertEqual([("p1",)], response.results)
-
- def test_insight_persons_lifecycle_query_week_sunday(self):
- self._create_test_events()
- self.team.timezone = "US/Pacific"
- self.team.week_start_day = WeekStartDay.SUNDAY
- self.team.save()
-
- date_from = "2020-01-09"
- date_to = "2020-01-19"
-
- response = self.select(
- """
- select * from (
- <ActorsQuery select={['properties.name as n']}>
- <InsightActorsQuery day='2020-01-12' status='returning'>
- <LifecycleQuery
- interval='week'
- dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
- series={[<EventsNode event='$pageview' math='total' />]}
- />
- </InsightActorsQuery>
- </ActorsQuery>
- )
- """,
- {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
- )
-
- self.assertEqual([("p1",), ("p2",)], response.results)
-
def test_insight_persons_trends_query_with_argmaxV1_calculate_adds_event_distinct_ids(self):
self._create_test_events()
self.team.timezone = "US/Pacific"
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index bebe8ede6be8..99c718c62216 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -613,7 +613,7 @@ def get_query_runner(
user=user,
)
if kind == "RetentionQuery":
- from .insights.retention.retention_query_runner import RetentionQueryRunner
+ from products.product_analytics.backend.facade.queries import RetentionQueryRunner
return RetentionQueryRunner(
query=cast(RetentionQuery | dict[str, Any], query),
@@ -669,7 +669,7 @@ def get_query_runner(
user=user,
)
if kind == "LifecycleQuery":
- from .insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
+ from products.product_analytics.backend.facade.queries import LifecycleQueryRunner
return LifecycleQueryRunner(
query=cast(LifecycleQuery | dict[str, Any], query),
diff --git a/posthog/hogql_queries/test/test_dashboard_filters_overrides.py b/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
index ac1b9d9be15d..c7a51ca8403b 100644
--- a/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
+++ b/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
@@ -4,50 +4,35 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from posthog.schema import (
- DashboardFilter,
- DataWarehouseNode,
- EventsNode,
- IntervalType,
- LifecycleQuery,
- RetentionFilter,
- RetentionQuery,
- TrendsQuery,
-)
+from posthog.schema import DashboardFilter, DataWarehouseNode, EventsNode, IntervalType, TracesQuery, TrendsQuery
+from posthog.hogql_queries.ai.traces_query_runner import TracesQueryRunner
from posthog.hogql_queries.apply_dashboard_filters import (
apply_dashboard_filters_to_dict,
resolve_effective_dashboard_filters,
)
-from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
-from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from posthog.hogql_queries.query_runner import QueryRunner
from posthog.models import Team
_TIME_SERIES = [EventsNode(event="$pageview")]
-# Only core-owned runners belong here. Product-owned runners (funnels, paths, stickiness) cover
-# the same dashboard-filter behavior in their own product tests.
+# Only core-owned runners belong here. Product-owned runners (funnels, lifecycle, paths, retention,
+# stickiness) cover the same dashboard-filter behavior in their own product tests.
# Runners whose query model carries an `interval` field.
INTERVAL_QUERY_RUNNERS: list[tuple[str, Callable[[Team], QueryRunner]]] = [
(
"trends",
lambda team: TrendsQueryRunner(query=TrendsQuery(series=_TIME_SERIES, interval=IntervalType.DAY), team=team),
),
- (
- "lifecycle",
- lambda team: LifecycleQueryRunner(
- query=LifecycleQuery(series=_TIME_SERIES, interval=IntervalType.DAY), team=team
- ),
- ),
]
-# Runners whose query model has no `interval` field.
+# Runners whose query model has no `interval` field. Traces is the only core-owned query that
+# takes dashboard filters without one, so it holds this slot on behalf of the shape.
NON_INTERVAL_QUERY_RUNNERS: list[tuple[str, Callable[[Team], QueryRunner]]] = [
(
- "retention",
- lambda team: RetentionQueryRunner(query=RetentionQuery(retentionFilter=RetentionFilter()), team=team),
+ "traces",
+ lambda team: TracesQueryRunner(query=TracesQuery(), team=team),
),
]
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index d62d20312c61..3a6819e1497c 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -1182,69 +1182,6 @@ class TestApplySeriesCustomNames(BaseTest):
self.assertEqual(patched_response.results, expected_results)
- @parameterized.expand(
- [
- (
- "patches_all_lifecycle_statuses",
- [
- {"action": {"order": 0, "custom_name": None}, "status": "new", "data": [1]},
- {"action": {"order": 0, "custom_name": None}, "status": "returning", "data": [2]},
- {"action": {"order": 0, "custom_name": None}, "status": "resurrecting", "data": [3]},
- {"action": {"order": 0, "custom_name": None}, "status": "dormant", "data": [4]},
- ],
- [
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "returning", "data": [2]},
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "resurrecting", "data": [3]},
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "dormant", "data": [4]},
- ],
- True,
- ),
- (
- "not_modified_when_lifecycle_names_match",
- [
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
- ],
- [
- {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
- ],
- False,
- ),
- ]
- )
- def test_apply_lifecycle_custom_names(
- self,
- _name: str,
- cached_results: list,
- expected_results: list,
- expect_modified: bool,
- ):
- from posthog.schema import CachedLifecycleQueryResponse, LifecycleQuery
-
- from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
-
- query = LifecycleQuery(
- series=[
- EventsNode(event="$pageview", custom_name="My Lifecycle"),
- ]
- )
-
- runner = LifecycleQueryRunner(query=query, team=self.team)
-
- cached_response = CachedLifecycleQueryResponse(
- results=cached_results,
- is_cached=True,
- last_refresh=datetime.now(UTC),
- next_allowed_client_refresh=datetime.now(UTC),
- cache_key="test_key",
- timezone="UTC",
- )
-
- patched_response, was_modified = runner.apply_series_custom_names(cached_response)
-
- self.assertEqual(patched_response.results, expected_results)
- self.assertEqual(was_modified, expect_modified)
-
@parameterized.expand(
[
(
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index d92c92726ca2..e2ab77a00dd9 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -761,7 +761,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_200_OK
insight_without_alert_support = deepcopy(self.default_insight_data)
- insight_without_alert_support["query"] = {"kind": "RetentionQuery", "retentionFilter": {}}
+ insight_without_alert_support["query"] = {"kind": "EventsQuery", "select": ["*"]}
self.client.patch(
f"/api/projects/{self.team.id}/insights/{another_insight['id']}",
data=insight_without_alert_support,
@@ -805,7 +805,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
# Changing to a kind that cannot carry alerts still cascades.
self.client.patch(
f"/api/projects/{self.team.id}/insights/{hogql_insight['id']}",
- data={"query": {"kind": "RetentionQuery", "retentionFilter": {}}},
+ data={"query": {"kind": "EventsQuery", "select": ["*"]}},
)
response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index d8c5ae5a20ae..7f2839ed7db1 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -120,7 +120,7 @@ class TestMetricAPI(APIBaseTest):
def test_invalid_definition_rejected(self) -> None:
response = self.client.post(
self.url,
- {"name": "mrr", "description": "d", "definition": {"kind": "RetentionQuery"}},
+ {"name": "mrr", "description": "d", "definition": {"kind": "EventsQuery"}},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/endpoints/backend/insight_transformers.py b/products/endpoints/backend/insight_transformers.py
index 6fc8ab0a70b2..bdb959156482 100644
--- a/products/endpoints/backend/insight_transformers.py
+++ b/products/endpoints/backend/insight_transformers.py
@@ -20,10 +20,10 @@ from posthog.hogql_queries.query_runner import get_query_runner
from posthog.models.team import Team
if TYPE_CHECKING:
- from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
- from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
+ from products.product_analytics.backend.facade.queries import LifecycleQueryRunner, RetentionQueryRunner
+
InsightRunner = Union["LifecycleQueryRunner", "RetentionQueryRunner", "TrendsQueryRunner"]
logger = structlog.get_logger(__name__)
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index 9e72abe8f461..d6b559c44076 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -1781,20 +1781,6 @@ class TestOptionalBreakdownProperties(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
self.assertEqual(response.json().get("attr"), "optional_breakdown_properties")
- def test_rejects_for_query_kind_without_breakdown_support(self):
- # LifecycleQuery has no breakdown support
- response = self.client.post(
- f"/api/environments/{self.team.id}/endpoints/",
- {
- "name": "ep_lifecycle",
- "query": {"kind": "LifecycleQuery", "series": [{"kind": "EventsNode"}]},
- "optional_breakdown_properties": ["$browser"],
- },
- format="json",
- )
- self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
- self.assertEqual(response.json().get("attr"), "optional_breakdown_properties")
-
def test_inheritance_on_query_change_prunes_to_existing_breakdowns(self):
self._create(
"ep_inherit",
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index b50ff60d7d0a..a3c4bc2cdea1 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from typing import Any
import pytest
from freezegun import freeze_time
@@ -16,8 +17,6 @@ from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.response import Response
-from posthog.schema import RetentionQuery
-
from posthog.hogql.errors import QueryError
from posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, TREND_FILTER_TYPE_EVENTS
@@ -505,44 +504,55 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("Cohort breakdowns are not supported", response.json()["detail"])
- def test_can_materialize_lifecycle_query(self):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="user1",
- )
- flush_persons_and_events()
-
+ @parameterized.expand(
+ [
+ (
+ "lifecycle",
+ {
+ "kind": "LifecycleQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "dateRange": {"date_from": "-7d"},
+ "interval": "day",
+ },
+ ),
+ (
+ "retention",
+ {
+ "kind": "RetentionQuery",
+ "dateRange": {"date_from": "2025-01-01", "date_to": "2025-01-08"},
+ "retentionFilter": {
+ "period": "Day",
+ "totalIntervals": 7,
+ "retentionType": RETENTION_FIRST_EVER_OCCURRENCE,
+ "targetEntity": {
+ "id": "$user_signed_up",
+ "name": "$user_signed_up",
+ "type": TREND_FILTER_TYPE_EVENTS,
+ },
+ "returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
+ },
+ },
+ ),
+ ]
+ )
+ def test_can_materialize_allowed_insight_query(self, _name: str, query: dict[str, Any]) -> None:
endpoint = create_endpoint_with_version(
- name="test_lifecycle_query",
+ name=f"test_{_name}_query",
team=self.team,
- query={
- "kind": "LifecycleQuery",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- "dateRange": {"date_from": "-7d"},
- "interval": "day",
- },
+ query=query,
created_by=self.user,
)
version = endpoint.versions.first()
+ assert version is not None
- response = self.client.patch(
- f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",
- {
- "is_materialized": True,
- "data_freshness_seconds": 43200,
- },
- format="json",
- )
+ can_materialize, reason = version.can_materialize()
+ self.assertTrue(can_materialize, reason)
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- version.refresh_from_db()
- self.assertIsNotNone(version.saved_query)
- saved_query = version.saved_query
- assert saved_query is not None
- assert saved_query.query is not None
- self.assertEqual(saved_query.query["kind"], "HogQLQuery")
- self.assertIsInstance(saved_query.query["query"], str)
+ # The allowlist only reads the kind, so compile too: this is the step that would break if the
+ # runner stopped producing a printable AST.
+ hogql_query = build_endpoint_hogql(version.query, self.team)
+ self.assertEqual(hogql_query["kind"], "HogQLQuery")
+ self.assertIsInstance(hogql_query["query"], str)
@parameterized.expand(
[
@@ -589,52 +599,6 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(can_materialize)
self.assertIn(query["kind"], reason)
- def test_can_materialize_retention_query(self):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="user1",
- )
- flush_persons_and_events()
-
- endpoint = create_endpoint_with_version(
- name="test_retention_query",
- team=self.team,
- query=RetentionQuery(
- dateRange={"date_from": "2025-01-01", "date_to": "2025-01-08"},
- retentionFilter={
- "period": "Day",
- "totalIntervals": 7,
- "retentionType": RETENTION_FIRST_EVER_OCCURRENCE,
- "targetEntity": {
- "id": "$user_signed_up",
- "name": "$user_signed_up",
- "type": TREND_FILTER_TYPE_EVENTS,
- },
- "returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
- },
- ).model_dump(),
- created_by=self.user,
- )
- version = endpoint.versions.first()
-
- response = self.client.patch(
- f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",
- {
- "is_materialized": True,
- "data_freshness_seconds": 43200,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- version.refresh_from_db()
- self.assertIsNotNone(version.saved_query)
- saved_query = version.saved_query
- assert saved_query is not None
- assert saved_query.query is not None
- self.assertEqual(saved_query.query["kind"], "HogQLQuery")
-
def test_materialization_status_in_response(self):
"""Test that materialization status is included in endpoint response."""
endpoint = create_endpoint_with_version(
diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.py
index caa193d7ddb3..caef37643e0c 100644
--- a/products/endpoints/backend/tests/test_insight_response_parity.py
+++ b/products/endpoints/backend/tests/test_insight_response_parity.py
@@ -29,7 +29,11 @@ from posthog.schema import (
)
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
-from products.endpoints.backend.insight_transformers import _transform_trends
+from products.endpoints.backend.insight_transformers import (
+ MaterializedSeriesMismatchError,
+ _transform_trends,
+ transform_materialized_insight_response,
+)
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -321,64 +325,32 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
# =========================================================================
def test_materialized_lifecycle_has_insight_shape(self):
- endpoint = create_endpoint_with_version(
- name="lifecycle_parity",
- team=self.team,
- query=LifecycleQuery(
- series=[EventsNode(event="$pageview")],
- dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},
- ).model_dump(),
- created_by=self.user,
- is_active=True,
- )
-
- # Step 1: Inline baseline
- inline_resp = self._run_endpoint(endpoint)
- assert inline_resp.status_code == status.HTTP_200_OK
- inline_results = inline_resp.json()["results"]
- assert len(inline_results) > 0
- assert isinstance(inline_results[0], dict)
- for field in LIFECYCLE_REQUIRED_FIELDS:
- assert field in inline_results[0], f"Inline lifecycle response missing '{field}'"
-
- # Step 2: Materialize
- self._materialize_endpoint(endpoint)
+ original_query = LifecycleQuery(
+ series=[EventsNode(event="$pageview")],
+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},
+ ).model_dump()
- # Step 3: Mock with lifecycle columns in ALPHABETICAL order
- # (matching real materialized table behavior — Delta/Parquet sorts columns)
+ # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.
dates = [date(2026, 1, d) for d in range(1, 11)]
- flat_response = HogQLQueryResponse(
- results=[
+ result: dict[str, Any] = {
+ "results": [
(dates, "new", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
(dates, "returning", [0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
(dates, "resurrecting", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
(dates, "dormant", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
],
- columns=["date", "status", "total"],
- types=["Array(Date)", "String", "Array(Int64)"],
- hasMore=False,
- )
-
- with mock.patch(
- "products.endpoints.backend.logic.execution.process_query_model",
- return_value=flat_response,
- ):
- mat_resp = self._run_endpoint(endpoint)
+ "columns": ["date", "status", "total"],
+ "types": ["Array(Date)", "String", "Array(Int64)"],
+ }
- assert mat_resp.status_code == status.HTTP_200_OK
- mat_results = mat_resp.json()["results"]
- assert len(mat_results) > 0
+ transform_materialized_insight_response(result, original_query, self.team)
- first = mat_results[0]
- assert isinstance(first, dict), f"Expected dict, got {type(first).__name__}: {first}"
+ rows = result["results"]
+ assert len(rows) > 0
for field in LIFECYCLE_REQUIRED_FIELDS:
- assert field in first, f"Materialized lifecycle response missing '{field}'"
-
- # Value assertions: verify lifecycle statuses are present
- statuses = {r["status"] for r in mat_results}
- assert statuses == {"new", "returning", "resurrecting", "dormant"}, f"Unexpected statuses: {statuses}"
- # Each status should have 10 data points
- for r in mat_results:
+ assert field in rows[0], f"Materialized lifecycle response missing '{field}'"
+ assert {r["status"] for r in rows} == {"new", "returning", "resurrecting", "dormant"}
+ for r in rows:
assert len(r["data"]) == 10, f"Status {r['status']}: expected 10 data points, got {len(r['data'])}"
# =========================================================================
@@ -386,37 +358,14 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
# =========================================================================
def test_materialized_retention_has_insight_shape(self):
- endpoint = create_endpoint_with_version(
- name="retention_parity",
- team=self.team,
- query=RetentionQuery(
- retentionFilter=RetentionFilter(),
- dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},
- ).model_dump(),
- created_by=self.user,
- is_active=True,
- )
-
- # Step 1: Inline baseline
- inline_resp = self._run_endpoint(endpoint)
- assert inline_resp.status_code == status.HTTP_200_OK
- inline_results = inline_resp.json()["results"]
- assert len(inline_results) > 0
- assert isinstance(inline_results[0], dict)
- for field in RETENTION_REQUIRED_FIELDS:
- assert field in inline_results[0], f"Inline retention response missing '{field}'"
- # Retention results have nested "values" with "count" and "label"
- assert isinstance(inline_results[0]["values"], list)
- assert "count" in inline_results[0]["values"][0]
- assert "label" in inline_results[0]["values"][0]
-
- # Step 2: Materialize
- self._materialize_endpoint(endpoint)
+ original_query = RetentionQuery(
+ retentionFilter=RetentionFilter(),
+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},
+ ).model_dump()
- # Step 3: Mock with retention columns in ALPHABETICAL order
- # (matching real materialized table behavior — Delta/Parquet sorts columns)
- flat_response = HogQLQueryResponse(
- results=[
+ # Columns arrive in alphabetical order, the way Delta/Parquet sorts a materialized table.
+ result: dict[str, Any] = {
+ "results": [
(1, 0, 0),
(1, 1, 0),
(1, 0, 1),
@@ -424,33 +373,19 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
(0, 0, 2),
(0, 1, 2),
],
- columns=["count", "intervals_from_base", "start_event_matching_interval"],
- types=["UInt64", "Int64", "Int64"],
- hasMore=False,
- )
-
- with mock.patch(
- "products.endpoints.backend.logic.execution.process_query_model",
- return_value=flat_response,
- ):
- mat_resp = self._run_endpoint(endpoint)
+ "columns": ["count", "intervals_from_base", "start_event_matching_interval"],
+ "types": ["UInt64", "Int64", "Int64"],
+ }
- assert mat_resp.status_code == status.HTTP_200_OK
- mat_results = mat_resp.json()["results"]
- assert len(mat_results) > 0
+ transform_materialized_insight_response(result, original_query, self.team)
- first = mat_results[0]
- assert isinstance(first, dict), f"Expected dict, got {type(first).__name__}: {first}"
+ rows = result["results"]
+ assert len(rows) >= 3, f"Expected at least 3 cohorts, got {len(rows)}"
for field in RETENTION_REQUIRED_FIELDS:
- assert field in first, f"Materialized retention response missing '{field}'"
- assert isinstance(first["values"], list), "Retention values should be a list"
- assert "count" in first["values"][0], "Retention values missing 'count'"
- assert "label" in first["values"][0], "Retention values missing 'label'"
-
- # Value assertions: first cohort (interval 0) should have count=1 at base
- assert first["values"][0]["count"] == 1, f"Expected count=1 at base, got {first['values'][0]['count']}"
- # Retention creates one cohort per date interval in the range (10 days = 10 cohorts)
- assert len(mat_results) >= 3, f"Expected at least 3 cohorts, got {len(mat_results)}"
+ assert field in rows[0], f"Materialized retention response missing '{field}'"
+ assert isinstance(rows[0]["values"], list)
+ assert rows[0]["values"][0]["count"] == 1
+ assert "label" in rows[0]["values"][0]
# =========================================================================
# MULTI-SERIES TRENDS
@@ -667,11 +602,6 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
"""Genuine drift — materialized table has a series index the current query
doesn't define — must still trip the mismatch guard so we re-materialize.
"""
- from products.endpoints.backend.insight_transformers import (
- MaterializedSeriesMismatchError,
- transform_materialized_insight_response,
- )
-
endpoint = create_endpoint_with_version(
name="trends_genuine_drift",
team=self.team,
diff --git a/products/product_analytics/backend/facade/queries.py b/products/product_analytics/backend/facade/queries.py
index e06a1a020449..2b303e319976 100644
--- a/products/product_analytics/backend/facade/queries.py
+++ b/products/product_analytics/backend/facade/queries.py
@@ -17,7 +17,9 @@ _LAZY = {
"PATHS_V2_OTHER": "paths_v2.path_item",
"FunnelCorrelationQueryRunner": "funnels.funnel_correlation_query_runner",
"FunnelsQueryRunner": "funnels.funnels_query_runner",
+ "LifecycleQueryRunner": "lifecycle.lifecycle_query_runner",
"PathsQueryRunner": "paths.paths_query_runner",
+ "RetentionQueryRunner": "retention.retention_query_runner",
"PathsV2QueryRunner": "paths_v2.paths_v2_query_runner",
"StickinessQueryRunner": "stickiness.stickiness_query_runner",
"anchored_segment_to_funnels_query": "paths_v2.funnel_converter",
diff --git a/posthog/hogql_queries/insights/lifecycle/__init__.py b/products/product_analytics/backend/hogql_queries/lifecycle/__init__.py
similarity index 100%
rename from posthog/hogql_queries/insights/lifecycle/__init__.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/__init__.py
diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py b/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
similarity index 99%
rename from posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
index ab1fa3884d92..e73533a55eab 100644
--- a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
@@ -27,9 +27,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
-from posthog.hogql_queries.insights.lifecycle.lifecycle_validation_rules import (
- RequireLifecycleDataWarehouseSeriesForCustomAggregationTarget,
-)
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange, compare_interval_length
from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_earliest_timestamp_from_series
@@ -38,6 +35,9 @@ from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models.filters.mixins.utils import cached_property
from products.actions.backend.models.action import Action
+from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_validation_rules import (
+ RequireLifecycleDataWarehouseSeriesForCustomAggregationTarget,
+)
class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):
diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_validation_rules.py b/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_validation_rules.py
similarity index 100%
rename from posthog/hogql_queries/insights/lifecycle/lifecycle_validation_rules.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_validation_rules.py
diff --git a/posthog/hogql_queries/insights/lifecycle/test/__init__.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/__init__.py
similarity index 100%
rename from posthog/hogql_queries/insights/lifecycle/test/__init__.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/test/__init__.py
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_insight_actors.ambr b/products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_insight_actors.ambr
new file mode 100644
index 000000000000..f2be4bebee68
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_insight_actors.ambr
@@ -0,0 +1,95 @@
+# serializer version: 1
+# name: TestLifecycleInsightActors.test_insight_persons_lifecycle_query
+ '''
+ SELECT n AS n
+ FROM
+ (SELECT persons.properties___name AS n
+ FROM
+ (SELECT DISTINCT actor_id AS actor_id
+ FROM
+ (SELECT min(events__person.created_at) AS created_at,
+ arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'US/Pacific'), toIntervalDay(1)))) AS all_activity,
+ arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
+ arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'US/Pacific'), toIntervalDay(1)))) AS following_activity,
+ arrayMap((previous, current, index) -> if(ifNull(equals(previous, current), isNull(previous)
+ and isNull(current)), 'new', if(and(ifNull(equals(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), previous), isNull(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
+ and isNull(previous)), ifNull(notEquals(index, 1), 1)), 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) AS initial_status,
+ arrayMap((current, next) -> if(ifNull(equals(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), toTimeZone(next, 'US/Pacific')), isNull(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
+ and isNull(toTimeZone(next, 'US/Pacific'))), '', 'dormant'), all_activity, following_activity) AS dormant_status,
+ arrayMap(x -> plus(toTimeZone(x, 'US/Pacific'), toIntervalDay(1)), arrayFilter((current, is_dormant) -> ifNull(equals(is_dormant, 'dormant'), 0), all_activity, dormant_status)) AS dormant_periods,
+ arrayMap(x -> 'dormant', dormant_periods) AS dormant_label,
+ arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) AS temp_concat,
+ arrayJoin(temp_concat) AS period_status_pairs,
+ period_status_pairs.1 AS start_of_period,
+ period_status_pairs.2 AS status,
+ if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id
+ 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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
+ GROUP BY actor_id)
+ WHERE and(ifNull(equals(start_of_period, toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1))), isNull(start_of_period)
+ and isNull(toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1)))), equals(status, 'returning'))) AS source
+ INNER JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(person.id,
+ (SELECT source.actor_id AS actor_id
+ FROM
+ (SELECT DISTINCT actor_id AS actor_id
+ FROM
+ (SELECT min(events__person.created_at) AS created_at, arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'US/Pacific'), toIntervalDay(1)))) AS all_activity, arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity, arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'US/Pacific'), toIntervalDay(1)))) AS following_activity, arrayMap((previous, current, index) -> if(ifNull(equals(previous, current), isNull(previous)
+ and isNull(current)), 'new', if(and(ifNull(equals(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), previous), isNull(minus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
+ and isNull(previous)), ifNull(notEquals(index, 1), 1)), 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) AS initial_status, arrayMap((current, next) -> if(ifNull(equals(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)), toTimeZone(next, 'US/Pacific')), isNull(plus(toTimeZone(current, 'US/Pacific'), toIntervalDay(1)))
+ and isNull(toTimeZone(next, 'US/Pacific'))), '', 'dormant'), all_activity, following_activity) AS dormant_status, arrayMap(x -> plus(toTimeZone(x, 'US/Pacific'), toIntervalDay(1)), arrayFilter((current, is_dormant) -> ifNull(equals(is_dormant, 'dormant'), 0), all_activity, dormant_status)) AS dormant_periods, arrayMap(x -> 'dormant', dormant_periods) AS dormant_label, arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) AS temp_concat, arrayJoin(temp_concat) AS period_status_pairs, period_status_pairs.1 AS start_of_period, period_status_pairs.2 AS status, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id
+ 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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version) AS created_at, person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
+ GROUP BY actor_id)
+ WHERE and(ifNull(equals(start_of_period, toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1))), isNull(start_of_period)
+ and isNull(toStartOfInterval(toDateTime('2020-01-12', 'US/Pacific'), toIntervalDay(1)))), equals(status, 'returning'))) AS source)))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)
+ ORDER BY persons.properties___name ASC SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto')
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ 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/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr b/products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr
similarity index 90%
rename from posthog/hogql_queries/insights/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr
rename to products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr
index 267d1024559a..437e9502f7e4 100644
--- a/posthog/hogql_queries/insights/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/__snapshots__/test_lifecycle_query_runner.ambr
@@ -36,7 +36,7 @@
count(DISTINCT actor_id) AS counts,
status AS status
FROM
- (SELECT min(toTimeZone(events.person_created_at, 'UTC')) AS created_at,
+ (SELECT min(events__person.created_at) AS created_at,
arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'UTC'), toIntervalDay(1)))) AS all_activity,
arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'UTC'), toIntervalDay(1)))) AS following_activity,
@@ -60,6 +60,13 @@
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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),
(SELECT cohortpeople.person_id AS person_id
FROM cohortpeople
@@ -113,7 +120,7 @@
count(DISTINCT actor_id) AS counts,
status AS status
FROM
- (SELECT min(toTimeZone(events.person_created_at, 'UTC')) AS created_at,
+ (SELECT min(events__person.created_at) AS created_at,
arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'UTC'), toIntervalDay(1)))) AS all_activity,
arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'UTC'), toIntervalDay(1)))) AS following_activity,
@@ -137,6 +144,13 @@
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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
GROUP BY actor_id)
GROUP BY start_of_period,
@@ -187,7 +201,7 @@
count(DISTINCT actor_id) AS counts,
status AS status
FROM
- (SELECT min(toTimeZone(events.person_created_at, 'UTC')) AS created_at,
+ (SELECT min(events__person.created_at) AS created_at,
arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'UTC'), toIntervalDay(1)))) AS all_activity,
arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'UTC'), toIntervalDay(1)))) AS following_activity,
@@ -211,6 +225,13 @@
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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
GROUP BY actor_id)
GROUP BY start_of_period,
@@ -261,7 +282,7 @@
count(DISTINCT actor_id) AS counts,
status AS status
FROM
- (SELECT min(toTimeZone(events.person_created_at, 'US/Pacific')) AS created_at,
+ (SELECT min(events__person.created_at) AS created_at,
arraySort(groupUniqArray(toStartOfInterval(toTimeZone(events.timestamp, 'US/Pacific'), toIntervalDay(1)))) AS all_activity,
arrayPopBack(arrayPushFront(all_activity, toStartOfInterval(created_at, toIntervalDay(1)))) AS previous_activity,
arrayPopFront(arrayPushBack(all_activity, toStartOfInterval(toDateTime('1970-01-01 00:00:00', 'US/Pacific'), toIntervalDay(1)))) AS following_activity,
@@ -285,6 +306,13 @@
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)
+ LEFT JOIN
+ (SELECT argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$process_person_profile'), ''), 'null'), '^"|"$', ''), 'false'), 1), greaterOrEquals(events.timestamp, minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), less(events.timestamp, plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(1))), equals(events.event, '$pageview'))
GROUP BY actor_id)
GROUP BY start_of_period,
diff --git a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_data_warehouse.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
similarity index 98%
rename from posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_data_warehouse.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
index 25f4979182f2..4b6d545be806 100644
--- a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_data_warehouse.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
@@ -20,15 +20,15 @@ from posthog.schema import (
)
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
-from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_entity_properties
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.data_tools.backend.models.join import DataWarehouseJoin
+from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
-TEST_BUCKET = "test_storage_bucket-posthog.hogql_queries.insights.lifecycle.lifecycle_data_warehouse"
+TEST_BUCKET = "test_storage_bucket-products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_data_warehouse"
class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py
new file mode 100644
index 000000000000..0484cd7daa9f
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py
@@ -0,0 +1,143 @@
+from typing import Any, Optional
+
+from freezegun import freeze_time
+from posthog.test.base import (
+ APIBaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ _create_person,
+ snapshot_clickhouse_queries,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.models.team import WeekStartDay
+
+
+class TestLifecycleInsightActors(ClickhouseTestMixin, APIBaseTest):
+ maxDiff = None
+
+ def _create_test_events(self):
+ data = [
+ (
+ "p1",
+ [
+ "2020-01-11T12:00:00Z",
+ "2020-01-12T12:00:00Z",
+ "2020-01-13T12:00:00Z",
+ "2020-01-15T12:00:00Z",
+ "2020-01-17T12:00:00Z",
+ "2020-01-19T12:00:00Z",
+ ],
+ ),
+ ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
+ ("p3", ["2020-01-12T12:00:00Z"]),
+ ("p4", ["2020-01-15T12:00:00Z"]),
+ ]
+ for distinct_id, timestamps in data:
+ with freeze_time(timestamps[0]):
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=[distinct_id],
+ properties={
+ "name": distinct_id,
+ **({"email": "[email protected]"} if distinct_id == "p1" else {}),
+ },
+ )
+ for timestamp in timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties={"$group_0": "org:1"},
+ )
+
+ def select(self, query: str, placeholders: Optional[dict[str, Any]] = None):
+ return execute_hogql_query(query=query, team=self.team, placeholders=placeholders or {})
+
+ @snapshot_clickhouse_queries
+ def test_insight_persons_lifecycle_query(self):
+ self._create_test_events()
+ self.team.timezone = "US/Pacific"
+ self.team.save()
+
+ date_from = "2020-01-09"
+ date_to = "2020-01-19"
+
+ response = self.select(
+ """
+ select * from (
+ <ActorsQuery select={['properties.name as n']}>
+ <InsightActorsQuery day='2020-01-12' status='returning'>
+ <LifecycleQuery
+ dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
+ series={[<EventsNode event='$pageview' math='total' />]}
+ />
+ </InsightActorsQuery>
+ </ActorsQuery>
+ )
+ """,
+ {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
+ )
+
+ self.assertEqual([("p1",)], response.results)
+
+ # A week bucket is anchored on the team's week start, so the same events put the returning
+ # actors on a different day under each setting.
+ def test_insight_persons_lifecycle_query_week_monday(self):
+ self._create_test_events()
+ self.team.timezone = "US/Pacific"
+ self.team.week_start_day = WeekStartDay.MONDAY
+ self.team.save()
+
+ date_from = "2020-01-09"
+ date_to = "2020-01-19"
+
+ response = self.select(
+ """
+ select * from (
+ <ActorsQuery select={['properties.name as n']}>
+ <InsightActorsQuery day='2020-01-13' status='returning'>
+ <LifecycleQuery
+ interval='week'
+ dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
+ series={[<EventsNode event='$pageview' math='total' />]}
+ />
+ </InsightActorsQuery>
+ </ActorsQuery>
+ )
+ """,
+ {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
+ )
+
+ self.assertEqual([("p1",)], response.results)
+
+ def test_insight_persons_lifecycle_query_week_sunday(self):
+ self._create_test_events()
+ self.team.timezone = "US/Pacific"
+ self.team.week_start_day = WeekStartDay.SUNDAY
+ self.team.save()
+
+ date_from = "2020-01-09"
+ date_to = "2020-01-19"
+
+ response = self.select(
+ """
+ select * from (
+ <ActorsQuery select={['properties.name as n']}>
+ <InsightActorsQuery day='2020-01-12' status='returning'>
+ <LifecycleQuery
+ interval='week'
+ dateRange={<DateRange date_from={{date_from}} date_to={{date_to}} />}
+ series={[<EventsNode event='$pageview' math='total' />]}
+ />
+ </InsightActorsQuery>
+ </ActorsQuery>
+ )
+ """,
+ {"date_from": ast.Constant(value=date_from), "date_to": ast.Constant(value=date_to)},
+ )
+
+ self.assertEqual([("p1",), ("p2",)], response.results)
diff --git a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
similarity index 99%
rename from posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
index b99b5763f909..fd9b93b32042 100644
--- a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
@@ -33,7 +33,6 @@ from posthog.schema import (
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting
@@ -43,6 +42,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
+from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
def create_action(**kwargs):
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner_filters.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner_filters.py
new file mode 100644
index 000000000000..2680423f9fb1
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner_filters.py
@@ -0,0 +1,111 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.schema import CachedLifecycleQueryResponse, DashboardFilter, EventsNode, IntervalType, LifecycleQuery
+
+from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
+
+
+class TestLifecycleDashboardFilters(BaseTest):
+ def _runner(self) -> LifecycleQueryRunner:
+ return LifecycleQueryRunner(
+ query=LifecycleQuery(series=[EventsNode(event="$pageview")], interval=IntervalType.DAY),
+ team=self.team,
+ )
+
+ @parameterized.expand(
+ [
+ ("override_written_onto_query", IntervalType.WEEK, IntervalType.WEEK),
+ ("absent_override_leaves_query_untouched", None, IntervalType.DAY),
+ ]
+ )
+ def test_dashboard_interval_override(
+ self, _name: str, dashboard_interval: IntervalType | None, expected: IntervalType
+ ) -> None:
+ runner = self._runner()
+
+ runner.apply_dashboard_filters(DashboardFilter(interval=dashboard_interval))
+
+ assert runner.query.interval == expected
+
+ @parameterized.expand(
+ [
+ ("override_forces_on", None, True, True),
+ ("override_forces_off", True, False, False),
+ ("absent_override_leaves_query_untouched", True, None, True),
+ ]
+ )
+ def test_dashboard_test_accounts_override(
+ self, _name: str, initial: bool | None, dashboard_filter: bool | None, expected: bool
+ ) -> None:
+ runner = self._runner()
+ if initial is not None:
+ runner.query.filterTestAccounts = initial
+
+ runner.apply_dashboard_filters(DashboardFilter(filterTestAccounts=dashboard_filter))
+
+ assert runner.query.filterTestAccounts is expected
+
+
+class TestLifecycleSeriesCustomNames(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "patches_all_lifecycle_statuses",
+ [
+ {"action": {"order": 0, "custom_name": None}, "status": "new", "data": [1]},
+ {"action": {"order": 0, "custom_name": None}, "status": "returning", "data": [2]},
+ {"action": {"order": 0, "custom_name": None}, "status": "resurrecting", "data": [3]},
+ {"action": {"order": 0, "custom_name": None}, "status": "dormant", "data": [4]},
+ ],
+ [
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "returning", "data": [2]},
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "resurrecting", "data": [3]},
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "dormant", "data": [4]},
+ ],
+ True,
+ ),
+ (
+ "not_modified_when_lifecycle_names_match",
+ [
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
+ ],
+ [
+ {"action": {"order": 0, "custom_name": "My Lifecycle"}, "status": "new", "data": [1]},
+ ],
+ False,
+ ),
+ ]
+ )
+ def test_apply_lifecycle_custom_names(
+ self,
+ _name: str,
+ cached_results: list,
+ expected_results: list,
+ expect_modified: bool,
+ ):
+ query = LifecycleQuery(
+ series=[
+ EventsNode(event="$pageview", custom_name="My Lifecycle"),
+ ]
+ )
+
+ runner = LifecycleQueryRunner(query=query, team=self.team)
+
+ cached_response = CachedLifecycleQueryResponse(
+ results=cached_results,
+ is_cached=True,
+ last_refresh=datetime.now(UTC),
+ next_allowed_client_refresh=datetime.now(UTC),
+ cache_key="test_key",
+ timezone="UTC",
+ )
+
+ patched_response, was_modified = runner.apply_series_custom_names(cached_response)
+
+ self.assertEqual(patched_response.results, expected_results)
+ self.assertEqual(was_modified, expect_modified)
diff --git a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_validation_rules.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_validation_rules.py
similarity index 95%
rename from posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_validation_rules.py
rename to products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_validation_rules.py
index 9608b452b54e..a99db3eb93cc 100644
--- a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_validation_rules.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_validation_rules.py
@@ -5,10 +5,11 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import EventsNode, LifecycleDataWarehouseNode, LifecycleQuery
-from posthog.hogql_queries.insights.lifecycle.lifecycle_validation_rules import (
+from posthog.hogql_queries.validation.validation import QueryValidationContext
+
+from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_validation_rules import (
RequireLifecycleDataWarehouseSeriesForCustomAggregationTarget,
)
-from posthog.hogql_queries.validation.validation import QueryValidationContext
class TestLifecycleValidationRules(BaseTest):
diff --git a/posthog/hogql_queries/insights/retention/__init__.py b/products/product_analytics/backend/hogql_queries/retention/__init__.py
similarity index 100%
rename from posthog/hogql_queries/insights/retention/__init__.py
rename to products/product_analytics/backend/hogql_queries/retention/__init__.py
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_builder.py
similarity index 97%
rename from posthog/hogql_queries/insights/retention/retention_base_query_builder.py
rename to products/product_analytics/backend/hogql_queries/retention/retention_base_query_builder.py
index 1bdf73785aa0..b875decc12ba 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_builder.py
@@ -13,15 +13,17 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.property import entity_to_expr, property_to_expr
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
-from posthog.hogql_queries.insights.retention.utils import breakdown_extract_expr
+
+from products.product_analytics.backend.hogql_queries.retention.utils import breakdown_extract_expr
if TYPE_CHECKING:
from posthog.schema import RetentionEntity, RetentionQuery
- from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRangeWithIntervals
from posthog.models import Team
+ from products.product_analytics.backend.hogql_queries.retention.retention_query_runner import RetentionQueryRunner
+
class RetentionBaseQueryBuilder(ABC):
runner: RetentionQueryRunner
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
rename to products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
index 3ae3d8435e4c..c2a28a126e45 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
@@ -7,9 +7,12 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.property import property_to_expr
from posthog.dataclasses import frozen
-from posthog.hogql_queries.insights.retention.retention_base_query_builder import RetentionBaseQueryBuilder
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, has_breakdown_filter
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_builder import (
+ RetentionBaseQueryBuilder,
+)
+
@frozen
class IntervalsFromBaseExprs:
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/retention_base_query_rolling.py
rename to products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
index 7d6b78ef3efa..fa8f5bdbf104 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_rolling.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
@@ -3,7 +3,9 @@ from posthog.schema import EntityType
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr
-from posthog.hogql_queries.insights.retention.retention_base_query_builder import RetentionBaseQueryBuilder
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_builder import (
+ RetentionBaseQueryBuilder,
+)
class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/retention_query_runner.py
rename to products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
index 848ca911c495..503f0697672e 100644
--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
@@ -33,18 +33,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql.timings import HogQLTimings
from posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL
-from posthog.hogql_queries.insights.retention.retention_base_query_fixed import RetentionFixedIntervalBaseQueryBuilder
-from posthog.hogql_queries.insights.retention.retention_base_query_rolling import (
- RetentionRollingIntervalBaseQueryBuilder,
-)
-from posthog.hogql_queries.insights.retention.retention_validation_rules import (
- DisallowBreakdownsWithDataWarehouse24HourWindows,
- DisallowCumulativeWith24HourWindows,
- DisallowGroupAggregationWithDataWarehouse24HourWindows,
- DisallowPropertyAggregationWith24HourWindows,
- DisallowUnsupportedDataWarehouseTimestampField,
- RequireRetentionDataWarehouseEntitiesForCustomAggregationTarget,
-)
from posthog.hogql_queries.insights.utils.breakdowns import (
ALL_USERS_COHORT_ID,
BREAKDOWN_OTHER_STRING_LABEL,
@@ -62,6 +50,20 @@ from posthog.models.user import User
from posthog.queries.util import correct_result_for_sampling
from products.actions.backend.models.action import Action
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_fixed import (
+ RetentionFixedIntervalBaseQueryBuilder,
+)
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_rolling import (
+ RetentionRollingIntervalBaseQueryBuilder,
+)
+from products.product_analytics.backend.hogql_queries.retention.retention_validation_rules import (
+ DisallowBreakdownsWithDataWarehouse24HourWindows,
+ DisallowCumulativeWith24HourWindows,
+ DisallowGroupAggregationWithDataWarehouse24HourWindows,
+ DisallowPropertyAggregationWith24HourWindows,
+ DisallowUnsupportedDataWarehouseTimestampField,
+ RequireRetentionDataWarehouseEntitiesForCustomAggregationTarget,
+)
DEFAULT_INTERVAL = IntervalType("day")
DEFAULT_TOTAL_INTERVALS = 7
diff --git a/posthog/hogql_queries/insights/retention/retention_validation_rules.py b/products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py
similarity index 100%
rename from posthog/hogql_queries/insights/retention/retention_validation_rules.py
rename to products/product_analytics/backend/hogql_queries/retention/retention_validation_rules.py
diff --git a/posthog/hogql_queries/insights/retention/test/__init__.py b/products/product_analytics/backend/hogql_queries/retention/test/__init__.py
similarity index 100%
rename from posthog/hogql_queries/insights/retention/test/__init__.py
rename to products/product_analytics/backend/hogql_queries/retention/test/__init__.py
diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
similarity index 89%
rename from posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr
rename to products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
index 3674783785ec..1e047db0d2c5 100644
--- a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr
+++ b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
@@ -15,7 +15,7 @@
(SELECT toString(posthog_test_warehouse_event_mix_signups_uuid.person_id) AS actor_id,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_uuid/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_uuid
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_uuid/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_uuid
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
@@ -67,7 +67,7 @@
(SELECT toString(posthog_test_warehouse_event_mix_signups_string.person_id) AS actor_id,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_string/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` String, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_string
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_string/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` String, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_string
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
@@ -122,14 +122,14 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity_breakdown.activity_type, 'signed_up'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS start_event_timestamps,
[] AS return_event_timestamps,
ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
GROUP BY actor_id,
breakdown_value
UNION ALL SELECT toString(posthog_test_warehouse_activity_breakdown.person_id) AS actor_id,
[] AS start_event_timestamps,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity_breakdown.activity_type, 'renewed'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS return_event_timestamps,
ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
GROUP BY actor_id,
breakdown_value) AS retention_events
GROUP BY actor_id,
@@ -172,12 +172,12 @@
(SELECT toString(posthog_test_warehouse_signups.person_id) AS actor_id,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_signups/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_signups
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_signups/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_signups
GROUP BY actor_id
UNION ALL SELECT toString(posthog_test_warehouse_renewals.person_id) AS actor_id,
[] AS start_event_timestamps,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))) AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_renewals/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `renewed_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_renewals
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_renewals/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `renewed_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_renewals
GROUP BY actor_id) AS retention_events
GROUP BY actor_id
HAVING 1) AS actor_activity
@@ -216,12 +216,12 @@
(SELECT toString(posthog_test_warehouse_activity.person_id) AS actor_id,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity.activity_type, 'signed_up'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS start_event_timestamps,
[] AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/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
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/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
GROUP BY actor_id
UNION ALL SELECT toString(posthog_test_warehouse_activity.person_id) AS actor_id,
[] AS start_event_timestamps,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity.activity_type, 'renewed'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS return_event_timestamps
- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/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
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/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
GROUP BY actor_id) AS retention_events
GROUP BY actor_id
HAVING 1) AS actor_activity
diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr
similarity index 87%
rename from posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr
rename to products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr
index 84e94b90dd73..b0a7fff23aad 100644
--- a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr
+++ b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse_24h_window.ambr
@@ -25,7 +25,7 @@
LEFT JOIN
(SELECT toString(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
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.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
@@ -60,13 +60,13 @@
FROM
(SELECT toString(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
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.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 toString(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
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.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
diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_query_runner.ambr
similarity index 98%
rename from posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr
rename to products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_query_runner.ambr
index 4f6f776dd8c4..66ce397a6d2c 100644
--- a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr
+++ b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_query_runner.ambr
@@ -910,7 +910,7 @@
count(DISTINCT actor_activity.actor_id) AS count
FROM
(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
- arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(or(and(equals(events.event, '$pageview'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)), equals(events.event, 'non_matching_event')), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS start_event_timestamps,
+ arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(or(and(equals(events.event, '$pageview'), ifNull(equals(events__person.properties___email, '[email protected]'), 0)), equals(events.event, 'non_matching_event')), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS start_event_timestamps,
arrayMap(x -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(x)), range(0, 7)) AS date_range,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(equals(events.event, '$pageview'), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS return_event_timestamps,
arrayJoin(arrayFilter(x -> ifNull(greater(x, -1), 0), arrayMap((interval_index, interval_date, _start_event_timestamps) -> if(has(_start_event_timestamps, interval_date), minus(interval_index, 1), -1), arrayEnumerate(date_range), date_range, arrayResize([start_event_timestamps], length(date_range), start_event_timestamps)))) AS start_interval_index,
@@ -923,7 +923,17 @@
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), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('$pageview', 'non_matching_event')), or(or(and(equals(events.event, '$pageview'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)), equals(events.event, 'non_matching_event')), equals(events.event, '$pageview')))
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('$pageview', 'non_matching_event')), or(or(and(equals(events.event, '$pageview'), ifNull(equals(events__person.properties___email, '[email protected]'), 0)), equals(events.event, 'non_matching_event')), equals(events.event, '$pageview')))
GROUP BY actor_id
HAVING 1) AS actor_activity
GROUP BY start_event_matching_interval,
diff --git a/posthog/hogql_queries/insights/retention/test/data/retention_extended_person_properties.csv b/products/product_analytics/backend/hogql_queries/retention/test/data/retention_extended_person_properties.csv
similarity index 100%
rename from posthog/hogql_queries/insights/retention/test/data/retention_extended_person_properties.csv
rename to products/product_analytics/backend/hogql_queries/retention/test/data/retention_extended_person_properties.csv
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse.py
index c206f88c4c9c..5df300e9d591 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse.py
@@ -16,16 +16,16 @@ from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
-from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
-from posthog.hogql_queries.insights.retention.test.utils import pad, pluck
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
+from products.product_analytics.backend.hogql_queries.retention.retention_query_runner import RetentionQueryRunner
+from products.product_analytics.backend.hogql_queries.retention.test.utils import pad, pluck
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"
+TEST_BUCKET = "test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse"
class TestRetentionDataWarehouse(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse_24h_window.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse_24h_window.py
index 64facbf612ae..2ed61b21d6fb 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse_24h_window.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_data_warehouse_24h_window.py
@@ -16,11 +16,10 @@ 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.product_analytics.backend.hogql_queries.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"
+TEST_BUCKET = "test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse_24h_window"
ACTIVITY_TABLE_COLUMNS = {
"id": "Int64",
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_first_time_anchor.py
similarity index 97%
rename from posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_first_time_anchor.py
index eed49788c4fe..79a07270191b 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_first_time_anchor.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_first_time_anchor.py
@@ -10,7 +10,9 @@ from posthog.schema import RetentionEntity
from posthog.hogql import ast
-from posthog.hogql_queries.insights.retention.retention_base_query_fixed import RetentionFixedIntervalBaseQueryBuilder
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_fixed import (
+ RetentionFixedIntervalBaseQueryBuilder,
+)
def _walk_ast(node: Any, visit: Callable[[Any], None]) -> None:
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
index afd198b6a0bb..4d34618d927b 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
@@ -36,9 +36,6 @@ from posthog.constants import (
TREND_FILTER_TYPE_EVENTS,
)
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
-from posthog.hogql_queries.insights.retention.retention_base_query_fixed import RetentionFixedIntervalBaseQueryBuilder
-from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
-from posthog.hogql_queries.insights.retention.test.utils import pad, pluck
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABEL
from posthog.models.group.util import create_group
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
@@ -48,9 +45,14 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
+from products.product_analytics.backend.hogql_queries.retention.retention_base_query_fixed import (
+ RetentionFixedIntervalBaseQueryBuilder,
+)
+from products.product_analytics.backend.hogql_queries.retention.retention_query_runner import RetentionQueryRunner
+from products.product_analytics.backend.hogql_queries.retention.test.utils import pad, pluck
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
-TEST_BUCKET = "test_storage_bucket-posthog.hogql_queries.insights.retention"
+TEST_BUCKET = "test_storage_bucket-products.product_analytics.backend.hogql_queries.retention"
def _create_signup_actions(team, user_and_timestamps):
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner_filters.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner_filters.py
new file mode 100644
index 000000000000..ef0dc702cdc6
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner_filters.py
@@ -0,0 +1,37 @@
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.schema import DashboardFilter, IntervalType, RetentionFilter, RetentionQuery
+
+from products.product_analytics.backend.hogql_queries.retention.retention_query_runner import RetentionQueryRunner
+
+
+class TestRetentionDashboardFilters(BaseTest):
+ def _runner(self) -> RetentionQueryRunner:
+ return RetentionQueryRunner(query=RetentionQuery(retentionFilter=RetentionFilter()), team=self.team)
+
+ def test_dashboard_interval_override_is_skipped(self) -> None:
+ runner = self._runner()
+
+ runner.apply_dashboard_filters(DashboardFilter(interval=IntervalType.WEEK))
+
+ assert not hasattr(runner.query, "interval")
+
+ @parameterized.expand(
+ [
+ ("override_forces_on", None, True, True),
+ ("override_forces_off", True, False, False),
+ ("absent_override_leaves_query_untouched", True, None, True),
+ ]
+ )
+ def test_dashboard_test_accounts_override(
+ self, _name: str, initial: bool | None, dashboard_filter: bool | None, expected: bool
+ ) -> None:
+ runner = self._runner()
+ if initial is not None:
+ runner.query.filterTestAccounts = initial
+
+ runner.apply_dashboard_filters(DashboardFilter(filterTestAccounts=dashboard_filter))
+
+ assert runner.query.filterTestAccounts is expected
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_utils.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py
similarity index 94%
rename from posthog/hogql_queries/insights/retention/test/test_retention_utils.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py
index c03bd8d45d22..1ccccdeef2d5 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_utils.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_utils.py
@@ -4,7 +4,7 @@ from django.test import SimpleTestCase
from posthog.hogql import ast
-from posthog.hogql_queries.insights.retention.utils import breakdown_extract_expr
+from products.product_analytics.backend.hogql_queries.retention.utils import breakdown_extract_expr
def _chain(expr: ast.Expr) -> list:
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
similarity index 99%
rename from posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py
rename to products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
index a3a0a64c7b97..4d92e6ed97e7 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_validation_rules.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_validation_rules.py
@@ -6,15 +6,16 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import AggregationType, BreakdownFilter, EntityType, RetentionFilter, RetentionQuery, TimeWindowMode
-from posthog.hogql_queries.insights.retention.retention_validation_rules import (
+from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings
+from posthog.hogql_queries.validation.validation import QueryValidationContext
+
+from products.product_analytics.backend.hogql_queries.retention.retention_validation_rules import (
DisallowBreakdownsWithDataWarehouse24HourWindows,
DisallowCumulativeWith24HourWindows,
DisallowGroupAggregationWithDataWarehouse24HourWindows,
DisallowPropertyAggregationWith24HourWindows,
RequireRetentionDataWarehouseEntitiesForCustomAggregationTarget,
)
-from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings
-from posthog.hogql_queries.validation.validation import QueryValidationContext
class TestRetentionValidationRules(BaseTest):
diff --git a/posthog/hogql_queries/insights/retention/test/utils.py b/products/product_analytics/backend/hogql_queries/retention/test/utils.py
similarity index 100%
rename from posthog/hogql_queries/insights/retention/test/utils.py
rename to products/product_analytics/backend/hogql_queries/retention/test/utils.py
diff --git a/posthog/hogql_queries/insights/retention/utils.py b/products/product_analytics/backend/hogql_queries/retention/utils.py
similarity index 100%
rename from posthog/hogql_queries/insights/retention/utils.py
rename to products/product_analytics/backend/hogql_queries/retention/utils.py
diff --git a/products/product_analytics/backend/tests/api/test_retention_query_upgrade.py b/products/product_analytics/backend/tests/api/test_retention_query_upgrade.py
new file mode 100644
index 000000000000..bda33144809d
--- /dev/null
+++ b/products/product_analytics/backend/tests/api/test_retention_query_upgrade.py
@@ -0,0 +1,58 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from posthog.schema import CachedRetentionQueryResponse, MeanRetentionCalculation, RetentionQuery
+
+
+class TestRetentionQueryUpgrade(APIBaseTest):
+ @patch("posthog.api.query.process_query_model")
+ def test_query_endpoint_upgrades_before_running(self, mock_process_query):
+ mock_process_query.return_value = CachedRetentionQueryResponse(
+ cache_key="cache_123",
+ is_cached=False,
+ last_refresh="2023-10-16T12:00:00Z",
+ next_allowed_client_refresh="2023-10-16T14:00:00Z",
+ results=[],
+ timezone="UTC",
+ )
+
+ self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {
+ "query": {
+ "kind": "RetentionQuery",
+ "retentionFilter": {
+ "period": "Day",
+ "totalIntervals": 8,
+ "targetEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
+ "returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
+ "retentionType": "retention_first_time",
+ "showMean": True,
+ },
+ },
+ "client_query_id": "5d92fb51-5088-45e8-91b2-843aef3d69bd",
+ },
+ ).json()
+
+ mock_process_query.assert_called_once()
+ updated_query = mock_process_query.call_args.args[1]
+ assert isinstance(updated_query, RetentionQuery)
+ assert updated_query.version == 2
+ assert updated_query.retentionFilter.meanRetentionCalculation == MeanRetentionCalculation.SIMPLE
+
+ def test_upgrade_endpoint_returns_the_migrated_query(self):
+ query = {"kind": "RetentionQuery", "retentionFilter": {"period": "Day", "totalIntervals": 7, "showMean": True}}
+
+ response = self.client.post(f"/api/environments/{self.team.id}/query/upgrade/", {"query": query})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {
+ "query": {
+ "kind": "RetentionQuery",
+ "retentionFilter": {"meanRetentionCalculation": "simple", "period": "Day", "totalIntervals": 7},
+ "version": 2,
+ }
+ },
+ )
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
index 529637fbdaa4..dbf3867c99c4 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
@@ -19,10 +19,10 @@ from posthog.schema import (
EventsNode,
IntervalType,
PropertyOperator,
- RetentionFilter,
- RetentionQuery,
TrendsFilter,
TrendsQuery,
+ WebStatsBreakdown,
+ WebStatsTableQuery,
WebVitalsQuery,
)
@@ -260,9 +260,9 @@ class TestWebVitalsTimeseriesLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# A schema-valid non-Trends source must fall through to the legacy source
# unwrap, not raise in the runner constructor (which would surface as an
# internal error rather than running the query).
- query = WebVitalsQuery(source=RetentionQuery(retentionFilter=RetentionFilter()), properties=[]).model_dump(
- mode="json"
- )
+ query = WebVitalsQuery(
+ source=WebStatsTableQuery(breakdownBy=WebStatsBreakdown.PAGE, properties=[]), properties=[]
+ ).model_dump(mode="json")
with patch(
"products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",
return_value=True,