:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(filters): delete the legacy Filter (#104270)
Thomas Obermüller2bda514375f5
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 87c2cd8a43d7..ba091c3ad97b 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -19,12 +19,12 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.constants import SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY, AvailableFeaturefrom posthog.models import Team-from posthog.models.filters.filter import Filterfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.slo.context import slo_operation+from posthog.test.insight_queries import browser_filtered_pageview_query, default_pageview_queryfrom products.access_control.backend.models.access_control import AccessControlfrom products.dashboards.backend.models.dashboard import Dashboard@@ -82,18 +82,13 @@ class TestSubscriptionTemporal(APILicensedTest):dashboard: Dashboard = None # type: ignoreinsight: Insight = None # type: ignore- insight_filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-@classmethoddef setUpTestData(cls):super().setUpTestData()cls.dashboard = Dashboard.objects.create(team=cls.team, name="example dashboard", created_by=cls.user)cls.insight = Insight.objects.create(- filters=Filter(data=cls.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=cls.team,created_by=cls.user,)@@ -566,12 +561,12 @@ class TestSubscriptionTemporal(APILicensedTest):def test_can_update_dashboard_subscription_with_new_insights(self):insight_1 = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)insight_2 = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)@@ -633,7 +628,7 @@ class TestSubscriptionTemporal(APILicensedTest):insights = []for _ in range(MAX_INSIGHTS + 1):insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)@@ -670,7 +665,7 @@ class TestSubscriptionTemporal(APILicensedTest):# Create an insight that belongs to a different dashboardother_dashboard = Dashboard.objects.create(team=self.team, name="other dashboard", created_by=self.user)other_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)@@ -716,7 +711,7 @@ class TestSubscriptionTemporal(APILicensedTest):# Create another team and insightother_team = Team.objects.create(organization=self.organization, name="Other Team")other_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=other_team,created_by=self.user,)@@ -1428,7 +1423,7 @@ class TestSubscriptionTemporal(APILicensedTest):team_two = Team.objects.create(organization=self.organization, name="Team two")team_three = Team.objects.create(organization=self.organization, name="Team three")team_three_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=team_three,created_by=self.user,)@@ -1438,7 +1433,7 @@ class TestSubscriptionTemporal(APILicensedTest):Subscription.objects.create(team=team,insight=Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=team,created_by=self.user,),@@ -1785,7 +1780,7 @@ class TestSubscriptionTemporal(APILicensedTest):def test_list_subscriptions_filter_by_insights(self):other_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(), team=self.team, created_by=self.user+ query=browser_filtered_pageview_query(), team=self.team, created_by=self.user)first_id = self._create_subscription(title="First").json()["id"]second_id = self._create_subscription(title="Second", insight=other_insight.id).json()["id"]@@ -1824,7 +1819,7 @@ class TestSubscriptionTemporal(APILicensedTest):def _insight(self, **kwargs) -> Insight:return Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(), team=self.team, created_by=self.user, **kwargs+ query=browser_filtered_pageview_query(), team=self.team, created_by=self.user, **kwargs)def test_list_subscriptions_filter_by_dashboard_tiles(self):@@ -1891,7 +1886,7 @@ class TestSubscriptionTemporal(APILicensedTest):def test_list_subscriptions_search_matches_insight_name(self):named_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,name="UniqueInsightNameForSearchTest",@@ -2335,7 +2330,7 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):def setUpTestData(cls):super().setUpTestData()cls.insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=cls.team,created_by=cls.user,)diff --git a/ee/clickhouse/models/test/test_filters.py b/ee/clickhouse/models/test/test_filters.pydeleted file mode 100644index d0f1bf9b9099..000000000000--- a/ee/clickhouse/models/test/test_filters.py+++ /dev/null@@ -1,655 +0,0 @@-from posthog.models.filters import Filter-from posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.test.test_filter import TestFilter as PGTestFilters--from products.cohorts.backend.models.cohort import Cohort---class TestFilters(PGTestFilters):- maxDiff = None-- def test_simplify_cohorts(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ]- }- ],- )- cohort.calculate_people_ch(pending_version=0)-- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]})- filter_with_groups = Filter(- data={- "properties": {- "type": "AND",- "values": [{"type": "cohort", "key": "id", "value": cohort.pk}],- }- }- )-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- }- },- )-- self.assertEqual(- filter_with_groups.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- }- },- )-- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "key": "id",- "value": cohort.pk,- "negation": False,- "type": "precalculated-cohort",- }- ],- }- },- )-- self.assertEqual(- filter_with_groups.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "key": "id",- "negation": False,- "value": cohort.pk,- "type": "precalculated-cohort",- }- ],- }- },- )-- def test_simplify_static_cohort(self):- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [{"type": "static-cohort", "negation": False, "key": "id", "value": cohort.pk}],- }- },- )-- def test_simplify_hasdone_cohort(self):- cohort = Cohort.objects.create(team=self.team, groups=[{"event_id": "$pageview", "days": 1}])- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [{"type": "cohort", "negation": False, "key": "id", "value": cohort.pk}],- }- },- )-- def test_simplify_multi_group_cohort(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {"properties": [{"key": "$some_prop", "value": "something", "type": "person"}]},- {"properties": [{"key": "$another_prop", "value": "something", "type": "person"}]},- ],- )- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "$some_prop",- "value": "something",- }- ],- },- {- "type": "AND",- "values": [- {- "type": "person",- "key": "$another_prop",- "value": "something",- }- ],- },- ],- }- ],- }- },- )-- def test_recursive_cohort(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ]- }- ],- )- recursive_cohort = Cohort.objects.create(- team=self.team,- groups=[{"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]}],- )- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": recursive_cohort.pk}]})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ],- }- },- )-- def test_simplify_cohorts_with_recursive_negation(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ]- }- ],- )- recursive_cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {"key": "email", "value": "xyz", "type": "person"},- {- "type": "cohort",- "key": "id",- "value": cohort.pk,- "negation": True,- },- ]- }- ],- )- filter = Filter(- data={- "properties": [- {- "type": "cohort",- "key": "id",- "value": recursive_cohort.pk,- "negation": True,- }- ]- }- )-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "type": "cohort",- "key": "id",- "value": recursive_cohort.pk,- "negation": True,- }- ],- }- },- )-- def test_simplify_cohorts_with_simple_negation(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ]- }- ],- )- filter = Filter(- data={- "properties": [- {- "type": "cohort",- "key": "id",- "value": cohort.pk,- "negation": True,- }- ]- }- )-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "type": "cohort",- "key": "id",- "value": cohort.pk,- "negation": True,- }- ],- }- },- )-- def test_simplify_no_such_cohort(self):- filter = Filter(data={"properties": [{"type": "cohort", "key": "id", "value": 555_555}]})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [{"type": "cohort", "key": "id", "value": 555_555}],- }- },- )-- def test_simplify_entities(self):- cohort = Cohort.objects.create(- team=self.team,- groups=[- {- "properties": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ]- }- ],- )- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "properties": [{"type": "cohort", "key": "id", "value": cohort.pk}],- }- ]- }- )-- self.assertEqual(- filter.simplify(self.team).entities_to_dict(),- {- "events": [- {- "type": "events",- "distinct_id_field": None,- "id": "$pageview",- "id_field": None,- "math": None,- "math_hogql": None,- "math_property": None,- "math_property_revenue_currency": None,- "math_group_type_index": None,- "custom_name": None,- "order": None,- "name": "$pageview",- "properties": {- "type": "AND",- "values": [- {- "key": "email",- "operator": "icontains",- "value": ".com",- "type": "person",- }- ],- },- "table_name": None,- "timestamp_field": None,- }- ]- },- )-- def test_simplify_entities_with_group_math(self):- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "math": "unique_group",- "math_group_type_index": 2,- }- ]- }- )-- self.assertEqual(- filter.simplify(self.team).entities_to_dict(),- {- "events": [- {- "type": "events",- "distinct_id_field": None,- "id": "$pageview",- "id_field": None,- "math": "unique_group",- "math_hogql": None,- "math_property": None,- "math_property_revenue_currency": None,- "math_group_type_index": 2,- "custom_name": None,- "order": None,- "name": "$pageview",- "properties": {- "type": "AND",- "values": [- {- "key": "$group_2",- "operator": "is_not",- "value": "",- "type": "event",- }- ],- },- "table_name": None,- "timestamp_field": None,- }- ]- },- )-- def test_simplify_when_aggregating_by_group(self):- filter = RetentionFilter(data={"aggregation_group_type_index": 0})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "key": "$group_0",- "operator": "is_not",- "value": "",- "type": "event",- }- ],- }- },- )-- def test_simplify_funnel_entities_when_aggregating_by_group(self):- filter = Filter(data={"events": [{"id": "$pageview"}], "aggregation_group_type_index": 2})-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "AND",- "values": [- {- "key": "$group_2",- "operator": "is_not",- "value": "",- "type": "event",- }- ],- }- },- )-- def test_simplify_nested(self):- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- }- ],- },- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg2",- },- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg3",- },- ],- },- ],- }- }- )-- # Can't remove the single prop groups if the parent group has multiple. The second list of conditions becomes property groups- # because of simplify now will return prop groups by default to ensure type consistency- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- },- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg2",- }- ],- },- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg3",- }- ],- },- ],- },- ],- }- },- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- }- ],- },- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg2",- }- ],- },- ],- }- }- )-- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": ".com",- }- ],- },- {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "operator": "icontains",- "value": "arg2",- }- ],- },- ],- }- },- )diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.pyindex 7a6afb574cbf..e13236fcac81 100644--- a/ee/clickhouse/queries/test/test_cohort_query.py+++ b/ee/clickhouse/queries/test/test_cohort_query.py@@ -1,5 +1,5 @@from datetime import datetime, timedelta-from typing import Any+from typing import Any, Optionalimport pytestimport unittest@@ -20,7 +20,8 @@ from posthog.schema import PersonsOnEventsModefrom posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.hogql_cohort_query import TestWrapperCohortQuery as CohortQueryfrom posthog.models import Team-from posthog.models.filters.filter import Filter+from posthog.models.property import PropertyGroup+from posthog.models.property.parse import expand_cohort_properties, parse_property_group_datafrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort@@ -59,7 +60,7 @@ def _create_cohort(**kwargs):return cohort-def execute(filter: Filter, team: Team):+def execute(filter: PropertyGroup, team: Team):# Ensure tables are fully merged before reading membership. ClickHouse's eventual# consistency (CollapsingMergeTree and other MergeTree variants) means cohortpeople /# person / events may not be fully merged immediately after the test writes.@@ -67,11 +68,20 @@ def execute(filter: Filter, team: Team):sync_execute("OPTIMIZE TABLE person FINAL")sync_execute("OPTIMIZE TABLE sharded_events FINAL")- cohort_query = CohortQuery(filter=filter, team=team)+ cohort_query = CohortQuery(property_groups=filter, team=team)assert ["id"] == cohort_query.hogql_result.columnsreturn cohort_query.hogql_result.results+def _properties(data: dict, team: Optional[Team] = None) -> PropertyGroup:+ """Parse a legacy insight-filter dict down to the property group CohortQuery takes.++ A team expands cohort properties, as a team-bound filter used to.+ """+ parsed = parse_property_group_data(data.get("properties"))+ return expand_cohort_properties(parsed, team) if team else parsed++class TestCohortQuery(ClickhouseTestMixin, BaseTest):def test_basic_query(self):action1 = Action.objects.create(@@ -197,7 +207,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):}}- filter = Filter(data=data)+ filter = _properties(data=data)res = execute(filter, self.team)@@ -214,7 +224,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):})- filter = Filter(data=data)+ filter = _properties(data=data)res = execute(filter, self.team)@@ -249,7 +259,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -298,7 +308,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -358,7 +368,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -433,7 +443,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -491,7 +501,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -558,7 +568,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -627,7 +637,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -699,7 +709,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -734,7 +744,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):assert {p1.uuid, p2.uuid, p3.uuid} == {r[0] for r in res}def test_performed_event_zero_times_(self):- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -754,7 +764,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):})with pytest.raises(ValueError):- CohortQuery(filter=filter, team=self.team).get_query()+ CohortQuery(property_groups=filter, team=self.team).get_query()def test_stopped_performing_event(self):p1 = _create_person(@@ -784,7 +794,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -874,7 +884,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -930,7 +940,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):distinct_id="p2",timestamp=datetime.now() - timedelta(days=4),)- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -987,7 +997,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1063,7 +1073,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1097,7 +1107,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):# Filter for:# Regularly completed [$pageview] [at least] [1] times per# [3][day] period for at least [3] of the last [3] periods- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1135,7 +1145,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):# Filter for:# Regularly completed [$pageview] [at least] [1] times per# [3][day] period for at least [3] of the last [3] periods- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1209,7 +1219,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):],}}- filter = Filter(data=data)+ filter = _properties(data=data)res = execute(filter, self.team)assert sorted([p1.uuid, p2.uuid, p3.uuid]) == sorted([r[0] for r in res])@@ -1243,7 +1253,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):# Filter for:# Regularly completed [$pageview] [at least] [2] times per# [3][day] period for at least [2] of the last [3] periods- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1272,7 +1282,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):# Filter for:# Regularly completed [$pageview] [at least] [1] times per# [3][day] period for at least [2] of the last [3] periods- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1320,7 +1330,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):properties={"name": "test3", "email": "[email protected]"},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -1430,7 +1440,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1496,7 +1506,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):distinct_ids=["p1"],properties={"name": "test", "$sample_field": "[email protected]"},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -1552,7 +1562,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1572,7 +1582,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)with pytest.raises(ValidationError):- CohortQuery(filter=filter, team=self.team)+ CohortQuery(property_groups=filter, team=self.team)def test_negation_with_simplify_filters(self):_create_person(@@ -1615,7 +1625,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1721,7 +1731,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1857,7 +1867,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -1906,7 +1916,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):cohort.calculate_people_ch(pending_version=0)- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2043,7 +2053,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2079,7 +2089,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2129,7 +2139,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2158,7 +2168,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):# verifies membership, not result cardinality.assert {p2.uuid} == {r[0] for r in res}- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2245,7 +2255,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2283,7 +2293,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()cohort.insert_users_by_list(["p1"])- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2319,7 +2329,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()cohort.insert_users_by_list(["p1", "p2"])- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2342,7 +2352,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):assert [p2.uuid] == [r[0] for r in res]- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2390,7 +2400,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2459,7 +2469,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2516,7 +2526,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2592,7 +2602,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2694,7 +2704,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2783,7 +2793,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "AND",@@ -2860,7 +2870,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)flush_persons_and_events()- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -2966,7 +2976,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3098,7 +3108,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3251,7 +3261,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3353,7 +3363,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):flush_persons_and_events()# "Application Opened" gte 2 times per 1 year for at least 2 of the last 2 years- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3435,7 +3445,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):)# Create filter using the cohort- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3496,7 +3506,7 @@ class TestCohortNegationValidation(BaseTest):},)- filter = Filter(+ filter = _properties(data={"properties": {"type": "OR",@@ -3572,14 +3582,14 @@ class TestCohortNegationValidation(BaseTest):}cohort_query1 = CohortQuery(- filter=Filter(+ property_groups=_properties(data=filter_data,team=self.team,),team=self.team,)cohort_query2 = CohortQuery(- filter=Filter(+ property_groups=_properties(data=filter_data,team=other_team,),diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 84336af85e81..19214e1fb4c9 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -45,10 +45,9 @@ from posthog.api.services.flags_service import (batch_evaluate_flag_for_team,)from posthog.api.shared import SearchMatchTypeSerializerMixin, SerializedPersonActorSerializer, UserBasicSerializer-from posthog.api.utils import action, parse_actor_property_filters+from posthog.api.utils import action, paging_params, parse_actor_property_filtersfrom posthog.cdp.filters import build_behavioral_event_exprfrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.constants import LIMIT, OFFSETfrom posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exception@@ -75,9 +74,9 @@ from posthog.models.activity_logging.activity_log import ()from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_paramsfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.filters.filter import Filterfrom posthog.models.filters.utils import earliest_timestamp_funcfrom posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist+from posthog.models.property.parse import expand_cohort_properties, parse_property_group_datafrom posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS, Propertyfrom posthog.models.property.relative_date import determine_parsed_date_for_property_matchingfrom posthog.models.team.team import DEPRECATED_ATTRS, Team@@ -1338,7 +1337,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializtry:if properties:HogQLCohortQuery(- filter=Filter(data={"properties": properties}, team=team), team=team+ property_groups=expand_cohort_properties(parse_property_group_data(properties), team), team=team).get_query_executor(user=user).generate_clickhouse_sql()if query:context = HogQLContext(team_id=team.pk, team=team, user=user, enable_select_queries=True)@@ -1399,7 +1398,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializif self.context["request"].method != "PATCH":return- parsed_filter = Filter(data=request_filters)+ parsed_filter = parse_property_group_data(request_filters.get("properties"))instance = cast(Cohort, self.instance)if instance.is_static and cohort_will_be_static:return@@ -1415,7 +1414,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializif not cohort_used_in_flags:return- for prop in parsed_filter.property_groups.flat:+ for prop in parsed_filter.flat:if prop.type == "behavioral":raise serializers.ValidationError(detail="Behavioral filters cannot be added to cohorts used in feature flags.",@@ -1952,14 +1951,16 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVidef persons(self, request: Request, **kwargs) -> Response:cohort: Cohort = self.get_object()team = self.team- filter = Filter(request=request, team=self.team)assert request.user.is_authenticated+ paging = paging_params(request)+ limit = paging.limit+ offset = paging.offsetis_csv_request = self.request.accepted_renderer.format == "csv" or request.GET.get("is_csv_export")- if is_csv_request and not filter.limit:- filter = filter.shallow_clone({LIMIT: CSV_EXPORT_LIMIT, OFFSET: 0})- elif not filter.limit:- filter = filter.shallow_clone({LIMIT: 100})+ if is_csv_request and not limit:+ limit, offset = CSV_EXPORT_LIMIT, 0+ elif not limit:+ limit = 100tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)cohort_properties: list[dict] = [{"type": "cohort", "key": "id", "value": cohort.pk}]@@ -1972,22 +1973,18 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi# Match the legacy PersonQuery ordering (created_at DESC, id DESC) so pagination# leads with the newest members; ActorsQuery otherwise defaults to id ASC.orderBy=["created_at DESC", "id DESC"],- limit=filter.limit,- offset=filter.offset,+ limit=limit,+ offset=offset,)actors_response = ActorsQueryRunner(team=team, query=actors_query).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)actor_ids = [row[0] for row in actors_response.results]with personhog_caller_tag("cohorts/persons"):serialized_actors = get_serialized_people(team, actor_ids, distinct_id_limit=10)- _should_paginate = len(actor_ids) >= filter.limit+ _should_paginate = len(actor_ids) >= limit- next_url = format_query_params_absolute_url(request, filter.offset + filter.limit) if _should_paginate else None- previous_url = (- format_query_params_absolute_url(request, filter.offset - filter.limit)- if filter.offset - filter.limit >= 0- else None- )+ next_url = format_query_params_absolute_url(request, offset + limit) if _should_paginate else None+ previous_url = format_query_params_absolute_url(request, offset - limit) if offset - limit >= 0 else Noneif is_csv_request:KEYS_ORDER = ["id",diff --git a/posthog/api/element.py b/posthog/api/element.pyindex becc842fe87c..399373e3cef2 100644--- a/posthog/api/element.py+++ b/posthog/api/element.py@@ -23,9 +23,10 @@ from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ServerTimingsGathered, actionfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.models import Element, Filter, Team+from posthog.models import Element, Teamfrom posthog.models.element.chain_query import normalized_elements_chain_exprfrom posthog.models.element.element import build_attributes_filter, chain_to_element_dicts+from posthog.models.property.parse import parse_properties_for_teamfrom posthog.permissions import posthog_feature_flag_enabledfrom posthog.utils import format_query_params_absolute_url@@ -181,9 +182,7 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):timer = ServerTimingsGathered()with timer("prepare_for_query"), tracer.start_as_current_span("elements_api_stats.prepare_for_query"):- # Filter parses the properties param (including property groups) and folds the- # team's test-account filters in when filter_test_accounts is set- filter = Filter(request=request, team=self.team)+ property_groups = parse_properties_for_team(request.GET.dict(), self.team)date_range = QueryDateRange(date_range=DateRange(date_from=request.query_params.get("date_from", "-7d"),@@ -257,7 +256,7 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"event_types": ast.Constant(value=list(events_filter)),"date_from": ast.Constant(value=query_date_from),"date_to": ast.Constant(value=date_range.date_to()),- "property_filters": property_to_expr(filter.property_groups, team=self.team),+ "property_filters": property_to_expr(property_groups, team=self.team),"limit": ast.Constant(value=limit + 1),"offset": ast.Constant(value=offset),},diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 66323db01d02..cfa7b4e23e1a 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -40,10 +40,9 @@ from posthog.api.fields import CoercedStringListFieldfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.utils import action, parse_actor_property_filters+from posthog.api.utils import action, paging_params, parse_actor_property_filtersfrom posthog.auth import PersonalAPIKeyAuthenticationfrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.constants import LIMIT, OFFSETfrom posthog.errors import ExposedCHQueryError, QueryErrorCategory, classify_query_errorfrom posthog.event_usage import get_request_analytics_propertiesfrom posthog.exceptions_capture import capture_exception@@ -51,7 +50,7 @@ from posthog.helpers.impersonation import is_impersonatedfrom posthog.hogql_queries.properties_timeline import PropertiesTimelinefrom posthog.hogql_queries.serialized_actors import SerializedPerson, get_serialized_peoplefrom posthog.metrics import LABEL_TEAM_ID-from posthog.models import Filter, Person, Team, User+from posthog.models import Person, Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_paramsfrom posthog.models.async_deletion import AsyncDeletion, DeletionType@@ -731,15 +730,17 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):client_query_id = request.GET.get("client_query_id")tag_client_query_id(client_query_id)team = self.team- filter = Filter(request=request, team=self.team)-assert request.user.is_authenticated+ paging = paging_params(request)+ limit = paging.limit+ offset = paging.offset+is_csv_request = self.request.accepted_renderer.format == "csv"if is_csv_request:- filter = filter.shallow_clone({LIMIT: CSV_EXPORT_LIMIT, OFFSET: 0})- elif not filter.limit:- filter = filter.shallow_clone({LIMIT: DEFAULT_PAGE_LIMIT})+ limit, offset = CSV_EXPORT_LIMIT, 0+ elif not limit:+ limit = DEFAULT_PAGE_LIMITfrom posthog.hogql import ast # noqa: PLC0415 — deferred to avoid a circular import at module loadfrom posthog.hogql.query import execute_hogql_query # noqa: PLC0415@@ -747,33 +748,35 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415person_properties: list[dict] = parse_actor_property_filters(request.GET.get("properties"))- if filter.email:- person_properties.append({"type": "person", "key": "email", "value": filter.email, "operator": "exact"})+ if request.GET.get("email"):+ person_properties.append(+ {"type": "person", "key": "email", "value": request.GET.get("email"), "operator": "exact"}+ )include_total = "include_total" in request.GETinclude_matched_fields = str_to_bool(request.GET.get("include_matched_fields"))- search = (filter.search or "").strip()+ search = (request.GET.get("search") or "").strip()tag_term = search if include_matched_fields else None# Nothing else narrows the result set, so an identifier that resolves over personhog is# already the whole first page, and a ClickHouse scan would add nothing. A tagged search# needs the hit on every page, because it leads the tagged sequence.- can_answer_from_identifier = not person_properties and (filter.offset == 0 or include_matched_fields)+ can_answer_from_identifier = not person_properties and (offset == 0 or include_matched_fields)# This endpoint bypasses `QueryRunner.run()`, so nothing else measures how long it takes.# The search path is the slow one, so the shape of the request is recorded alongside the# duration. The search term itself is never recorded - it is user data.slo_properties: dict[str, JsonValue] = {"query_type": "ActorsQuery",- "has_search": bool(filter.search),+ "has_search": bool(request.GET.get("search")),"has_properties": bool(person_properties),- "has_distinct_id": bool(filter.distinct_id),+ "has_distinct_id": bool(request.GET.get("distinct_id")),# Only a caller that can cancel sends an id, which is what separates the command# palette's searches from the persons page's on the dashboard."has_client_query_id": bool(client_query_id),"include_total": include_total,"is_csv": is_csv_request,- "limit": filter.limit,- "offset": filter.offset,+ "limit": limit,+ "offset": offset,}# The block wraps the identifier fast paths too, not just the ClickHouse one. Measuring# only the slow path would drop every fast answer out of the sample, so the endpoint would@@ -794,22 +797,26 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):properties: list[dict] | dict[str, Any] = person_propertiesorder_by = ["created_at DESC", "id DESC"]answered_by = "clickhouse"- if filter.distinct_id:+ exact_distinct_id = request.GET.get("distinct_id")+ if exact_distinct_id:# Exact match on any of the person's distinct IDs; no matching person => no results.- matched = get_person_by_distinct_id(team.pk, filter.distinct_id, distinct_id_limit=0)+ matched = get_person_by_distinct_id(team.pk, exact_distinct_id, distinct_id_limit=0)if matched is None:# Return early: a constant-false predicate can't be pushed into the persons# lazy table, so ClickHouse would still aggregate every person row for the# team before filtering everything out.slo.tag(answered_by="exact_identifier", result_count=0)- return self._person_list_response(request, [], filter, total_count=0 if include_total else None)+ return self._person_list_response(+ request, [], limit, offset, total_count=0 if include_total else None+ )if can_answer_from_identifier and not search:- page = [str(matched.uuid)][filter.offset : filter.offset + filter.limit]+ page = [str(matched.uuid)][offset : offset + limit]slo.tag(answered_by="exact_identifier", result_count=len(page))return self._person_list_response(request,page,- filter,+ limit,+ offset,total_count=1 if include_total else None,has_next=False,)@@ -822,14 +829,15 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)if exact_hits and not email_property_search:API_PERSON_LIST_SEARCH_COUNTER.labels(answered_by="exact_identifier").inc()- page = list(exact_hits)[filter.offset : filter.offset + filter.limit]+ page = list(exact_hits)[offset : offset + limit]slo.tag(answered_by="exact_identifier", result_count=len(page))return self._person_list_response(request,page,- filter,+ limit,+ offset,total_count=len(exact_hits) if include_total else None,- has_next=len(exact_hits) > filter.offset + filter.limit,+ has_next=len(exact_hits) > offset + limit,tag_term=tag_term,exact_hits=exact_hits,)@@ -855,15 +863,15 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):properties=properties,search=None if email_property_search else search or None,orderBy=order_by,- limit=filter.limit,- offset=filter.offset,+ limit=limit,+ offset=offset,)# Use .calculate() (not .run()) — it applies the limit/offset paginator but skips the# insight-caching wrapper. With an id-only select there's no actor-column hydration, so# we still hydrate the person objects ourselves via get_serialized_people.actors_runner = ActorsQueryRunner(team=team, query=actors_query)# ClickHouse can lag behind personhog or fail, so the hit leads the first page regardless.- hit_leads_page = email_property_search and filter.offset == 0+ hit_leads_page = email_property_search and offset == 0actor_ids: list[Any] = []total_count: Optional[int] = None# A cancel kills every ClickHouse query the request has in flight, so both queries below@@ -910,14 +918,15 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):slo.tag(answered_by=answered_by, result_count=len(actor_ids))return self._person_list_response(- request, actor_ids, filter, total_count=total_count, tag_term=tag_term, exact_hits=exact_hits+ request, actor_ids, limit, offset, total_count=total_count, tag_term=tag_term, exact_hits=exact_hits)def _person_list_response(self,request: request.Request,person_uuids: builtins.list[Any],- filter: Filter,+ limit: int,+ offset: int,total_count: Optional[int] = None,has_next: Optional[bool] = None,tag_term: Optional[str] = None,@@ -950,14 +959,10 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# A full page means there may be more behind it. Callers that know the whole result set up# front say so instead, so a page that happens to fill the limit does not advertise an# empty page after it.- _should_paginate = len(person_uuids) >= filter.limit if has_next is None else has_next+ _should_paginate = len(person_uuids) >= limit if has_next is None else has_next- next_url = format_query_params_absolute_url(request, filter.offset + filter.limit) if _should_paginate else None- previous_url = (- format_query_params_absolute_url(request, filter.offset - filter.limit)- if filter.offset - filter.limit >= 0- else None- )+ next_url = format_query_params_absolute_url(request, offset + limit) if _should_paginate else None+ previous_url = format_query_params_absolute_url(request, offset - limit) if offset - limit >= 0 else None# TEMPORARY: Work out usage patterns of this endpointrenderer = SafeJSONRenderer()diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 186fb98b04b9..b4e6e5a81376 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -22,7 +22,7 @@ from posthog.api.test.dashboards import DashboardAPIfrom posthog.caching.insight_result import InsightResultfrom posthog.constants import AvailableFeaturefrom posthog.helpers.dashboard_templates import create_from_template, create_group_type_mapping_detail_dashboard-from posthog.models import Filter, Team, User+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.file_system.file_system_view_log import FileSystemViewLog@@ -1107,15 +1107,10 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):def test_no_cache_available(self):dashboard = Dashboard.objects.create(team=self.team, name="dashboard")- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-with time_machine.travel("2020-01-04T13:00:01Z", tick=False):# Pretend we cached something a while ago, but we won't have anything in the redis cacheinsight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,last_refresh=now(),)diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.pyindex 4141529bc22e..7943ca1770b2 100644--- a/posthog/api/test/test_element.py+++ b/posthog/api/test/test_element.py@@ -209,6 +209,11 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):response = self.client.get(f"/api/element/stats/?paginate_response=true&properties={properties_filter}").json()self.assertEqual(len(response["results"]), 1)+ # An empty value means no filter, the same as omitting the parameter.+ empty = self.client.get("/api/element/stats/?paginate_response=true&properties=")+ self.assertEqual(empty.status_code, status.HTTP_200_OK)+ self.assertEqual(len(empty.json()["results"]), 3)+@parameterized.expand([(False, False), (True, False), (True, True)])def test_element_stats_can_filter_by_person_properties(self, person_on_events: bool, poe_v2: bool) -> None:with override_settings(PERSON_ON_EVENTS_OVERRIDE=person_on_events, PERSON_ON_EVENTS_V2_OVERRIDE=poe_v2):diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex fc0070defe0c..769abc33cbac 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -2125,6 +2125,17 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ @parameterized.expand(+ [+ ("junk_limit", "limit=not-a-number"),+ ("junk_offset", "offset=not-a-number"),+ ]+ )+ def test_list_rejects_non_integer_pagination_params(self, _name: str, query: str):+ response = self.client.get(f"/api/person/?{query}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_csv_export(self):_create_person(team=self.team,diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 506bafa5e19f..b368ed1f94c3 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -28,10 +28,10 @@ from posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, decode_jwtfrom posthog.models import ActivityLog, OrganizationMembershipfrom posthog.models.data_color_theme import DataColorTheme-from posthog.models.filters.filter import Filterfrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import User+from posthog.test.insight_queries import browser_filtered_pageview_queryfrom products.access_control.backend.models.access_control import AccessControlfrom products.alerts.backend.models.alert import AlertConfiguration@@ -123,18 +123,13 @@ class TestSharing(APIBaseTest):dashboard: Dashboard = None # type: ignoreinsight: Insight = None # type: ignore- insight_filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-@classmethoddef setUpTestData(cls):super().setUpTestData()cls.dashboard = Dashboard.objects.create(team=cls.team, name="example dashboard", created_by=cls.user)cls.insight = Insight.objects.create(- filters=Filter(data=cls.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=cls.team,created_by=cls.user,)diff --git a/posthog/api/test/test_utils.py b/posthog/api/test/test_utils.pyindex 5ceb43c5fa75..c741976f975b 100644--- a/posthog/api/test/test_utils.py+++ b/posthog/api/test/test_utils.py@@ -15,7 +15,6 @@ from posthog.api.utils import (check_definition_ids_inclusion_field_sql,format_paginated_url,get_data,- get_target_entity,hostname_in_allowed_url_list,is_async_query,is_insight_query,@@ -27,7 +26,6 @@ from posthog.api.utils import (strip_url_userinfo,unparsed_hostname_in_allowed_url_list,)-from posthog.models.filters.filter import Filterfrom posthog.test.base import BaseTest@@ -116,38 +114,6 @@ class TestUtils(BaseTest):"api/some_url?offset=0",)- def test_get_target_entity(self):- request = lambda url: cast(Any, RequestFactory().get(url))- filter = Filter(- data={- "entity_id": "$pageview",- "entity_type": "events",- "events": [{"id": "$pageview", "type": "events"}],- }- )- entity = get_target_entity(filter)-- assert entity.id == "$pageview"- assert entity.type == "events"- assert entity.math is None-- filter = Filter(- data={- "entity_id": "$pageview",- "entity_type": "events",- "entity_math": "unique_group",- "events": [- {"id": "$pageview", "type": "events", "math": "unique_group"},- {"id": "$pageview", "type": "events"},- ],- }- )- entity = get_target_entity(filter)-- assert entity.id == "$pageview"- assert entity.type == "events"- assert entity.math == "unique_group"-def test_check_definition_ids_inclusion_field_sql(self):definition_ids = ["",diff --git a/posthog/api/utils.py b/posthog/api/utils.pyindex a9cd6fe01c18..4eb91241258b 100644--- a/posthog/api/utils.py+++ b/posthog/api/utils.py@@ -29,6 +29,8 @@ from urllib3 import HTTPConnectionPool, HTTPSConnectionPool, PoolManagerfrom posthog.schema import QueryTimingfrom posthog.api.documentation import extend_schema+from posthog.constants import LIMIT, OFFSET+from posthog.dataclasses import frozenfrom posthog.exceptions import (RequestParsingError,UnspecifiedCompressionFallbackParsingError,@@ -36,11 +38,8 @@ from posthog.exceptions import ()from posthog.helpers.impersonation import is_impersonatedfrom posthog.hogql_queries.legacy_compatibility.clean_properties import clean_property-from posthog.models import Entity, User+from posthog.models import Userfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity-from posthog.models.entity import MathType-from posthog.models.filters.filter import Filter-from posthog.models.filters.stickiness_filter import StickinessFilterfrom posthog.security.url_validation import has_ambiguous_authorityfrom posthog.utils import load_data_from_requestfrom posthog.utils_cors import cors_response@@ -92,80 +91,6 @@ class ClassicBehaviorBooleanFieldSerializer(serializers.BooleanField):Field.__init__(self, allow_null=True, required=False, **kwargs)-def get_target_entity(filter: Union[Filter, StickinessFilter]) -> Entity:- # Except for "events", we require an entity id and type to be provided- if not filter.target_entity_id and filter.target_entity_type != "events":- raise ValidationError("An entity id and the entity type must be provided to determine an entity")-- entity_math = filter.target_entity_math or "total" # make math explicit- possible_entity = entity_from_order(filter.target_entity_order, filter.entities)-- if possible_entity:- return possible_entity-- possible_entity = retrieve_entity_from(- filter.target_entity_id,- filter.target_entity_type,- entity_math,- filter.events,- filter.actions,- )- if possible_entity:- return possible_entity- elif filter.target_entity_type:- return Entity(- {- "id": filter.target_entity_id,- "type": filter.target_entity_type,- "math": entity_math,- }- )- else:- raise ValidationError("An entity must be provided for target entity to be determined")---def entity_from_order(order: Optional[str], entities: list[Entity]) -> Optional[Entity]:- if not order:- return None-- for entity in entities:- if entity.index == int(order):- return entity- return None---def retrieve_entity_from(- entity_id: Optional[str],- entity_type: Optional[str],- entity_math: MathType,- events: list[Entity],- actions: list[Entity],-) -> Optional[Entity]:- """- Retrieves the entity from the events and actions.-- NOTE: entity_id here is considered always to be a string. event ids are- strings, and action ids are ints. Elsewhere we get the `entity_id` from a- get request, from which we do not get type information, and we do not- require the entity type to be provided. A more complete solution might be to- require entity type information, but to resolve the issue we cast the action- id to a string, such that we can get equality.-- This doesn't preclude ths issue that an event name could be a string that is- also a valid number however, but this should be an unlikely occurance.- """-- if entity_type == "actions":- for action in actions:- if action.id == entity_id and (action.math or "total") == entity_math:- return action- else:- for event in events:- if event.id == entity_id and (event.math or "total") == entity_math:- return event- return None--def format_paginated_url(request: request.Request, offset: int, page_size: int, mode=PaginationMode.next):result = request.get_full_path()if not result:@@ -824,3 +749,28 @@ def log_activity_from_viewset()except:pass+++@frozen+class Paging:+ """A page of results asked for by `limit` and `offset`. Either is 0 when the client sends neither."""++ limit: int+ offset: int+++def _paging_param(raw: str | None, name: str) -> int:+ if not raw:+ return 0+ try:+ return int(raw)+ except ValueError as error:+ raise ValidationError(f"'{name}' must be an integer") from error+++def paging_params(request: request.Request) -> Paging:+ """Read the `limit` and `offset` query params, defaulting either to 0 when absent or empty."""+ return Paging(+ limit=_paging_param(request.GET.get(LIMIT), LIMIT),+ offset=_paging_param(request.GET.get(OFFSET), OFFSET),+ )diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex a58f22123f7f..e9e1512a37d9 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -44,8 +44,9 @@ from posthog.hogql.query import HogQLQueryExecutorfrom posthog.constants import PropertyOperatorTypefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.events_query_runner import EventsQueryRunner-from posthog.models import Filter, Property, Team, User+from posthog.models import Property, Team, Userfrom posthog.models.property import OperatorInterval, PropertyGroup+from posthog.models.property.parse import expand_cohort_properties, parse_property_group_datafrom posthog.ph_client import feature_enabled_or_falsefrom posthog.types import AnyPropertyFilter@@ -88,7 +89,9 @@ def _require_select_query(query: ast.SelectQuery | ast.SelectSetQuery) -> ast.Sereturn query-def unwrap_cohort(filter: Filter, team_id: int, team: Optional[Team] = None, cohort: Optional[Cohort] = None) -> Filter:+def unwrap_cohort(+ property_groups: PropertyGroup, team_id: int, team: Optional[Team] = None, cohort: Optional[Cohort] = None+) -> PropertyGroup:"""Flatten cohort-typed properties into nested static/dynamic-cohort PropertyGroups.Each ``cohort``/``precalculated-cohort`` property is replaced by an AND group holding a@@ -182,8 +185,7 @@ def unwrap_cohort(filter: Filter, team_id: int, team: Optional[Team] = None, cohreturn property_group- new_props = _unwrap(filter.property_groups)- return filter.shallow_clone({"properties": new_props.to_dict()})+ return _unwrap(property_groups)class TestWrapperCohortQuery:@@ -193,8 +195,8 @@ class TestWrapperCohortQuery:``clickhouse_query`` / ``get_query`` expose the generated SQL."""- def __init__(self, filter: Filter, team: Team):- executor = HogQLCohortQuery(filter=filter, team=team).get_query_executor()+ def __init__(self, property_groups: PropertyGroup, team: Team):+ executor = HogQLCohortQuery(property_groups=property_groups, team=team).get_query_executor()self.hogql_result = executor.execute()self.clickhouse_query = executor.clickhouse_sql@@ -245,24 +247,19 @@ def _person_test_account_properties(team: Team) -> list[Property]:class HogQLCohortQuery:def __init__(self,- filter: Optional[Filter] = None,+ property_groups: Optional[PropertyGroup] = None,cohort: Optional[Cohort] = None,team: Optional[Team] = None,):if cohort is not None:self.hogql_context = HogQLContext(team_id=cohort.team.pk, enable_select_queries=True)self.team = team or cohort.team- unwrapped = unwrap_cohort(- Filter(- data={"properties": cohort.properties},- team=cohort.team,- hogql_context=self.hogql_context,- ),+ property_groups = unwrap_cohort(+ expand_cohort_properties(parse_property_group_data(cohort.properties), cohort.team),self.team.pk,self.team,cohort,)- property_groups = unwrapped.property_groupsif (cohort.filters or {}).get("filterTestAccounts"):test_props = _person_test_account_properties(self.team)if test_props:@@ -274,14 +271,14 @@ class HogQLCohortQuery:],)self.property_groups = property_groups- elif filter is not None:+ elif property_groups is not None:if team is None:- raise ValueError("HogQLCohortQuery requires a team when constructed from a filter")+ raise ValueError("HogQLCohortQuery requires a team when constructed from properties")self.hogql_context = HogQLContext(team_id=team.pk, enable_select_queries=True)self.team = team- self.property_groups = unwrap_cohort(filter, team.pk, team).property_groups+ self.property_groups = unwrap_cohort(property_groups, team.pk, team)else:- raise ValueError("HogQLCohortQuery requires either a cohort or a filter")+ raise ValueError("HogQLCohortQuery requires either a cohort or properties")def get_query_executor(self, *, user: Optional[User] = None, bypass_warehouse_access_control: bool = False@@ -328,7 +325,7 @@ class HogQLCohortQuery:series = self._get_series(prop, math)if prop.event_filters:- filter = Filter(data={"properties": prop.event_filters}).property_groups+ filter = parse_property_group_data(prop.event_filters)series[0].properties = filterif prop.explicit_datetime:@@ -384,7 +381,7 @@ class HogQLCohortQuery:raise ValidationError("count_operator must be gt(e), lt(e), exact, or None")if prop.event_filters:- property_groups = Filter(data={"properties": prop.event_filters}).property_groups+ property_groups = parse_property_group_data(prop.event_filters)typed_properties: list[AnyPropertyFilter] = []for property in property_groups.values:if isinstance(property, PropertyGroup):diff --git a/posthog/hogql_queries/properties_timeline/properties_timeline.py b/posthog/hogql_queries/properties_timeline/properties_timeline.pyindex d461842037f3..69562c0df963 100644--- a/posthog/hogql_queries/properties_timeline/properties_timeline.py+++ b/posthog/hogql_queries/properties_timeline/properties_timeline.py@@ -1,7 +1,7 @@import jsonimport datetimefrom datetime import timedelta-from typing import Any, TypedDict, TypeVar, Union, cast+from typing import Any, TypedDict, Union, castfrom zoneinfo import ZoneInfofrom dateutil.relativedelta import relativedelta@@ -16,7 +16,6 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.constants import NON_TIME_SERIES_DISPLAY_TYPES, TREND_FILTER_TYPE_ACTIONSfrom posthog.hogql_queries.properties_timeline.query_date_range import QueryDateRangefrom posthog.models.entity import Entity-from posthog.models.filters import Filterfrom posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterfrom posthog.models.group.group import Groupfrom posthog.models.person.person import Person@@ -25,10 +24,10 @@ from posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action-F = TypeVar("F", Filter, PropertiesTimelineFilter)--def offset_time_series_date_by_interval(date: datetime.datetime, *, filter: F, team: Team) -> datetime.datetime:+def offset_time_series_date_by_interval(+ date: datetime.datetime, *, filter: PropertiesTimelineFilter, team: Team+) -> datetime.datetime:"""If the insight is time-series, offset date according to the interval of the filter."""if filter.display in NON_TIME_SERIES_DISPLAY_TYPES:return datediff --git a/posthog/hogql_queries/properties_timeline/query_date_range.py b/posthog/hogql_queries/properties_timeline/query_date_range.pyindex a924eddf66f5..ded7b1a7c108 100644--- a/posthog/hogql_queries/properties_timeline/query_date_range.py+++ b/posthog/hogql_queries/properties_timeline/query_date_range.py@@ -9,9 +9,9 @@ from dateutil.relativedelta import relativedeltafrom rest_framework.exceptions import ValidationErrorfrom posthog.interval_specs import UnsupportedIntervalError, get_trunc_func-from posthog.models.filters import AnyFilterfrom posthog.models.filters.base_filter import BaseFilterfrom posthog.models.filters.mixins.interval import IntervalMixin+from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterfrom posthog.models.team import Teamfrom posthog.models.team.team import WeekStartDayfrom posthog.utils import DEFAULT_DATE_FROM_DAYS, relative_date_parse, relative_date_parse_with_delta_mapping@@ -60,7 +60,7 @@ class QueryDateRange:- a datetime already (only for filters constructed internally)"""- _filter: AnyFilter+ _filter: PropertiesTimelineFilter_team: Team_table: str_should_round: Optional[bool]@@ -68,7 +68,7 @@ class QueryDateRange:def __init__(self,- filter: AnyFilter,+ filter: PropertiesTimelineFilter,team: Team,should_round: Optional[bool] = None,table="",diff --git a/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py b/posthog/hogql_queries/properties_timeline/test/test_query_date_range.pyindex f81a1093540e..06aacbd05ff9 100644--- a/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py+++ b/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py@@ -2,13 +2,13 @@ import time_machinefrom posthog.test.base import APIBaseTestfrom posthog.hogql_queries.properties_timeline.query_date_range import QueryDateRange-from posthog.models.filters.filter import Filter+from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterclass TestQueryDateRange(APIBaseTest):def test_parsed_date(self):with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "-48h","interval": "day",@@ -31,7 +31,7 @@ class TestQueryDateRange(APIBaseTest):def test_parsed_date_hour(self):with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "-48h","interval": "hour",@@ -54,7 +54,7 @@ class TestQueryDateRange(APIBaseTest):def test_parsed_date_middle_of_hour(self):with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "2021-08-23 05:00:00","date_to": "2021-08-26 07:00:00",@@ -78,7 +78,7 @@ class TestQueryDateRange(APIBaseTest):def test_parsed_date_week_rounded(self):with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "-7d","interval": "week",@@ -101,7 +101,7 @@ class TestQueryDateRange(APIBaseTest):def test_is_hourly(self):with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "-48h","interval": "day",@@ -116,7 +116,7 @@ class TestQueryDateRange(APIBaseTest):self.assertFalse(query_date_range.is_hourly(None))with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):- filter = Filter(+ filter = PropertiesTimelineFilter(data={"date_from": "-48h","interval": "hour",diff --git a/posthog/migrations/0071_cache_dashboard_items.py b/posthog/migrations/0071_cache_dashboard_items.pyindex 9b9d1b2b72a7..d418ae7935fa 100644--- a/posthog/migrations/0071_cache_dashboard_items.py+++ b/posthog/migrations/0071_cache_dashboard_items.py@@ -4,9 +4,10 @@ import secretsfrom django.db import migrations, models-from posthog.models import Filter-+# The legacy Filter this normalized is gone. The migration is elidable and replaced by+# 0001_squash_2026_09_07_initial, so a fresh database never runs it and an existing one+# applied it years ago; the normalization is left out rather than reimplemented.def forwards_func(apps, schema_editor):Dashboard = apps.get_model("posthog", "Dashboard")DashboardItem = apps.get_model("posthog", "DashboardItem")@@ -21,7 +22,6 @@ def forwards_func(apps, schema_editor):continueif item.filters.get("funnel_id"):item.funnel_id = item.filters["funnel_id"]- item.filters = Filter(data=item.filters).to_dict()item.save()diff --git a/posthog/migrations/0073_update_dashboard_item_filters.py b/posthog/migrations/0073_update_dashboard_item_filters.pyindex d4310df88ef1..45837e5f6612 100644--- a/posthog/migrations/0073_update_dashboard_item_filters.py+++ b/posthog/migrations/0073_update_dashboard_item_filters.py@@ -2,17 +2,12 @@from django.db import migrations-from posthog.models import Filter-+# The legacy Filter this normalized is gone. The migration is elidable and replaced by+# 0001_squash_2026_09_07_initial, so a fresh database never runs it and an existing one+# applied it years ago; the normalization is left out rather than reimplemented.def forwards_func(apps, schema_editor):- DashboardItem = apps.get_model("posthog", "DashboardItem")- items = DashboardItem.objects.filter(filters__isnull=False)- for item in items:- if item.filters == {}:- continue- item.filters = Filter(data=item.filters).to_dict()- item.save()+ passdef reverse_func(apps, schema_editor):diff --git a/posthog/migrations/0102_dashboarditem_filters_hash.py b/posthog/migrations/0102_dashboarditem_filters_hash.pyindex 93ef27c4ff49..22b650096bd2 100644--- a/posthog/migrations/0102_dashboarditem_filters_hash.py+++ b/posthog/migrations/0102_dashboarditem_filters_hash.py@@ -1,23 +1,13 @@# Generated by Django 3.0.6 on 2020-11-24 11:39-import hashlib-from django.db import migrations, models-from posthog.models.filters import Filter---def generate_cache_key(stringified: str) -> str:- # nosemgrep: python.lang.security.insecure-hash-algorithms-md5.insecure-hash-algorithm-md5- return "cache_" + hashlib.md5(stringified.encode("utf-8")).hexdigest()-+# The legacy Filter this built the hash from is gone. The migration is elidable and replaced+# by 0001_squash_2026_09_07_initial, so a fresh database never runs it and an existing one+# applied it years ago; the backfill is left out rather than reimplemented.def forward(apps, schema_editor):- DashboardItem = apps.get_model("posthog", "DashboardItem")- for item in DashboardItem.objects.filter(filters__isnull=False, dashboard__isnull=False).exclude(filters={}):- filter = Filter(data=item.filters)- item.filters_hash = generate_cache_key(f"{filter.toJSON()}_{item.team_id}")- item.save()+ passdef reverse(apps, schema_editor):diff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 5a2daf6f1543..5303ea01d1fd 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -29,7 +29,7 @@ from .file_system.file_system import FileSystemfrom .file_system.file_system_home_folder import FileSystemHomeFolderfrom .file_system.file_system_view_log import FileSystemViewLogfrom .file_system.user_product_list import UserProductList-from .filters import Filter, RetentionFilter+from .filters import RetentionFilterfrom .group import Groupfrom .group_usage_metric import GroupUsageMetricfrom .group_type_mapping import GroupTypeMapping@@ -113,7 +113,6 @@ __all__ = ["FileSystemHomeFolder","FileSystemViewLog","UserProductList",- "Filter","Group","GroupUsageMetric","GroupTypeMapping",diff --git a/posthog/models/entity/entity.py b/posthog/models/entity/entity.pyindex 8779f024d405..fe194359e328 100644--- a/posthog/models/entity/entity.py+++ b/posthog/models/entity/entity.py@@ -1,3 +1,4 @@+import jsonimport inspectfrom collections import Counterfrom typing import TYPE_CHECKING, Any, Literal, Optional@@ -6,7 +7,14 @@ from django.conf import settingsfrom rest_framework.exceptions import ValidationError-from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS+from posthog.constants import (+ ACTIONS,+ DATA_WAREHOUSE_ENTITIES,+ EVENTS,+ TREND_FILTER_TYPE_ACTIONS,+ TREND_FILTER_TYPE_DATA_WAREHOUSE,+ TREND_FILTER_TYPE_EVENTS,+)from posthog.models.filters.mixins.funnel import FunnelFromToStepsMixinfrom posthog.models.filters.mixins.property import PropertyMixinfrom posthog.models.filters.utils import validate_group_type_index@@ -216,3 +224,24 @@ class ExclusionEntity(Entity, FunnelFromToStepsMixin):ret.update(func())return ret+++def parse_entities(data: dict) -> list["Entity"]:+ """Build the ordered entity list from an insight-style filter dict."""+ processed_entities: list[Entity] = []+ for key, entity_type in (+ (ACTIONS, TREND_FILTER_TYPE_ACTIONS),+ (EVENTS, TREND_FILTER_TYPE_EVENTS),+ (DATA_WAREHOUSE_ENTITIES, TREND_FILTER_TYPE_DATA_WAREHOUSE),+ ):+ raw = data.get(key)+ if not raw:+ continue+ if isinstance(raw, str):+ raw = json.loads(raw)+ processed_entities.extend([Entity({**entity, "type": entity_type}) for entity in raw])++ processed_entities.sort(key=lambda entity: entity.order if entity.order else -1)+ for index, entity in enumerate(processed_entities):+ entity.index = index+ return processed_entitiesdiff --git a/posthog/models/filters/__init__.py b/posthog/models/filters/__init__.pyindex 9b2c8f49f739..fc5496ea745e 100644--- a/posthog/models/filters/__init__.py+++ b/posthog/models/filters/__init__.py@@ -1,18 +1,11 @@-from .filter import Filterfrom .path_filter import PathFilterfrom .properties_timeline_filter import PropertiesTimelineFilterfrom .retention_filter import RetentionFilterfrom .stickiness_filter import StickinessFilter__all__ = [- "Filter","PathFilter","RetentionFilter","StickinessFilter","PropertiesTimelineFilter",- "AnyFilter",]--type AnyFilter = Filter | PathFilter | RetentionFilter | StickinessFilter | PropertiesTimelineFilter--type AnyInsightFilter = Filter | PathFilter | RetentionFilter | StickinessFilterdiff --git a/posthog/models/filters/filter.py b/posthog/models/filters/filter.pydeleted file mode 100644index 4cebe94146bd..000000000000--- a/posthog/models/filters/filter.py+++ /dev/null@@ -1,99 +0,0 @@-from .base_filter import BaseFilter-from .mixins.common import (- BreakdownMixin,- BreakdownValueMixin,- ClientQueryIdMixin,- CompareMixin,- DateMixin,- DisplayDerivedMixin,- DistinctIdMixin,- EmailMixin,- EntitiesMixin,- EntityIdMixin,- EntityMathMixin,- EntityOrderMixin,- EntityTypeMixin,- FilterTestAccountsMixin,- # FormulaMixin,- IncludeRecordingsMixin,- InsightMixin,- LimitMixin,- OffsetMixin,- SampleMixin,- SearchMixin,- SelectorMixin,- ShownAsMixin,- SmoothingIntervalsMixin,- UpdatedAfterMixin,-)-from .mixins.funnel import (- FunnelCorrelationActorsMixin,- FunnelCorrelationMixin,- FunnelFromToStepsMixin,- FunnelHogQLAggregationMixin,- FunnelLayoutMixin,- FunnelPersonsStepBreakdownMixin,- FunnelPersonsStepMixin,- FunnelTrendsPersonsMixin,- FunnelTypeMixin,- FunnelWindowDaysMixin,- FunnelWindowMixin,- HistogramMixin,-)-from .mixins.groups import GroupsAggregationMixin-from .mixins.interval import IntervalMixin-from .mixins.property import PropertyMixin-from .mixins.simplify import SimplifyFilterMixin---class Filter(- PropertyMixin,- IntervalMixin,- SmoothingIntervalsMixin,- EntitiesMixin,- EntityIdMixin,- EntityTypeMixin,- EntityMathMixin,- EntityOrderMixin,- DisplayDerivedMixin,- SelectorMixin,- ShownAsMixin,- BreakdownMixin,- CompareMixin,- BreakdownValueMixin,- FilterTestAccountsMixin,- InsightMixin,- OffsetMixin,- LimitMixin,- DateMixin,- # FormulaMixin,- FunnelWindowDaysMixin,- FunnelWindowMixin,- FunnelFromToStepsMixin,- FunnelPersonsStepMixin,- FunnelTrendsPersonsMixin,- FunnelPersonsStepBreakdownMixin,- FunnelLayoutMixin,- FunnelHogQLAggregationMixin,- FunnelTypeMixin,- HistogramMixin,- GroupsAggregationMixin,- FunnelCorrelationMixin,- FunnelCorrelationActorsMixin,- SimplifyFilterMixin,- IncludeRecordingsMixin,- SearchMixin,- DistinctIdMixin,- EmailMixin,- UpdatedAfterMixin,- ClientQueryIdMixin,- SampleMixin,- BaseFilter,-):- """- Filters allow us to describe what events to show/use in various places in the system, for example Trends or Funnels.- This object isn't a table in the database. It gets stored against the specific models itself as JSON.- This class just allows for stronger typing of this object.- """-- passdiff --git a/posthog/models/filters/lifecycle_filter.py b/posthog/models/filters/lifecycle_filter.pydeleted file mode 100644index dce9dd781be5..000000000000--- a/posthog/models/filters/lifecycle_filter.py+++ /dev/null@@ -1,36 +0,0 @@-import datetime-from typing import Any, Optional--from rest_framework.exceptions import ValidationError-from rest_framework.request import Request--from posthog.models import Filter-from posthog.utils import relative_date_parse---class LifecycleFilter(Filter):- target_date: Optional[datetime.datetime] = None- lifecycle_type: Optional[str] = None-- def __init__(- self,- data: Optional[dict[str, Any]] = None,- request: Optional[Request] = None,- **kwargs,- ) -> None:- super().__init__(data, request, **kwargs)-- if not data and not request:- raise ValidationError("Must include lifecycle type and target date")-- if data:- target_date = data.get("target_date", None)- if target_date:- assert self.team is not None- self.target_date = relative_date_parse(target_date, self.team.timezone_info)- if self.target_date is None:- raise ValidationError("Must include specified target date")-- self.lifecycle_type = data.get("lifecycle_type", None)- if self.lifecycle_type is None:- raise ValidationError("Must include lifecycle type")diff --git a/posthog/models/filters/mixins/property.py b/posthog/models/filters/mixins/property.pyindex e22c846fbee0..74ca8036861b 100644--- a/posthog/models/filters/mixins/property.py+++ b/posthog/models/filters/mixins/property.py@@ -1,14 +1,12 @@import json-from typing import Any, Optional, Union, cast-import posthoganalyticsfrom rest_framework.exceptions import ValidationError-from posthog.constants import PROPERTIES, PropertyOperatorType-from posthog.exceptions_capture import capture_exception+from posthog.constants import PROPERTIESfrom posthog.models.filters.mixins.base import BaseParamMixinfrom posthog.models.filters.mixins.utils import cached_property, include_dict, include_query_tags-from posthog.models.property import Property, PropertyGroup, PropertyValidationError+from posthog.models.property import Property, PropertyGroup+from posthog.models.property.parse import parse_properties, parse_property_group_dataclass PropertyMixin(BaseParamMixin):@@ -17,30 +15,7 @@ class PropertyMixin(BaseParamMixin):return self._parse_data(key=PROPERTIES)def _parse_data(self, key: str) -> PropertyGroup:- _props = self._data.get(key)-- if isinstance(_props, str):- try:- loaded_props = json.loads(_props)- except json.decoder.JSONDecodeError:- raise ValidationError("Data is unparsable!")- else:- loaded_props = _props-- # if grouped properties- if isinstance(loaded_props, dict) and "type" in loaded_props and "values" in loaded_props:- try:- return self._parse_property_group(loaded_props)- except ValidationError:- raise- except ValueError as e:- raise ValidationError(f"PropertyGroup is unparsable: {e}")- # already a PropertyGroup just return- elif isinstance(loaded_props, PropertyGroup):- return loaded_props-- # old properties- return PropertyGroup(type=PropertyOperatorType.AND, values=self.old_properties(key=key))+ return parse_property_group_data(self._data.get(key))def old_properties(self, key: str) -> list[Property]:_props = self._data.get(key)@@ -62,92 +37,7 @@ class PropertyMixin(BaseParamMixin):return []else:# old style dict properties or a list of properties- return self._parse_properties(loaded_props)-- def _parse_properties(self, properties: Optional[Any]) -> list[Property]:- if isinstance(properties, list):- _properties = []- for prop_params in properties:- if isinstance(prop_params, Property):- _properties.append(prop_params)- else:- try:- new_prop = Property(**prop_params)- _properties.append(new_prop)- except (PropertyValidationError, ValidationError, TypeError) as e:- # PropertyValidationError covers every failure Property.__init__ itself- # raises; ValidationError covers validate_group_type_index's own DRF- # error, which Property.__init__ leaves unwrapped so it still reaches- # direct callers as a 400; TypeError covers `Property(**prop_params)`- # failing to unpack prop_params as a mapping before __init__ even runs.- # Dropping an unparsable property changes validation behavior for every- # caller (e.g. cohort.properties.flat missing a behavioral leaf lets- # behavioral-cohort checks pass silently), so this must stay visible- # instead of failing silent. Report structure only — never the- # property's own value/event_filters — since those can carry real user- # data (e.g. an exact-match email filter). Code-variable capture would- # otherwise attach those same values from this frame's locals regardless- # of what we pass as additional_properties, so it's disabled for this call.- prop_dict = prop_params if isinstance(prop_params, dict) else {}- with posthoganalytics.new_context():- posthoganalytics.set_capture_exception_code_variables_context(False)- capture_exception(- e,- additional_properties={- "property_type": prop_dict.get("type"),- "property_fields": sorted(prop_dict.keys()) or None,- },- )- continue- return _properties- if not properties:- return []-- # old style dict properties- ret = []- for key, value in properties.items():- key_split = key.split("__")- ret.append(- Property(- key=key_split[0],- value=value,- operator=key_split[1] if len(key_split) > 1 else None,- type="event",- )- )- return ret-- def _parse_property_group(self, group: Optional[dict]) -> PropertyGroup:- if group and "type" in group and "values" in group:- return PropertyGroup(- PropertyOperatorType(group["type"].upper()),- self._parse_property_group_list(group["values"]),- )-- return PropertyGroup(PropertyOperatorType.AND, cast(list[Property], []))-- def _parse_property_group_list(self, prop_list: Optional[list]) -> Union[list[Property], list[PropertyGroup]]:- if not prop_list:- # empty prop list- return cast(list[Property], [])- has_property_groups = False- has_simple_properties = False-- for prop in prop_list:- if "type" in prop and "values" in prop:- has_property_groups = True- elif "key" in prop:- has_simple_properties = True- else:- has_property_groups = True-- if has_simple_properties and has_property_groups:- raise ValidationError("Property list cannot contain both PropertyGroup and Property objects")-- if has_property_groups:- return [self._parse_property_group(group) for group in prop_list]- else:- return self._parse_properties(prop_list)+ return parse_properties(loaded_props)@include_dictdef properties_to_dict(self):diff --git a/posthog/models/filters/mixins/simplify.py b/posthog/models/filters/mixins/simplify.pyindex 6f40ed6487d2..68bf81747d6e 100644--- a/posthog/models/filters/mixins/simplify.py+++ b/posthog/models/filters/mixins/simplify.py@@ -2,7 +2,6 @@ from typing import TYPE_CHECKING, Any, Literal, castfrom posthog.constants import PropertyOperatorTypefrom posthog.models.property import GroupTypeIndex, PropertyGroup-from posthog.schema_enums import PropertyOperatorif TYPE_CHECKING: # Avoid circular importfrom posthog.models import Property, Team@@ -89,35 +88,14 @@ class SimplifyFilterMixin:return PropertyGroup(type=PropertyOperatorType.AND, values=simplified_properties_values)def _simplify_property_group(self, team: "Team", prop_group: "PropertyGroup", **kwargs) -> "PropertyGroup":- from posthog.models.property import Property, PropertyGroup+ from posthog.models.property.parse import expand_cohort_group- new_groups = []- for group in prop_group.values:- if isinstance(group, PropertyGroup):- new_groups.append(self._simplify_property_group(team, group))- elif isinstance(group, Property):- new_groups.append(self._simplify_property(team, group))-- prop_group.values = new_groups- return prop_group+ return expand_cohort_group(prop_group, team)def _simplify_property(self, team: "Team", property: "Property", **kwargs) -> "PropertyGroup":- if property.type == "cohort":- from products.cohorts.backend.models.cohort import Cohort- from products.cohorts.backend.models.util import simplified_cohort_filter_properties-- try:- cohort = Cohort.objects.get(pk=cast(str | int, property.value), team__project_id=team.project_id)- except Cohort.DoesNotExist:- # :TODO: Handle non-existing resource in-query instead- return PropertyGroup(type=PropertyOperatorType.AND, values=[property])-- return simplified_cohort_filter_properties(- cohort, team, property.negation or property.operator == PropertyOperator.NOT_IN.value- )+ from posthog.models.property.parse import expand_cohort_property- # PropertyOperatorType doesn't really matter here, since only one value.- return PropertyGroup(type=PropertyOperatorType.AND, values=[property])+ return expand_cohort_property(property, team)def _group_set_property(self, group_type_index: GroupTypeIndex) -> "Property":from posthog.models.property import Propertydiff --git a/posthog/models/filters/mixins/test/test_interval.py b/posthog/models/filters/mixins/test/test_interval.pyindex d47adfc6b3e8..10405ba76528 100644--- a/posthog/models/filters/mixins/test/test_interval.py+++ b/posthog/models/filters/mixins/test/test_interval.py@@ -1,21 +1,21 @@import pytest-from posthog.models import Filter+from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter@pytest.mark.parametrize("filter,expected_interval",[- (Filter(data={"interval": "hour"}), "hour"),- (Filter(data={"interval": "day"}), "day"),- (Filter(data={"interval": "week"}), "week"),- (Filter(data={"interval": "month"}), "month"),+ (PropertiesTimelineFilter(data={"interval": "hour"}), "hour"),+ (PropertiesTimelineFilter(data={"interval": "day"}), "day"),+ (PropertiesTimelineFilter(data={"interval": "week"}), "week"),+ (PropertiesTimelineFilter(data={"interval": "month"}), "month"),# Downcasing- (Filter(data={"interval": "HoUR"}), "hour"),+ (PropertiesTimelineFilter(data={"interval": "HoUR"}), "hour"),# Blank filter- (Filter(data={"events": []}), "day"),+ (PropertiesTimelineFilter(data={"events": []}), "day"),# Legacy support - translate minutes to hours!- (Filter(data={"interval": "minute"}), "hour"),+ (PropertiesTimelineFilter(data={"interval": "minute"}), "hour"),],)def test_filter_interval_success(filter, expected_interval):@@ -27,10 +27,10 @@ def test_filter_interval_success(filter, expected_interval):"filter,expected_error_message",[(- Filter(data={"interval": "foo"}),+ PropertiesTimelineFilter(data={"interval": "foo"}),"Interval foo does not belong to SUPPORTED_INTERVAL_TYPES!",),- (Filter(data={"interval": 123}), "Interval must be a string!"),+ (PropertiesTimelineFilter(data={"interval": 123}), "Interval must be a string!"),],)def test_filter_interval_errors(filter, expected_error_message):diff --git a/posthog/models/filters/mixins/test/test_property.py b/posthog/models/filters/mixins/test/test_property.pyindex 20f7b9e46cb9..fbe9324532c4 100644--- a/posthog/models/filters/mixins/test/test_property.py+++ b/posthog/models/filters/mixins/test/test_property.py@@ -6,12 +6,12 @@ from unittest.mock import patchfrom posthoganalytics.contexts import get_capture_exception_code_variables_contextfrom rest_framework.exceptions import ValidationError-from posthog.models import Filter+from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterfrom posthog.models.property import Property, PropertyGroup, PropertyValidationErrordef test_property_group_multi_level_parsing():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -47,7 +47,7 @@ def test_property_group_multi_level_parsing():def test_property_group_simple_parsing():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -69,14 +69,14 @@ def test_property_group_simple_parsing():def test_property_group_empty_parsing():- filter = Filter(data={"properties": {}})+ filter = PropertiesTimelineFilter(data={"properties": {}})assert filter.property_groups.type == "AND"assert filter.property_groups.values == []def test_property_group_invalid_parsing():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "XaND",@@ -93,7 +93,7 @@ def test_property_group_invalid_parsing():def test_property_group_includes_unhomogenous_groups():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -112,7 +112,7 @@ def test_property_group_includes_unhomogenous_groups():def test_property_multi_level_to_dict():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -149,7 +149,7 @@ def test_property_multi_level_to_dict():def test_property_group_simple_to_dict():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -171,7 +171,7 @@ def test_property_group_simple_to_dict():def test_property_group_simple_json_parsing():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": json.dumps({@@ -196,7 +196,7 @@ def test_property_group_simple_json_parsing():def test_property_group_multi_level_json_parsing():- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": json.dumps({@@ -273,7 +273,7 @@ def test_property_group_parsing_reports_and_skips_unparsable_property(# with no visibility at all. It must still be dropped (callers across the codebase# rely on best-effort parsing of legacy/malformed data), but the failure must now be# reported — regardless of which internal check inside Property.__init__ rejected it.- filter = Filter(+ filter = PropertiesTimelineFilter(data={"properties": {"type": "AND",@@ -282,7 +282,7 @@ def test_property_group_parsing_reports_and_skips_unparsable_property(})- with patch("posthog.models.filters.mixins.property.capture_exception") as mock_capture_exception:+ with patch("posthog.models.property.parse.capture_exception") as mock_capture_exception:properties = filter.property_groups.valuesassert len(properties) == 1@@ -303,9 +303,9 @@ def test_property_group_parsing_reports_non_mapping_property():# `Property(**prop_params)` unpacking with TypeError, before __init__ even runs. The# grouped-properties path can't reach this: a non-mapping element trips the "cannot# contain both PropertyGroup and Property objects" check first.- filter = Filter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})+ filter = PropertiesTimelineFilter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})- with patch("posthog.models.filters.mixins.property.capture_exception") as mock_capture_exception:+ with patch("posthog.models.property.parse.capture_exception") as mock_capture_exception:properties = filter.property_groups.valuesassert len(properties) == 1@@ -328,10 +328,10 @@ def test_property_group_parsing_disables_code_variable_capture_for_reported_excedef fake_capture_exception(error, additional_properties=None):observed_context_values.append(get_capture_exception_code_variables_context())- filter = Filter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})+ filter = PropertiesTimelineFilter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})with patch(- "posthog.models.filters.mixins.property.capture_exception", side_effect=fake_capture_exception+ "posthog.models.property.parse.capture_exception", side_effect=fake_capture_exception) as mock_capture_exception:_ = filter.property_groups.valuesdiff --git a/posthog/models/filters/test/test_filter.py b/posthog/models/filters/test/test_filter.pyindex 674ada9e03de..eba8ed3ac9fc 100644--- a/posthog/models/filters/test/test_filter.py+++ b/posthog/models/filters/test/test_filter.py@@ -3,52 +3,24 @@ from typing import castfrom posthog.test.base import BaseTestfrom posthog.constants import FILTER_TEST_ACCOUNTS-from posthog.models import Filterfrom posthog.models.property import Property+from posthog.models.property.parse import expand_cohort_properties, parse_properties_for_team, parse_property_group_data++from products.cohorts.backend.models.cohort import Cohortclass TestFilter(BaseTest):def test_old_style_properties(self):- filter = Filter(data={"properties": {"$browser__is_not": "IE7", "$OS": "Mac"}})- self.assertEqual(cast(Property, filter.property_groups.values[0]).key, "$browser")- self.assertEqual(cast(Property, filter.property_groups.values[0]).operator, "is_not")- self.assertEqual(cast(Property, filter.property_groups.values[0]).value, "IE7")- self.assertEqual(cast(Property, filter.property_groups.values[0]).type, "event")- self.assertEqual(cast(Property, filter.property_groups.values[1]).key, "$OS")- self.assertEqual(cast(Property, filter.property_groups.values[1]).operator, None)- self.assertEqual(cast(Property, filter.property_groups.values[1]).value, "Mac")+ property_groups = parse_property_group_data({"$browser__is_not": "IE7", "$OS": "Mac"})+ self.assertEqual(cast(Property, property_groups.values[0]).key, "$browser")+ self.assertEqual(cast(Property, property_groups.values[0]).operator, "is_not")+ self.assertEqual(cast(Property, property_groups.values[0]).value, "IE7")+ self.assertEqual(cast(Property, property_groups.values[0]).type, "event")+ self.assertEqual(cast(Property, property_groups.values[1]).key, "$OS")+ self.assertEqual(cast(Property, property_groups.values[1]).operator, None)+ self.assertEqual(cast(Property, property_groups.values[1]).value, "Mac")- def test_to_dict(self):- filter = Filter(- data={- "events": [{"id": "$pageview"}],- "display": "ActionsLineGraph",- "compare": True,- "interval": "",- "actions": [],- "date_from": "2020-01-01T20:00:00Z",- "search": "query",- "client_query_id": "123",- }- )- self.assertCountEqual(- list(filter.to_dict().keys()),- [- "events",- "display",- "compare",- "insight",- "date_from",- "interval",- "smoothing_intervals",- "breakdown_attribution_type",- "sampling_factor",- "search",- "breakdown_normalize_url",- ],- )-- def test_simplify_test_accounts(self):+ def test_test_accounts_are_folded_in(self):self.team.test_account_filters = [{"key": "email",@@ -61,70 +33,91 @@ class TestFilter(BaseTest):data = {"properties": [{"key": "attr", "value": "some_val"}]}- filter = Filter(data=data, team=self.team)-self.assertEqual(- filter.properties_to_dict(),+ parse_properties_for_team(data, self.team).to_dict(),{- "properties": {- "type": "AND",- "values": [{"key": "attr", "value": "some_val", "type": "event"}],- }+ "type": "AND",+ "values": [{"key": "attr", "value": "some_val", "type": "event"}],},)- self.assertTrue(filter.is_simplified)-- filter = Filter(data={**data, FILTER_TEST_ACCOUNTS: True}, team=self.team)self.assertEqual(- filter.properties_to_dict(),+ parse_properties_for_team({**data, FILTER_TEST_ACCOUNTS: True}, self.team).to_dict(),{- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ],- },- {- "type": "AND",- "values": [{"key": "attr", "value": "some_val", "type": "event"}],- },- ],- }+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "email",+ "value": "@posthog.com",+ "operator": "not_icontains",+ "type": "person",+ }+ ],+ },+ {+ "type": "AND",+ "values": [{"key": "attr", "value": "some_val", "type": "event"}],+ },+ ],},)- self.assertTrue(filter.is_simplified)- self.assertEqual(- filter.simplify(self.team).properties_to_dict(),- {- "properties": {+ def test_nested_groups_keep_their_shape(self):+ # A single-property group nested under a parent with several values keeps its level;+ # only a group that is its parent's sole value collapses.+ properties = {+ "type": "OR",+ "values": [+ {+ "type": "OR",+ "values": [+ {"type": "AND", "values": [{"type": "person", "key": "email", "value": ".com"}]},+ ],+ },+ {"type": "AND","values": [- {- "type": "AND",- "values": [- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ],- },- {- "type": "AND",- "values": [{"key": "attr", "value": "some_val", "type": "event"}],- },+ {"type": "person", "key": "email", "value": "arg2"},+ {"type": "person", "key": "email", "value": "arg3"},],- }+ },+ ],+ }++ self.assertEqual(+ expand_cohort_properties(parse_property_group_data(properties), self.team).to_dict(),+ {+ "type": "OR",+ "values": [+ {"type": "OR", "values": [{"type": "person", "key": "email", "value": ".com"}]},+ {+ "type": "AND",+ "values": [+ {"type": "AND", "values": [{"type": "person", "key": "email", "value": "arg2"}]},+ {"type": "AND", "values": [{"type": "person", "key": "email", "value": "arg3"}]},+ ],+ },+ ],},)++ def test_cohort_nested_in_a_group_is_expanded(self):+ cohort = Cohort.objects.create(+ team=self.team,+ groups=[{"properties": [{"key": "email", "operator": "icontains", "value": ".com", "type": "person"}]}],+ )++ properties = {+ "type": "AND",+ "values": [+ {"type": "OR", "values": [{"type": "cohort", "key": "id", "value": cohort.pk}]},+ ],+ }++ self.assertEqual(+ expand_cohort_properties(parse_property_group_data(properties), self.team).to_dict(),+ {"type": "AND", "values": [{"type": "person", "key": "email", "operator": "icontains", "value": ".com"}]},+ )diff --git a/posthog/models/filters/test/test_lifecycle_filter.py b/posthog/models/filters/test/test_lifecycle_filter.pydeleted file mode 100644index 6f9159623337..000000000000--- a/posthog/models/filters/test/test_lifecycle_filter.py+++ /dev/null@@ -1,76 +0,0 @@-from posthog.test.base import BaseTest--from posthog.models.filters.lifecycle_filter import LifecycleFilter-from posthog.utils import relative_date_parse---class TestLifecycleFilter(BaseTest):- def test_filter_properties(self):- target_date = "2023-05-15"- lifecycle_type = "new"- filter = LifecycleFilter(- data={- "breakdown_attribution_type": "first_touch",- "breakdown_normalize_url": "False",- "date_from": "-14d",- "display": "ActionsLineGraph",- "events": '[{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview", "custom_name": null, "math": "total", "math_property": null, "math_group_type_index": null, "properties": {}}]',- "insight": "LIFECYCLE",- "interval": "week",- "sampling_factor": "",- "shown_as": "Lifecycle",- "smoothing_intervals": "1",- "entity_id": "$pageview",- "entity_type": "events",- "entity_math": "total",- "target_date": target_date,- "entity_order": "0",- "lifecycle_type": lifecycle_type,- "cache_invalidation_key": "ZY7tZ2Ak",- "is_simplified": True,- },- team=self.team,- )-- self.assertEqual(- filter.to_dict(),- {- "breakdown_attribution_type": "first_touch",- "breakdown_normalize_url": False,- "date_from": "-14d",- "display": "ActionsLineGraph",- "events": [- {- "distinct_id_field": None,- "id": "$pageview",- "id_field": None,- "type": "events",- "order": 0,- "name": "$pageview",- "custom_name": None,- "math": "total",- "math_property": None,- "math_property_revenue_currency": None,- "math_hogql": None,- "math_group_type_index": None,- "properties": {},- "timestamp_field": None,- "table_name": None,- }- ],- "entity_id": "$pageview",- "entity_math": "total",- "entity_order": "0",- "entity_type": "events",- "insight": "LIFECYCLE",- "interval": "week",- "sampling_factor": "",- "shown_as": "Lifecycle",- "smoothing_intervals": 1,- },- )- self.assertEqual(filter.lifecycle_type, lifecycle_type)- self.assertEqual(- filter.target_date,- relative_date_parse(target_date, self.team.timezone_info),- )diff --git a/posthog/models/filters/utils.py b/posthog/models/filters/utils.pyindex 3da0db1cbaf9..1fb384f5ffe5 100644--- a/posthog/models/filters/utils.py+++ b/posthog/models/filters/utils.py@@ -1,16 +1,8 @@-from typing import Any, Literal, Optional, cast+from typing import Any, Literal, castfrom rest_framework.exceptions import ValidationError-from rest_framework.request import Request-from posthog.constants import (- GROUP_TYPES_LIMIT,- INSIGHT_FUNNELS,- INSIGHT_PATHS,- INSIGHT_RETENTION,- INSIGHT_STICKINESS,- INSIGHT_TRENDS,-)+from posthog.constants import GROUP_TYPES_LIMITGroupTypeIndex = Literal[0, 1, 2, 3, 4]@@ -23,41 +15,6 @@ def earliest_timestamp_func(team_id: int):return get_earliest_timestamp_unfiltered(Team.objects.get(pk=team_id))-def get_filter(team, data: Optional[dict] = None, request: Optional[Request] = None):- from .filter import Filter- from .path_filter import PathFilter- from .retention_filter import RetentionFilter- from .stickiness_filter import StickinessFilter-- if data is None:- data = {}- insight = data.get("insight")- if not insight and request:- insight = request.GET.get("insight") or request.data.get("insight")- if insight == INSIGHT_RETENTION:- return RetentionFilter(data={**data, "insight": INSIGHT_RETENTION}, request=request, team=team)- elif insight == INSIGHT_STICKINESS or (insight == INSIGHT_TRENDS and data.get("shown_as") == "Stickiness"):- return StickinessFilter(- data=data,- request=request,- team=team,- get_earliest_timestamp=earliest_timestamp_func,- )- elif insight == INSIGHT_PATHS:- return PathFilter(data={**data, "insight": INSIGHT_PATHS}, request=request, team=team)- elif insight == INSIGHT_FUNNELS:- return Filter(- data={- **data,- **(request.data if request else {}),- "insight": INSIGHT_FUNNELS,- },- request=request,- team=team,- )- return Filter(data=data, request=request, team=team)--def validate_group_type_index(param_name: str, value: Any, required=False) -> GroupTypeIndex | None:error = ValidationError(f"{param_name} is required to be at least 0 and less than {GROUP_TYPES_LIMIT}",diff --git a/posthog/models/property/parse.py b/posthog/models/property/parse.pynew file mode 100644index 000000000000..3290a691ee01--- /dev/null+++ b/posthog/models/property/parse.py@@ -0,0 +1,190 @@+import json+from typing import TYPE_CHECKING, Any, Optional, Union, cast++import posthoganalytics+from rest_framework.exceptions import ValidationError++from posthog.constants import FILTER_TEST_ACCOUNTS, PROPERTIES, PropertyOperatorType+from posthog.exceptions_capture import capture_exception+from posthog.schema_enums import PropertyOperator++from .property import Property, PropertyGroup, PropertyValidationError++if TYPE_CHECKING:+ from posthog.models.team import Team+++def parse_property_group_data(data: Any) -> PropertyGroup:+ """Parse a `properties` value into a PropertyGroup, in any shape the API has ever accepted."""+ if isinstance(data, str):+ # `?properties=` reaches here as an empty string once the request dict is passed straight+ # through. The filter layer that used to sit in front dropped a falsy query param before+ # parsing, so an empty value has to keep meaning "no properties" instead of failing.+ if not data.strip():+ return PropertyGroup(type=PropertyOperatorType.AND, values=[])+ try:+ loaded_props = json.loads(data)+ except json.decoder.JSONDecodeError:+ raise ValidationError("Data is unparsable!")+ else:+ loaded_props = data++ if isinstance(loaded_props, dict) and "type" in loaded_props and "values" in loaded_props:+ try:+ return parse_property_group(loaded_props)+ except ValidationError:+ raise+ except ValueError as e:+ raise ValidationError(f"PropertyGroup is unparsable: {e}")+ elif isinstance(loaded_props, PropertyGroup):+ return loaded_props++ return PropertyGroup(type=PropertyOperatorType.AND, values=parse_properties(loaded_props))+++def parse_properties(properties: Optional[Any]) -> list[Property]:+ if isinstance(properties, list):+ _properties = []+ for prop_params in properties:+ if isinstance(prop_params, Property):+ _properties.append(prop_params)+ else:+ try:+ new_prop = Property(**prop_params)+ _properties.append(new_prop)+ except (PropertyValidationError, ValidationError, TypeError) as e:+ # PropertyValidationError covers every failure Property.__init__ itself+ # raises; ValidationError covers validate_group_type_index's own DRF+ # error, which Property.__init__ leaves unwrapped so it still reaches+ # direct callers as a 400; TypeError covers `Property(**prop_params)`+ # failing to unpack prop_params as a mapping before __init__ even runs.+ # Dropping an unparsable property changes validation behavior for every+ # caller (e.g. cohort.properties.flat missing a behavioral leaf lets+ # behavioral-cohort checks pass silently), so this must stay visible+ # instead of failing silent. Report structure only — never the+ # property's own value/event_filters — since those can carry real user+ # data (e.g. an exact-match email filter). Code-variable capture would+ # otherwise attach those same values from this frame's locals regardless+ # of what we pass as additional_properties, so it's disabled for this call.+ prop_dict = prop_params if isinstance(prop_params, dict) else {}+ with posthoganalytics.new_context():+ posthoganalytics.set_capture_exception_code_variables_context(False)+ capture_exception(+ e,+ additional_properties={+ "property_type": prop_dict.get("type"),+ "property_fields": sorted(prop_dict.keys()) or None,+ },+ )+ continue+ return _properties+ if not properties:+ return []++ # old style dict properties+ ret = []+ for key, value in properties.items():+ key_split = key.split("__")+ ret.append(+ Property(+ key=key_split[0],+ value=value,+ operator=key_split[1] if len(key_split) > 1 else None,+ type="event",+ )+ )+ return ret+++def parse_property_group(group: Optional[dict]) -> PropertyGroup:+ if group and "type" in group and "values" in group:+ return PropertyGroup(+ PropertyOperatorType(group["type"].upper()),+ parse_property_group_list(group["values"]),+ )++ return PropertyGroup(PropertyOperatorType.AND, cast(list[Property], []))+++def parse_property_group_list(prop_list: Optional[list]) -> Union[list[Property], list[PropertyGroup]]:+ if not prop_list:+ # empty prop list+ return cast(list[Property], [])+ has_property_groups = False+ has_simple_properties = False++ for prop in prop_list:+ if "type" in prop and "values" in prop:+ has_property_groups = True+ elif "key" in prop:+ has_simple_properties = True+ else:+ has_property_groups = True++ if has_simple_properties and has_property_groups:+ raise ValidationError("Property list cannot contain both PropertyGroup and Property objects")++ if has_property_groups:+ return [parse_property_group(group) for group in prop_list]+ else:+ return parse_properties(prop_list)+++def expand_cohort_properties(prop_group: PropertyGroup, team: "Team") -> PropertyGroup:+ """Replace cohort properties with the concrete lookups they stand for.++ A cohort that is not static, precalculated, or behavioral expands into its own+ person properties, so it matches before its first calculation has run.+ """+ from .util import clear_excess_levels # noqa: PLC0415 — avoids a circular import++ return clear_excess_levels(expand_cohort_group(prop_group, team), skip=True)+++def expand_cohort_group(prop_group: PropertyGroup, team: "Team") -> PropertyGroup:+ new_values: list[Any] = []+ for value in prop_group.values:+ if isinstance(value, PropertyGroup):+ new_values.append(expand_cohort_group(value, team))+ elif isinstance(value, Property):+ new_values.append(expand_cohort_property(value, team))++ prop_group.values = new_values+ return prop_group+++def expand_cohort_property(property: Property, team: "Team") -> PropertyGroup:+ if property.type != "cohort":+ # PropertyOperatorType doesn't really matter here, since only one value.+ return PropertyGroup(type=PropertyOperatorType.AND, values=[property])++ from products.cohorts.backend.models.cohort import Cohort # noqa: PLC0415 — avoids a circular import+ from products.cohorts.backend.models.util import simplified_cohort_filter_properties # noqa: PLC0415++ try:+ cohort = Cohort.objects.get(pk=cast(str | int, property.value), team__project_id=team.project_id)+ except Cohort.DoesNotExist:+ # :TODO: Handle non-existing resource in-query instead+ return PropertyGroup(type=PropertyOperatorType.AND, values=[property])++ return simplified_cohort_filter_properties(+ cohort, team, property.negation or property.operator == PropertyOperator.NOT_IN.value+ )+++def parse_properties_for_team(data: dict, team: "Team") -> PropertyGroup:+ """Parse a filter dict's properties and resolve them against the team.++ Folds in the team's test-account filters when the dict asks for them, then expands+ cohorts, matching what a team-bound filter used to produce.+ """+ parsed = parse_property_group_data(data.get(PROPERTIES))++ if data.get(FILTER_TEST_ACCOUNTS) in (True, "true"):+ test_accounts = {"type": "AND", "values": team.test_account_filters}+ existing = parsed.to_dict()+ parsed = parse_property_group_data(+ {"type": "AND", "values": [test_accounts, existing]} if existing else test_accounts+ )++ return expand_cohort_properties(parsed, team)diff --git a/posthog/types.py b/posthog/types.pyindex a3ad38ad22cd..a93b272ead0c 100644--- a/posthog/types.py+++ b/posthog/types.py@@ -48,14 +48,6 @@ from posthog.schema import (WorkflowVariablePropertyFilter,)-from posthog.models.filters.filter import Filter-from posthog.models.filters.path_filter import PathFilter-from posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.stickiness_filter import StickinessFilter--type FilterType = Union[Filter, PathFilter, RetentionFilter, StickinessFilter]-"""Legacy insight filters."""-type InsightQueryNode = Union[TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, PathsV2Query, StickinessQuery, LifecycleQuery]diff --git a/products/actions/backend/models/util.py b/products/actions/backend/models/util.pyindex c7b261012943..f3cf2bc4b725 100644--- a/products/actions/backend/models/util.py+++ b/products/actions/backend/models/util.py@@ -3,8 +3,8 @@ from collections import (Counter as TCounter,)-from posthog.models import Filterfrom posthog.models.property import PropertyIdentifier+from posthog.models.property.parse import parse_property_group_datafrom products.actions.backend.models.action import Action@@ -18,7 +18,7 @@ def get_action_tables_and_properties(action: Action) -> TCounter[PropertyIdentifif action_step.url:result[("$current_url", "event", None)] += 1result += extract_tables_and_properties(- Filter(data={"properties": action_step.properties or []}).property_groups.flat,+ parse_property_group_data(action_step.properties or []).flat,team_id=action.team_id,)diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex f74340802e46..3d0784c163e5 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -26,10 +26,10 @@ from posthog.helpers.batch_iterators import ArrayBatchIterator, BatchIterator, Ffrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation-from posthog.models.filters.filter import Filterfrom posthog.models.person import Personfrom posthog.models.person.util import get_person_by_uuid, get_person_ids_and_uuids_by_uuidsfrom posthog.models.property import Property, PropertyGroup+from posthog.models.property.parse import parse_property_group_datafrom posthog.models.utils import RootTeamManager, RootTeamMixin, sane_reprfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.schema_enums import ProductKey@@ -632,7 +632,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):def properties(self) -> PropertyGroup:if self.filters:# Do not try simplifying properties at this stage. We'll let this happen at query time.- return Filter(data={**self.filters, "is_simplified": True}).property_groups+ return parse_property_group_data(self.filters.get("properties"))# convert deprecated groups to propertiesif self.groups:@@ -659,7 +659,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):group["properties"] = new_properties# Do not try simplifying properties at this stage. We'll let this happen at query time.- property_groups.append(Filter(data={**group, "is_simplified": True}).property_groups)+ property_groups.append(parse_property_group_data(group.get("properties")))elif group.get("action_id") or group.get("event_id"):key = group.get("action_id") or group.get("event_id")event_type: Literal["actions", "events"] = "actions" if group.get("action_id") else "events"diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex b67a96467f51..5ee5edd0fc7a 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -43,7 +43,7 @@ from posthog.exceptions import (ClickHouseQueryTimeOut,)from posthog.exceptions_capture import capture_exception-from posthog.models import Filter, Team+from posthog.models import Teamfrom posthog.models.person.sql import (DELETE_PERSON_FROM_STATIC_COHORT,INSERT_COHORT_ALL_PEOPLE_THROUGH_PERSON_ID,@@ -51,6 +51,7 @@ from posthog.models.person.sql import (PERSON_STATIC_COHORT_TABLE,)from posthog.models.property import Property, PropertyGroup+from posthog.models.property.parse import expand_cohort_properties, parse_property_group_datafrom posthog.schema_enums import ChartDisplayType, ProductKeyfrom posthog.schema_migrations.upgrade import upgrade@@ -912,7 +913,7 @@ def simplified_cohort_filter_properties(cohort: Cohort, team: Team, is_negated=F)# :TRICKY: We need to ensure we don't have infinite loops in here# guaranteed during cohort creation- return Filter(data={"properties": cohort.properties.to_dict()}, team=team).property_groups+ return expand_cohort_properties(parse_property_group_data(cohort.properties.to_dict()), team)# We have person properties only# TODO: Handle negating a complete property groupdiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex ad1c1356e38b..77b32b1544d3 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -40,7 +40,7 @@ from posthog.exceptions import (from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activityfrom posthog.models.activity_logging.model_activity import is_impersonated_sessionfrom posthog.models.activity_logging.utils import get_changed_fields_local-from posthog.models.filters.filter import Filter+from posthog.models.entity.entity import Entity, parse_entitiesfrom posthog.models.person.util import get_person_ids_and_uuids_by_uuidsfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Team@@ -4132,9 +4132,9 @@ class ExperimentService:raise ValidationError("Experiment already has an exposure cohort")exposure_filter_data = (experiment.parameters or {}).get("custom_exposure_filter")- exposure_filter = None+ exposure_entities: list[Entity] = []if exposure_filter_data:- exposure_filter = Filter(data={**exposure_filter_data, "is_simplified": True}, team=experiment.team)+ exposure_entities = parse_entities(exposure_filter_data)target_entity: int | str = "$feature_flag_called"target_entity_type = "events"@@ -4147,8 +4147,8 @@ class ExperimentService:}]- if exposure_filter:- entity = exposure_filter.entities[0]+ if exposure_entities:+ entity = exposure_entities[0]if entity.id:target_entity_type = entity.type if entity.type in ["events", "actions"] else "events"target_entity = entity.iddiff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.pyindex 25edd49946fa..ff2f82d6b555 100644--- a/products/exports/backend/api/test/test_exports.py+++ b/products/exports/backend/api/test/test_exports.py@@ -24,7 +24,6 @@ from posthog.hogql.errors import QueryErrorfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.filters.filter import Filterfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -131,11 +130,6 @@ class TestExports(APIBaseTest):else:mock_exporter_task.assert_not_called()- insight_filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-@classmethoddef setUpTestData(cls):super().setUpTestData()@@ -617,7 +611,7 @@ class TestExports(APIBaseTest):],)other_insight = Insight.objects.create(- filters=Filter(data=self.insight_filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=other_team,created_by=self.user,)diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex e92883905445..5735c137c662 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -22,7 +22,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ErrorResponseSerializer, actionfrom posthog.constants import AvailableFeaturefrom posthog.models import Team, User-from posthog.models.filters.filter import Filter+from posthog.models.property.parse import parse_property_group_datafrom posthog.rate_limit import CopyFlagsBurstRateThrottle, CopyFlagsSustainedRateThrottlefrom posthog.user_permissions import UserPermissionsfrom posthog.utils import safe_int@@ -1257,9 +1257,7 @@ class OrganizationFeatureFlagView(# create new cohort in the destination projectif not destination_cohort:- prop_group = Filter(- data={"properties": original_cohort.properties.to_dict(), "is_simplified": True}- ).property_groups+ prop_group = parse_property_group_data(original_cohort.properties.to_dict())for prop in prop_group.flat:if prop.type == "cohort" and not isinstance(prop.value, list):diff --git a/products/feature_flags/backend/blast_radius_flag_deps.py b/products/feature_flags/backend/blast_radius_flag_deps.pyindex 9deddab314d4..ec6120aac7b0 100644--- a/products/feature_flags/backend/blast_radius_flag_deps.py+++ b/products/feature_flags/backend/blast_radius_flag_deps.py@@ -13,7 +13,6 @@ from posthog.hogql.errors import (from posthog.hogql.property import property_to_exprfrom posthog.hogql.visitor import TraversingVisitor, clone_expr-from posthog.models.filters import Filterfrom posthog.models.property import Property, PropertyGroup, PropertyOperatorType, PropertyValidationErrorfrom posthog.models.team.team import Teamfrom posthog.utils import safe_int@@ -94,7 +93,7 @@ class FlagDependencyEstimator:counting every person."""- def __init__(self, team: Team, clean_condition: Callable[[Team, dict], Filter]):+ def __init__(self, team: Team, clean_condition: Callable[[Team, dict], PropertyGroup]):self.team = team# Injected rather than imported: user_blast_radius imports this module, and its cleaner# must normalize the dependency's stored filters the same way as the condition being sized.@@ -216,7 +215,7 @@ class FlagDependencyEstimator:if plain_properties:try:cleaned = self.clean_condition(self.team, {"properties": plain_properties})- targeting = property_to_expr(cleaned.property_groups, self.team, scope="person")+ targeting = property_to_expr(cleaned, self.team, scope="person")except _TARGETING_BUILD_ERRORS:return Nonefactors.append(self._indicator(targeting))diff --git a/products/feature_flags/backend/person_sampling.py b/products/feature_flags/backend/person_sampling.pyindex e9a22e2d54f7..f6e4f15cb113 100644--- a/products/feature_flags/backend/person_sampling.py+++ b/products/feature_flags/backend/person_sampling.py@@ -10,7 +10,7 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query-from posthog.models.filters import Filter+from posthog.models.property import PropertyGroupfrom posthog.models.team.team import Teamfrom posthog.schema_enums import PersonsArgMaxVersion@@ -97,7 +97,11 @@ def sampled_or_exact_count(run_count: Callable[[Optional[int]], int]) -> int:def count_matching_persons(- team: Team, filter: Optional[Filter], database: Database, query_type: str, weight: Optional[ast.Expr] = None+ team: Team,+ prop_group: Optional[PropertyGroup],+ database: Database,+ query_type: str,+ weight: Optional[ast.Expr] = None,) -> int:"""Count the persons a filter matches, or every person on the team when filter is None.@@ -106,19 +110,19 @@ def count_matching_persons(weights over the matched persons instead of their number."""return sampled_or_exact_estimate(- lambda sample_modulus: _run_person_count(team, filter, database, query_type, sample_modulus, weight)+ lambda sample_modulus: _run_person_count(team, prop_group, database, query_type, sample_modulus, weight))def _run_person_count(team: Team,- filter: Optional[Filter],+ prop_group: Optional[PropertyGroup],database: Database,query_type: str,sample_modulus: Optional[int],weight: Optional[ast.Expr] = None,) -> tuple[int, float]:- query = build_person_count_query(team, filter, sample_modulus=sample_modulus, weight=weight)+ query = build_person_count_query(team, prop_group, sample_modulus=sample_modulus, weight=weight)response = execute_hogql_query(query=query,team=team,@@ -130,7 +134,7 @@ def _run_person_count(# whatever this says, so the pin is only load-bearing if that path is ever lost. A# filtered count reads person properties, where v2 is the faster shape, so it keeps the# automatic choice.- modifiers=HogQLQueryModifiers(personsArgMaxVersion=PersonsArgMaxVersion.V1) if filter is None else None,+ modifiers=HogQLQueryModifiers(personsArgMaxVersion=PersonsArgMaxVersion.V1) if prop_group is None else None,context=HogQLContext(team_id=team.pk, database=database),settings=count_settings(sample_modulus),)@@ -146,7 +150,7 @@ def read_person_count(results: list, weighted: bool) -> tuple[int, float]:def build_person_count_query(- team: Team, filter: Optional[Filter], sample_modulus: Optional[int], weight: Optional[ast.Expr] = None+ team: Team, prop_group: Optional[PropertyGroup], sample_modulus: Optional[int], weight: Optional[ast.Expr] = None) -> ast.SelectQuery:"""Count the persons a filter matches. With `weight`, the query returns the number of matched@@ -161,15 +165,15 @@ def build_person_count_query(]if sample_modulus is not None:where_exprs.append(person_sample_predicate(sample_modulus))- if filter is not None:- where_exprs.append(property_to_expr(filter.property_groups, team, scope="person"))+ if prop_group is not None:+ where_exprs.append(property_to_expr(prop_group, team, scope="person"))if weight is None:# A filter can add a one-to-many join: a `distinct_id` person property resolves through# persons.pdi, which gives a person one row per distinct id. So a filtered count dedups on# the person id. The unfiltered total joins nothing, so it keeps the plain count() and# avoids a uniqExact state over every person on the team.- if filter is None:+ if prop_group is None:count_expr: ast.Expr = ast.Call(name="count", args=[])else:count_expr = ast.Call(name="count", distinct=True, args=[ast.Field(chain=["persons", "id"])])diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.pyindex d22167063647..fc1a85735aa1 100644--- a/products/feature_flags/backend/user_blast_radius.py+++ b/products/feature_flags/backend/user_blast_radius.py@@ -22,8 +22,8 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.errors import ExposedCHQueryError, InternalCHQueryError-from posthog.models.filters import Filterfrom posthog.models.property import GroupTypeIndex, Property, PropertyGroup, PropertyValidationError+from posthog.models.property.parse import parse_properties_for_teamfrom posthog.models.property.relative_date import relative_date_parse_for_feature_flag_matchingfrom posthog.models.team.team import Teamfrom posthog.ph_client import feature_enabled_or_false@@ -63,7 +63,7 @@ def use_blast_radius_query_v2(team: Team) -> bool:)-def sampled_person_blast_radius(team: Team, filter: Filter, query_type: str) -> BlastRadiusResult:+def sampled_person_blast_radius(team: Team, prop_group: PropertyGroup, query_type: str) -> BlastRadiusResult:"""Person blast radius whose peak query memory does not grow with the size of the person table.@@ -80,18 +80,18 @@ def sampled_person_blast_radius(team: Team, filter: Filter, query_type: str) ->database = Database.create_for(team=team)total = count_matching_persons(team, None, database, query_type=query_type)- if len(filter.property_groups.flat) == 0:+ if len(prop_group.flat) == 0:return BlastRadiusResult(affected=total, total=total)- weight = _flag_dependency_weight(team, filter)+ weight = _flag_dependency_weight(team, prop_group)try:- affected = count_matching_persons(team, filter, database, query_type=query_type, weight=weight)+ affected = count_matching_persons(team, prop_group, database, query_type=query_type, weight=weight)except InternalCHQueryError as e:if weight is None or e.code not in _VALUE_PARSE_CH_ERROR_CODES:raise# A dependency's stored targeting failed a cast in ClickHouse. Its configuration is not# the caller's input, so the dependency sizes neutrally instead of failing the request.- affected = count_matching_persons(team, filter, database, query_type=query_type)+ affected = count_matching_persons(team, prop_group, database, query_type=query_type)return BlastRadiusResult(affected=min(affected, total), total=total)@@ -151,13 +151,13 @@ def _normalize_property_value(prop: Property) -> None:prop.value = str(prop.value)-def replace_proxy_properties(team: Team, feature_flag_condition: dict):+def replace_proxy_properties(team: Team, feature_flag_condition: dict) -> PropertyGroup:# Parse phase: everything here derives directly from the caller's filter JSON, so a# ValueError is caller input (malformed property shape, non-numeric cohort id) and becomes# a 400. Cohort ids are cast eagerly so a bad id fails here instead of surfacing as a bare# ValueError from deep inside query building.try:- prop_groups = Filter(data=feature_flag_condition, team=team).property_groups+ prop_groups = parse_properties_for_team(feature_flag_condition, team)for prop in prop_groups.flat:if prop.type in ("cohort", "static-cohort", "precalculated-cohort"):@@ -169,7 +169,7 @@ def replace_proxy_properties(team: Team, feature_flag_condition: dict):else:_normalize_property_value(prop)- return Filter(data={"properties": prop_groups.to_dict()}, team=team)+ return prop_groupsexcept ValueError as e:raise ValidationError({"filters": str(e) or "These filters cannot be evaluated."}) from e@@ -220,10 +220,10 @@ def get_user_blast_radius_persons(return _get_person_blast_radius_persons(team, cleaned_filter, cursor=cursor)-def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:+def _get_person_blast_radius(team: Team, prop_group: PropertyGroup) -> BlastRadiusResult:"""Calculate blast radius for person-based feature flags using HogQL."""- properties = filter.property_groups.flat+ properties = prop_group.flatif len(properties) == 0:# No filters means all persons are affected@@ -235,15 +235,15 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:# Each execute_hogql_query call would otherwise build its own, and the build cost# scales with the team's warehouse size.database = Database.create_for(team=team)- weight = _flag_dependency_weight(team, filter)+ weight = _flag_dependency_weight(team, prop_group)try:- estimate = _run_exact_person_count(team, filter, database, weight)+ estimate = _run_exact_person_count(team, prop_group, database, weight)except InternalCHQueryError as e:if weight is None or e.code not in _VALUE_PARSE_CH_ERROR_CODES:raise# A dependency's stored targeting failed a cast in ClickHouse. Its configuration is not# the caller's input, so the dependency sizes neutrally instead of failing the request.- estimate = _run_exact_person_count(team, filter, database, weight=None)+ estimate = _run_exact_person_count(team, prop_group, database, weight=None)# A condition with a flag dependency sums per-person match probabilities, so the count is a float.total_count = int(round(estimate))total_users = team.count_persons_seen_so_far(database=database)@@ -252,9 +252,11 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:return BlastRadiusResult(affected=blast_radius, total=total_users)-def _run_exact_person_count(team: Team, filter: Filter, database: Database, weight: Optional[ast.Expr]) -> float:+def _run_exact_person_count(+ team: Team, prop_group: PropertyGroup, database: Database, weight: Optional[ast.Expr]+) -> float:# property_to_expr handles all properties including cohorts- select_query = build_person_count_query(team, filter, sample_modulus=None, weight=weight)+ select_query = build_person_count_query(team, prop_group, sample_modulus=None, weight=weight)response = execute_hogql_query(query=select_query,team=team,@@ -266,20 +268,20 @@ def _run_exact_person_count(team: Team, filter: Filter, database: Database, weigreturn read_person_count(response.results, weighted=weight is not None)[1]-def _flag_dependency_weight(team: Team, filter: Filter) -> Optional[ast.Expr]:+def _flag_dependency_weight(team: Team, prop_group: PropertyGroup) -> Optional[ast.Expr]:"""Per-person probability that the condition's flag dependencies evaluate to their requestedvalues, or None when the condition has none. property_to_expr neutralizes flag properties, sothe count paths weight each person by this instead. The persons listing stays unweighted andlists everyone the plain filters match."""- group = filter.property_groups+ group = prop_groupif not any(prop.type == "flag" for prop in group.flat):return Nonereturn FlagDependencyEstimator(team, clean_condition=replace_proxy_properties).weight_expr(group)-def _build_person_query(team: Team, filter: Filter, cursor: Optional[str] = None) -> ast.SelectQuery:+def _build_person_query(team: Team, prop_group: PropertyGroup, cursor: Optional[str] = None) -> ast.SelectQuery:"""Build HogQL AST query to select distinct persons matching filters, paginated by id."""select_query = ast.SelectQuery(@@ -299,7 +301,7 @@ def _build_person_query(team: Team, filter: Filter, cursor: Optional[str] = None]# Add all property filters (including cohorts) via property_to_expr- property_expr = property_to_expr(filter.property_groups, team, scope="person")+ property_expr = property_to_expr(prop_group, team, scope="person")where_exprs.append(property_expr)# Add cursor-based pagination@@ -321,10 +323,12 @@ def _build_person_query(team: Team, filter: Filter, cursor: Optional[str] = Nonereturn select_query-def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupTypeIndex) -> BlastRadiusResult:+def _get_group_blast_radius(+ team: Team, prop_group: PropertyGroup, group_type_index: GroupTypeIndex+) -> BlastRadiusResult:"""Calculate blast radius for group-based feature flags using HogQL."""- properties = filter.property_groups.flat+ properties = prop_group.flat# Validate all group properties have correct group_type_indexfor property in properties:@@ -344,7 +348,7 @@ def _get_group_blast_radius(team: Team, filter: Filter, group_type_index: GroupTreturn BlastRadiusResult(affected=total_groups, total=total_groups)# Build the SELECT query for groups- select_query = _build_group_query(team, filter, group_type_index, return_count=True)+ select_query = _build_group_query(team, prop_group, group_type_index, return_count=True)# Execute the query with OFFLINE workload (groups queries can be massive)tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)@@ -368,7 +372,7 @@ PERSON_BATCH_SIZE = 500def _build_group_query(team: Team,- filter: Filter,+ prop_group: PropertyGroup,group_type_index: GroupTypeIndex,return_count: bool = True,cursor: Optional[str] = None,@@ -407,7 +411,7 @@ def _build_group_query(group_key_properties = []regular_properties = []- for prop in filter.property_groups.flat:+ for prop in prop_group.flat:if prop.key == "$group_key":group_key_properties.append(prop)else:@@ -572,11 +576,9 @@ def _build_group_query(# Add regular property filters using property_to_expr (only if there are any)if regular_properties:- regular_filter = Filter(- data={"properties": PropertyGroup(type=filter.property_groups.type, values=regular_properties).to_dict()},- team=team,+ property_expr = property_to_expr(+ PropertyGroup(type=prop_group.type, values=regular_properties), team, scope="group")- property_expr = property_to_expr(regular_filter.property_groups, team, scope="group")where_exprs.append(property_expr)# Add cursor-based pagination when returning keys@@ -600,11 +602,11 @@ def _build_group_query(return select_query-def _get_person_blast_radius_persons(team: Team, filter: Filter, cursor: Optional[str] = None) -> list[str]:+def _get_person_blast_radius_persons(team: Team, prop_group: PropertyGroup, cursor: Optional[str] = None) -> list[str]:"""Get distinct person IDs matching person-based feature flag filters."""# Build the SELECT query to get person IDs- select_query = _build_person_query(team, filter, cursor=cursor)+ select_query = _build_person_query(team, prop_group, cursor=cursor)tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)response = execute_hogql_query(@@ -618,11 +620,11 @@ def _get_person_blast_radius_persons(team: Team, filter: Filter, cursor: Optionadef _get_group_blast_radius_persons(- team: Team, filter: Filter, group_type_index: GroupTypeIndex, cursor: Optional[str] = None+ team: Team, prop_group: PropertyGroup, group_type_index: GroupTypeIndex, cursor: Optional[str] = None) -> list[str]:"""Get distinct group keys matching group-based feature flag filters."""- properties = filter.property_groups.flat+ properties = prop_group.flat# Validate all group properties have correct group_type_indexfor property in properties:@@ -636,7 +638,7 @@ def _get_group_blast_radius_persons(raise ValidationError("Invalid group type index for feature flag condition.")# Build the SELECT query to get group keys- select_query = _build_group_query(team, filter, group_type_index, return_count=False, cursor=cursor)+ select_query = _build_group_query(team, prop_group, group_type_index, return_count=False, cursor=cursor)tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)response = execute_hogql_query(diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.pyindex 2d5a4e3006cb..56cad49553ff 100644--- a/products/product_analytics/backend/models/insight.py+++ b/products/product_analytics/backend/models/insight.py@@ -1,3 +1,4 @@+import jsonfrom typing import TYPE_CHECKING, Any, Optionalfrom django.contrib.postgres.fields import ArrayField@@ -478,16 +479,16 @@ class InsightViewed(models.Model):@timed("generate_insight_cache_key")def generate_insight_filters_hash(insight: Insight, dashboard: Optional["Dashboard"]) -> str:- # Deferred: the legacy filters layer imports the HogQL/schema universe, and this model- # loads at django.setup() in every process.- from posthog.models.filters.utils import get_filter # noqa: PLC0415-+ # `dashboard_filters()` adds `date_from` and `date_to` whenever a dashboard is applied, so+ # dropping None values keeps a dashboard with no date range hashing as the bare insight.try:- dashboard_insight_filter = get_filter(data=insight.dashboard_filters(dashboard=dashboard), team=insight.team)- candidate_filters_hash = generate_cache_key(- insight.team.pk, "{}_{}".format(dashboard_insight_filter.toJSON(), insight.team_id)+ filters = insight.dashboard_filters(dashboard=dashboard)+ stringified = json.dumps(+ {key: value for key, value in filters.items() if value is not None},+ sort_keys=True,+ default=str,)- return candidate_filters_hash+ return generate_cache_key(insight.team.pk, f"{stringified}_{insight.team_id}")except Exception as e:logger.error("insight.generate_insight_cache_key.failed",diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.pyindex bddb4e61f970..2cd195f05092 100644--- a/products/product_analytics/backend/tests/api/test_insight.py+++ b/products/product_analytics/backend/tests/api/test_insight.py@@ -58,14 +58,14 @@ from posthog.constants import AvailableFeaturefrom posthog.errors import wrap_clickhouse_query_errorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionMode-from posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, User+from posthog.models import OrganizationMembership, SharingConfiguration, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.project import Projectfrom posthog.query_scan.findings import build_warningfrom posthog.query_scan.flag import QueryScanFlag, QueryScanModefrom posthog.query_scan.test.slots import stored_slotfrom posthog.test.db_context_capturing import capture_db_queries-from posthog.test.insight_queries import default_pageview_query, insight_query+from posthog.test.insight_queries import browser_filtered_pageview_query, default_pageview_query, insight_queryfrom products.access_control.backend.models.access_control import AccessControlfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold@@ -184,47 +184,37 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(fetched.json()["query"], query)def test_get_insight_items(self) -> None:- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)# create without user- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team)+ Insight.objects.create(query=browser_filtered_pageview_query(), team=self.team)response = self.client.get(f"/api/projects/{self.team.id}/insights/", data={"user": "true"}).json()self.assertEqual(len(response["results"]), 1)def test_get_insight_items_all_environments_included(self) -> None:- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-other_team_in_project = Team.objects.create(organization=self.organization, project=self.project)_, team_in_other_project = Project.objects.create_with_team(organization=self.organization, initiating_user=self.user)insight_a = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)insight_b = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=other_team_in_project,created_by=self.user,)Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=team_in_other_project,created_by=self.user,)@@ -415,13 +405,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)def test_get_saved_insight_items(self) -> None:- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),saved=True,team=self.team,created_by=self.user,@@ -429,13 +414,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# create without savedInsight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)# create without user- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team)+ Insight.objects.create(query=browser_filtered_pageview_query(), team=self.team)response = self.client.get(f"/api/projects/{self.team.id}/insights/",@@ -458,13 +443,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertTrue(insight.saved, f"Insight '{insight.name}' should have saved=True")def test_get_favorited_insight_items(self) -> None:- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }-Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),favorited=True,team=self.team,created_by=self.user,@@ -472,13 +452,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# create without favoritedInsight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),team=self.team,created_by=self.user,)# create without user- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team)+ Insight.objects.create(query=browser_filtered_pageview_query(), team=self.team)response = self.client.get(f"/api/projects/{self.team.id}/insights/?favorited=true&user=true")self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -495,10 +475,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):FEATURE_FLAG_UNIQUE_USERS_INSIGHT_NAME,)- filter_dict = {- "events": [{"id": "$pageview"}],- "properties": [{"key": "$browser", "value": "Mac OS X"}],- }generated = [(FEATURE_FLAG_TOTAL_VOLUME_INSIGHT_NAME,@@ -527,7 +503,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):Insight.objects.create(name=name,description=description,- filters=Filter(data=filter_dict).to_dict(),+ query=browser_filtered_pageview_query(),saved=True,team=self.team,created_by=self.user,@@ -755,7 +731,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)def test_retrieve_insight_by_id_or_short_id(self, _name, lookup) -> None:insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="abcd1234",name="dual-lookup",@@ -764,7 +740,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Another insight in a different team sharing the same short_id — must not be returned.other_team = Team.objects.create(organization=self.organization)Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=other_team,short_id="abcd1234",name="other-team",@@ -786,7 +762,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):numeric_short_id = "99999999999"assert not Insight.objects.filter(pk=int(numeric_short_id)).exists()insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id=numeric_short_id,name="numeric-short-id",@@ -803,14 +779,12 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):The `skip_results` query parameter can be passed so that only a list of objects is returned, withoutthe actual query data. This can speed things up if it's not needed."""- filter_dict = {"events": [{"id": "$pageview"}]}-Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, saved=True)+ Insight.objects.create(query=default_pageview_query(), team=self.team, saved=True)response = self.client.get(f"/api/projects/{self.team.id}/insights/?basic=true")self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -2327,7 +2301,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_logged_out_user_cannot_retrieve_insight(self) -> None:self.client.logout()insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)@@ -2358,13 +2332,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):flush_persons_and_events()insight = Insight.objects.create(name="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)Insight.objects.create( # This one isn't sharedname="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="abcdfghi",)@@ -2437,7 +2411,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.client.logout()deleted_insight = Insight.objects.create(name="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",deleted=True,@@ -2460,7 +2434,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.client.logout()insight = Insight.objects.create(name="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)@@ -2485,7 +2459,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_logged_out_user_cannot_retrieve_insight_with_disabled_insight_sharing_access_token(self) -> None:self.client.logout()insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)@@ -2530,20 +2504,20 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):flush_persons_and_events()insight = Insight.objects.create(name="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)deleted_insight = Insight.objects.create(name="Barfoo",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="87654321",deleted=True,)deleted_tile_insight = Insight.objects.create(name="Foobaz",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="abcdabcd",)@@ -2595,7 +2569,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.client.logout()insight = Insight.objects.create(name="Foobar",- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)@@ -2619,9 +2593,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@parameterized.expand([("single_id", 1), ("bulk_ids", 3)])@time_machine.travel("2022-03-22T00:00:00.000Z", tick=False)def test_create_insight_viewed(self, _name: str, count: int) -> None:- filter_dict = {"events": [{"id": "$pageview"}]}insights = [- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"viewed{i}")+ Insight.objects.create(query=default_pageview_query(), team=self.team, short_id=f"viewed{i}")for i in range(count)]@@ -2644,8 +2617,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)def test_insight_viewed_not_recorded_during_impersonation(self) -> None:- filter_dict = {"events": [{"id": "$pageview"}]}- insight = Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="viewed0")+ insight = Insight.objects.create(query=default_pageview_query(), team=self.team, short_id="viewed0")with patch("products.product_analytics.backend.presentation.insight.is_impersonated", return_value=True):response = self.client.post(@@ -2657,9 +2629,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(InsightViewed.objects.count(), 0)def test_update_insight_viewed(self) -> None:- filter_dict = {"events": [{"id": "$pageview"}]}insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=default_pageview_query(),team=self.team,short_id="12345678",)@@ -2686,9 +2657,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_cant_view_insight_viewed_for_insight_in_another_team(self) -> None:other_team = Team.objects.create(organization=self.organization, name="other team")- filter_dict = {"events": [{"id": "$pageview"}]}insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=default_pageview_query(),team=other_team,short_id="12345678",)@@ -2719,9 +2689,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(InsightViewed.objects.count(), 0)def test_bulk_upserts_existing_insight_viewed_rows(self) -> None:- filter_dict = {"events": [{"id": "$pageview"}]}insights = [- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"upsert{i}")+ Insight.objects.create(query=default_pageview_query(), team=self.team, short_id=f"upsert{i}")for i in range(3)]@@ -2746,15 +2715,10 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_bulk_filters_unauthorized_and_deleted_insight_ids(self) -> None:other_team = Team.objects.create(organization=self.organization, name="other team")- filter_dict = {"events": [{"id": "$pageview"}]}- own_insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="own1"- )- other_team_insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(), team=other_team, short_id="other"- )+ own_insight = Insight.objects.create(query=default_pageview_query(), team=self.team, short_id="own1")+ other_team_insight = Insight.objects.create(query=default_pageview_query(), team=other_team, short_id="other")deleted_insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="dead", deleted=True+ query=default_pageview_query(), team=self.team, short_id="dead", deleted=True)response = self.client.post(@@ -2767,13 +2731,11 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(InsightViewed.objects.first().insight_id, own_insight.id) # type: ignore[union-attr]def test_bulk_insight_viewed_query_count_does_not_grow_with_insight_count(self) -> None:- filter_dict = {"events": [{"id": "$pageview"}]}few = [- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"few{i}")- for i in range(2)+ Insight.objects.create(query=default_pageview_query(), team=self.team, short_id=f"few{i}") for i in range(2)]many = [- Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id=f"many{i}")+ Insight.objects.create(query=default_pageview_query(), team=self.team, short_id=f"many{i}")for i in range(10)]@@ -3008,17 +2970,17 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):filter_dict3 = {"events": [{"id": "$pageview"}], "breakdown": "email"}insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ filters=filter_dict,team=self.team,short_id="11223344",)insight2 = Insight.objects.create(- filters=Filter(data=filter_dict2).to_dict(),+ filters=filter_dict2,team=self.team,short_id="44332211",)Insight.objects.create(- filters=Filter(data=filter_dict3).to_dict(),+ filters=filter_dict3,team=self.team,short_id="00992281",)@@ -3228,7 +3190,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_soft_delete_cannot_be_reversed_for_another_team(self) -> None:other_team = Team.objects.create(organization=self.organization, name="other team")other_insight = Insight.objects.create(- filters=Filter(data={"events": [{"id": "$pageview"}]}).to_dict(),+ query=default_pageview_query(),team=other_team,short_id="abcabc",deleted=True,@@ -3922,12 +3884,10 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.organization.save()# Create insights with different access levels- filter_dict = {"events": [{"id": "$pageview"}]}-# Create an insight that will be blocked for regular usersblocked_insight_short_id = "block123"blocked_insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=default_pageview_query(),team=self.team,short_id=blocked_insight_short_id,name="Blocked Insight",@@ -3936,7 +3896,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Create an insight that will be accessibleaccessible_insight_short_id = "access_456"accessible_insight = Insight.objects.create(- filters=Filter(data=filter_dict).to_dict(),+ query=default_pageview_query(),team=self.team,short_id=accessible_insight_short_id,name="Accessible Insight",diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex c03f2f294810..3114a9599da5 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -84,8 +84,8 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_actionfrom posthog.models import Team, User-from posthog.models.filters import Filterfrom posthog.models.integration import Integration+from posthog.models.property.parse import expand_cohort_properties, parse_property_group_datafrom posthog.permissions import posthog_feature_flag_enabledfrom posthog.plugins.plugin_server_api import (cancel_hog_flow_batch_job,@@ -429,7 +429,8 @@ BATCH_FLAG_CONDITION_REJECTION = (def reject_flag_conditions_in_audience(team: Team, filters: dict) -> None:- property_groups = Filter(data=filters or {}, team=team).property_groups+ # Cohorts are expanded so a flag condition nested inside one is still caught.+ property_groups = expand_cohort_properties(parse_property_group_data((filters or {}).get("properties")), team)if any(prop.type == "flag" for prop in property_groups.flat):raise exceptions.ValidationError(BATCH_FLAG_CONDITION_REJECTION)diff --git a/products/workflows/backend/services/audience_v2.py b/products/workflows/backend/services/audience_v2.pyindex 1a23647b3f5f..3b6e2592133f 100644--- a/products/workflows/backend/services/audience_v2.py+++ b/products/workflows/backend/services/audience_v2.py@@ -9,7 +9,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.models.filters import Filter+from posthog.models.property import PropertyGroupfrom posthog.models.team.team import Teamfrom products.feature_flags.backend.person_sampling import (@@ -86,8 +86,8 @@ def get_dedupe_audience_count_v2(team: Team, filters: dict, dedupe_key: str) ->return BlastRadiusResult(affected=min(affected, total), total=total)-def _run_dedupe_count(team: Team, filter: Filter, database: Database, sample_modulus: Optional[int]) -> int:- query = build_dedupe_count_query(team, filter, sample_modulus=sample_modulus)+def _run_dedupe_count(team: Team, prop_group: PropertyGroup, database: Database, sample_modulus: Optional[int]) -> int:+ query = build_dedupe_count_query(team, prop_group, sample_modulus=sample_modulus)response = execute_hogql_query(query=query,team=team,@@ -99,7 +99,7 @@ def _run_dedupe_count(team: Team, filter: Filter, database: Database, sample_modreturn (response.results[0][0] if response.results else None) or 0-def build_dedupe_count_query(team: Team, filter: Filter, sample_modulus: Optional[int]) -> ast.SelectQuery:+def build_dedupe_count_query(team: Team, prop_group: PropertyGroup, sample_modulus: Optional[int]) -> ast.SelectQuery:where_exprs: list[ast.Expr] = [ast.CompareOperation(op=ast.CompareOperationOp.Eq,@@ -111,8 +111,8 @@ def build_dedupe_count_query(team: Team, filter: Filter, sample_modulus: Optiona# A fresh group expr per use: the resolver annotates AST nodes in place, so the# WHERE and SELECT must not share one instance.where_exprs.append(sample_predicate(email_dedupe_group_expr(), sample_modulus))- if len(filter.property_groups.flat) > 0:- where_exprs.append(property_to_expr(filter.property_groups, team, scope="person"))+ if len(prop_group.flat) > 0:+ where_exprs.append(property_to_expr(prop_group, team, scope="person"))return ast.SelectQuery(select=[ast.Call(name="count", distinct=True, args=[email_dedupe_group_expr()])],diff --git a/products/workflows/backend/services/batch_audience.py b/products/workflows/backend/services/batch_audience.pyindex 48012526907d..fc7e9e670496 100644--- a/products/workflows/backend/services/batch_audience.py+++ b/products/workflows/backend/services/batch_audience.py@@ -10,8 +10,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.models.filters import Filter-from posthog.models.property import GroupTypeIndex+from posthog.models.property import GroupTypeIndex, PropertyGroupfrom posthog.models.team.team import Teamfrom products.feature_flags.backend.user_blast_radius import (@@ -103,7 +102,7 @@ def get_batch_audience_count(left=ast.Field(chain=["persons", "team_id"]),right=ast.Constant(value=team.pk),),- property_to_expr(cleaned_filter.property_groups, team, scope="person"),+ property_to_expr(cleaned_filter, team, scope="person"),]# uniqCombined, not count(DISTINCT ...): the latter compiles to uniqExact, which holds@@ -141,7 +140,7 @@ def email_dedupe_group_expr() -> ast.Expr:def _build_audience_person_query(team: Team,- filter: Filter,+ prop_group: PropertyGroup,cursor: Optional[str] = None,dedupe_key: Optional[str] = None,) -> ast.SelectQuery:@@ -151,7 +150,7 @@ def _build_audience_person_query(left=ast.Field(chain=["persons", "team_id"]),right=ast.Constant(value=team.pk),),- property_to_expr(filter.property_groups, team, scope="person"),+ property_to_expr(prop_group, team, scope="person"),]if dedupe_key == EMAIL_DEDUPE_KEY: