: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
fix(flags): count blast radius via HogQL, drop legacy PersonQuery (#87287)
Sandy Spicer47dde8644ac5
diff --git a/ee/clickhouse/models/test/__snapshots__/test_property.ambr b/ee/clickhouse/models/test/__snapshots__/test_property.ambrindex 49f279860e40..d7ba09fdadf5 100644--- a/ee/clickhouse/models/test/__snapshots__/test_property.ambr+++ b/ee/clickhouse/models/test/__snapshots__/test_property.ambr@@ -58,7 +58,7 @@# ---# name: test_parse_groups_persons_edge_case_with_single_filtertuple(- 'AND ( has(%(vglobalperson_0)s, "pmat_email"))',+ 'AND ( has(%(vglobalperson_0)s, replaceRegexpAll(JSONExtractRaw(person_props, %(kglobalperson_0)s), \'^"|"$\', \'\')))',dict({'kglobalperson_0': 'email','vglobalperson_0': list([@@ -121,7 +121,7 @@# ---# name: test_parse_prop_clauses_defaults.2tuple(- 'AND ( has(%(vglobal_0)s, replaceRegexpAll(JSONExtractRaw(properties, %(kglobal_0)s), \'^"|"$\', \'\')) AND argMax(person."pmat_email", version) ILIKE %(vpersonquery_global_1)s)',+ 'AND ( has(%(vglobal_0)s, replaceRegexpAll(JSONExtractRaw(properties, %(kglobal_0)s), \'^"|"$\', \'\')) AND replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_global_1)s), \'^"|"$\', \'\') ILIKE %(vpersonquery_global_1)s)',dict({'kglobal_0': 'event_prop','kpersonquery_global_1': 'email',diff --git a/ee/clickhouse/models/test/test_property.py b/ee/clickhouse/models/test/test_property.pyindex 7403476987ec..3911c0f59923 100644--- a/ee/clickhouse/models/test/test_property.py+++ b/ee/clickhouse/models/test/test_property.py@@ -30,9 +30,6 @@ from posthog.models.property.util import (prop_filter_json_extract,)from posthog.models.team import Team-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query-from posthog.queries.person_query import PersonQuery-from posthog.queries.property_optimizer import PropertyOptimizerfrom posthog.queries.util import PersonPropertiesModefrom products.cohorts.backend.models.cohort import Cohort@@ -777,27 +774,16 @@ class TestPropFormat(ClickhouseTestMixin, BaseTest):class TestPropDenormalized(ClickhouseTestMixin, BaseTest):CLASS_DATA_LEVEL_SETUP = False- def _run_query(self, filter: Filter, join_person_tables=False) -> list:+ def _run_query(self, filter: Filter) -> list:filter.hogql_context.use_new_events_schema = False- outer_properties = PropertyOptimizer().parse_property_groups(filter.property_groups).outerquery, params = parse_prop_grouped_clauses(team_id=self.team.pk,- property_group=outer_properties,+ property_group=filter.property_groups,allow_denormalized_props=True,person_properties_mode=PersonPropertiesMode.USING_PERSON_PROPERTIES_COLUMN,hogql_context=filter.hogql_context,)- joins = ""- if join_person_tables:- person_query = PersonQuery(filter, self.team.pk)- person_subquery, person_join_params = person_query.get_query()- joins = f"""- INNER JOIN ({get_team_distinct_ids_query(self.team.pk)}) AS pdi ON events.distinct_id = pdi.distinct_id- INNER JOIN ({person_subquery}) person ON pdi.person_id = person.id- """- params.update(person_join_params)-- final_query = f"SELECT uuid FROM events {joins} WHERE team_id = %(team_id)s {query}"+ final_query = f"SELECT uuid FROM events WHERE team_id = %(team_id)s {query}"# Make sure we don't accidentally use json on the properties fieldself.assertNotIn("json", final_query.lower())return sync_execute(@@ -851,122 +837,6 @@ class TestPropDenormalized(ClickhouseTestMixin, BaseTest):)self.assertEqual(len(self._run_query(filter)), 1)- def test_prop_person_denormalized(self):- _create_person(- distinct_ids=["some_id"],- team_id=self.team.pk,- properties={"email": "[email protected]"},- )- _create_event(event="$pageview", team=self.team, distinct_id="some_id")-- materialize("person", "email")-- filter = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- }- ]- }- )- self.assertEqual(len(self._run_query(filter, join_person_tables=True)), 1)-- filter = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "not_icontains",- }- ]- }- )- self.assertEqual(len(self._run_query(filter, join_person_tables=True)), 0)-- def test_prop_person_groups_denormalized(self):- _filter = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- "operator": None,- },- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- "operator": None,- },- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- "operator": None,- },- {- "key": "person_prop",- "value": "efg",- "type": "person",- "operator": None,- },- ],- },- ],- }- }-- filter = Filter(data=_filter)-- _create_person(distinct_ids=["some_id_1"], team_id=self.team.pk, properties={})- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id_1",- properties={"event_prop2": "foo2"},- )-- _create_person(- distinct_ids=["some_id_2"],- team_id=self.team.pk,- properties={"person_prop2": "efg2"},- )- _create_event(event="$pageview", team=self.team, distinct_id="some_id_2")-- _create_person(- distinct_ids=["some_id_3"],- team_id=self.team.pk,- properties={"person_prop": "efg"},- )- _create_event(- event="$pageview",- team=self.team,- distinct_id="some_id_3",- properties={"event_prop": "foo"},- )-- materialize("events", "event_prop")- materialize("events", "event_prop2")- materialize("person", "person_prop")- materialize("person", "person_prop2")- self.assertEqual(len(self._run_query(filter, join_person_tables=True)), 3)-def test_prop_event_denormalized_ints(self):_create_event(event="$pageview",@@ -1075,16 +945,6 @@ def test_parse_prop_clauses_defaults(snapshot):)== snapshot)- assert (- parse_prop_grouped_clauses(- team_id=1,- property_group=filter.property_groups,- person_properties_mode=PersonPropertiesMode.DIRECT,- allow_denormalized_props=False,- hogql_context=filter.hogql_context,- )- == snapshot- )@pytest.mark.django_dbdiff --git a/ee/clickhouse/queries/column_optimizer.py b/ee/clickhouse/queries/column_optimizer.pydeleted file mode 100644index e150c030cd6e..000000000000--- a/ee/clickhouse/queries/column_optimizer.py+++ /dev/null@@ -1,115 +0,0 @@-from collections import Counter as TCounter-from typing import cast--from posthog.constants import TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType-from posthog.models.filters.mixins.utils import cached_property-from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter-from posthog.models.filters.stickiness_filter import StickinessFilter-from posthog.models.filters.utils import GroupTypeIndex-from posthog.models.property import PropertyIdentifier-from posthog.models.property.util import box_value, count_hogql_properties, extract_tables_and_properties-from posthog.queries.column_optimizer.foss_column_optimizer import FOSSColumnOptimizer-from posthog.queries.trends.util import is_series_group_based--from products.actions.backend.models.util import get_action_tables_and_properties---class EnterpriseColumnOptimizer(FOSSColumnOptimizer):- @cached_property- def group_types_to_query(self) -> set[GroupTypeIndex]:- used_properties = self.used_properties_with_type("group")- return {cast(GroupTypeIndex, group_type_index) for _, _, group_type_index in used_properties}-- @cached_property- def properties_used_in_filter(self) -> TCounter[PropertyIdentifier]:- "Returns collection of properties + types that this query would use"- counter: TCounter[PropertyIdentifier] = extract_tables_and_properties(- self.filter.property_groups.flat, team_id=self.team_id- )-- if not isinstance(self.filter, StickinessFilter):- # Some breakdown types read properties- if self.filter.breakdown_type in ["event", "person"]:- boxed_breakdown = box_value(self.filter.breakdown)- for b in boxed_breakdown:- if isinstance(b, str):- counter[- (- b,- self.filter.breakdown_type,- self.filter.breakdown_group_type_index,- )- ] += 1- elif self.filter.breakdown_type == "group":- # :TRICKY: We only support string breakdown for group properties- assert isinstance(self.filter.breakdown, str)- counter[- (- self.filter.breakdown,- self.filter.breakdown_type,- self.filter.breakdown_group_type_index,- )- ] += 1- elif self.filter.breakdown_type == "hogql":- if isinstance(self.filter.breakdown, list):- expr = str(self.filter.breakdown[0])- else:- expr = str(self.filter.breakdown)- counter = count_hogql_properties(expr, counter)-- # If we have a breakdowns attribute then make sure we pull in everything we- # need to calculate it- for breakdown in self.filter.breakdowns or []:- if breakdown["type"] == "hogql":- counter = count_hogql_properties(breakdown["property"], counter)- else:- counter[- (- breakdown["property"],- breakdown["type"],- self.filter.breakdown_group_type_index,- )- ] += 1-- # Both entities and funnel exclusions can contain nested property filters- for entity in self.entities_used_in_filter():- counter += extract_tables_and_properties(entity.property_groups.flat, team_id=self.team_id)-- # Math properties are also implicitly used.- #- # See posthog/queries/trends/util.py#process_math- if entity.math_property:- counter[(entity.math_property, "event", None)] += 1-- # Revenue currency properties are also implicitly used.- if entity.math_property_revenue_currency and entity.math_property_revenue_currency.property:- counter[(entity.math_property_revenue_currency.property, "event", None)] += 1-- # If groups are involved, they're also used- #- # See posthog/queries/trends/util.py#process_math- if is_series_group_based(entity):- counter[(f"$group_{entity.math_group_type_index}", "event", None)] += 1-- if entity.math == "unique_session":- counter[(f"$session_id", "event", None)] += 1-- # :TRICKY: If action contains property filters, these need to be included- #- # See ee/clickhouse/models/action.py#format_action_filter for an example- if entity.type == TREND_FILTER_TYPE_ACTIONS:- counter += get_action_tables_and_properties(entity.get_action(self.team_id))-- if (- not isinstance(self.filter, StickinessFilter | PropertiesTimelineFilter)- and self.filter.correlation_type == FunnelCorrelationType.PROPERTIES- and self.filter.correlation_property_names- ):- if self.filter.aggregation_group_type_index is not None:- for prop_value in self.filter.correlation_property_names:- counter[(prop_value, "group", self.filter.aggregation_group_type_index)] += 1- else:- for prop_value in self.filter.correlation_property_names:- counter[(prop_value, "person", None)] += 1-- return counterdiff --git a/ee/clickhouse/queries/test/__snapshots__/test_person_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_person_query.ambrdeleted file mode 100644index d281c880e5c8..000000000000--- a/ee/clickhouse/queries/test/__snapshots__/test_person_query.ambr+++ /dev/null@@ -1,369 +0,0 @@-# serializer version: 1-# name: test_person_query- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s---- GROUP BY id- HAVING max(is_deleted) = 0------ SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query.1- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_and_and_or_property_groups- '''-- SELECT id, argMax(properties, version) as person_props- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND (( "pmat_email" ILIKE %(vperson_filter_pre__0_0)s OR replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__0_1)s), '^"|"$', '') ILIKE %(vperson_filter_pre__0_1)s))-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND (( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0_0)s OR replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__0_1)s), '^"|"$', '') ILIKE %(vpersonquery_person_filter_fin__0_1)s))---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_anded_property_groups- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s AND has(%(vperson_filter_pre__1)s, replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__1)s), '^"|"$', '')) AND has(%(vperson_filter_pre__2)s, replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__2)s), '^"|"$', '')))-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s AND has(%(vpersonquery_person_filter_fin__1)s, replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__1)s), '^"|"$', '')) AND has(%(vpersonquery_person_filter_fin__2)s, replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__2)s), '^"|"$', '')))---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_entity_filters- '''-- SELECT id, argMax(pmat_email, version) as pmat_email- FROM person-- WHERE team_id = %(team_id)s---- GROUP BY id- HAVING max(is_deleted) = 0------ SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_entity_filters.1- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_entity_filters_and_property_group_filters- '''-- SELECT id, argMax(pmat_email, version) as pmat_email , argMax(properties, version) as person_props- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND (( "pmat_email" ILIKE %(vperson_filter_pre__0_0)s OR replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__0_1)s), '^"|"$', '') ILIKE %(vperson_filter_pre__0_1)s))-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND (( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0_0)s OR replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__0_1)s), '^"|"$', '') ILIKE %(vpersonquery_person_filter_fin__0_1)s))---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_entity_filters_and_property_group_filters.1- '''-- SELECT id, argMax(properties, version) as person_props- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ((( "pmat_email" ILIKE %(vperson_filter_pre__0_0_0)s OR replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__0_0_1)s), '^"|"$', '') ILIKE %(vperson_filter_pre__0_0_1)s))AND ( "pmat_email" ILIKE %(vperson_filter_pre__1_0)s OR replaceRegexpAll(JSONExtractRaw(properties, %(kperson_filter_pre__1_1)s), '^"|"$', '') ILIKE %(vperson_filter_pre__1_1)s))-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ((( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0_0_0)s OR replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__0_0_1)s), '^"|"$', '') ILIKE %(vpersonquery_person_filter_fin__0_0_1)s))AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__1_0)s OR replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), %(kpersonquery_person_filter_fin__1_1)s), '^"|"$', '') ILIKE %(vpersonquery_person_filter_fin__1_1)s))---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_extra_fields- '''-- SELECT id, argMax(pmat_email, version) as pmat_email , argMax(properties, version) as person_props- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_extra_requested_fields- '''-- SELECT id, argMax(properties, version) as person_props- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_extra_requested_fields.1- '''-- SELECT id, argMax(pmat_email, version) as pmat_email- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )---- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_multiple_cohorts- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s- AND id IN (- SELECT id FROM person-- WHERE team_id = %(team_id)s- AND ( "pmat_email" ILIKE %(vperson_filter_pre__0)s)-- )-- AND id in (- SELECT DISTINCT person_id FROM cohortpeople WHERE team_id = %(team_id)s AND cohort_id = %(_cohort_id_0)s AND version = %(_version_0)s- ) AND id in (- SELECT DISTINCT person_id FROM cohortpeople WHERE team_id = %(team_id)s AND cohort_id = %(_cohort_id_1)s AND version = %(_version_1)s- )-- GROUP BY id- HAVING max(is_deleted) = 0-- AND ( argMax(person."pmat_email", version) ILIKE %(vpersonquery_person_filter_fin__0)s)---- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_updated_after- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s---- GROUP BY id- HAVING max(is_deleted) = 0- and max(_timestamp) > parseDateTimeBestEffort(%(updated_after)s)----- SETTINGS optimize_aggregation_in_order = 1-- '''-# ----# name: test_person_query_with_updated_after.1- '''-- SELECT id- FROM person-- WHERE team_id = %(team_id)s---- GROUP BY id- HAVING max(is_deleted) = 0- and max(_timestamp) > parseDateTimeBestEffort(%(updated_after)s)----- SETTINGS optimize_aggregation_in_order = 1-- '''-# ---diff --git a/ee/clickhouse/queries/test/test_column_optimizer.py b/ee/clickhouse/queries/test/test_column_optimizer.pydeleted file mode 100644index 45009bb46bbb..000000000000--- a/ee/clickhouse/queries/test/test_column_optimizer.py+++ /dev/null@@ -1,271 +0,0 @@-from typing import Any--from posthog.test.base import APIBaseTest, ClickhouseTestMixin, cleanup_materialized_columns--from posthog.models.filters import Filter, RetentionFilter--from products.actions.backend.models.action import Action--from ee.clickhouse.materialized_columns.columns import materialize-from ee.clickhouse.queries.column_optimizer import EnterpriseColumnOptimizer--PROPERTIES_OF_ALL_TYPES = [- {"key": "event_prop", "value": ["foo", "bar"], "type": "event"},- {"key": "person_prop", "value": "efg", "type": "person"},- {"key": "id", "value": 1, "type": "cohort"},- {"key": "tag_name", "value": ["label"], "operator": "exact", "type": "element"},- {- "key": "group_prop",- "value": ["value"],- "operator": "exact",- "type": "group",- "group_type_index": 2,- },-]--BASE_FILTER = Filter({"events": [{"id": "$pageview", "type": "events", "order": 0}]})-FILTER_WITH_PROPERTIES = BASE_FILTER.shallow_clone({"properties": PROPERTIES_OF_ALL_TYPES})-FILTER_WITH_GROUPS = BASE_FILTER.shallow_clone({"properties": {"type": "AND", "values": PROPERTIES_OF_ALL_TYPES}})---class TestColumnOptimizer(ClickhouseTestMixin, APIBaseTest):- def setUp(self):- super().setUp()- self.team.test_account_filters = PROPERTIES_OF_ALL_TYPES- self.team.save()-- cleanup_materialized_columns()-- def _legacy_events_schema_filter(self, data: dict[str, Any]) -> Filter:- legacy_filter = Filter(data=data)- legacy_filter.hogql_context.use_new_events_schema = False- return legacy_filter-- def test_properties_used_in_filter(self):- properties_used_in_filter = lambda filter: (- EnterpriseColumnOptimizer(filter, self.team.id).properties_used_in_filter- )-- self.assertEqual(properties_used_in_filter(BASE_FILTER), {})- self.assertEqual(- properties_used_in_filter(FILTER_WITH_PROPERTIES),- {- ("event_prop", "event", None): 1,- ("person_prop", "person", None): 1,- ("id", "cohort", None): 1,- ("tag_name", "element", None): 1,- ("group_prop", "group", 2): 1,- },- )- self.assertEqual(- properties_used_in_filter(FILTER_WITH_GROUPS),- {- ("event_prop", "event", None): 1,- ("person_prop", "person", None): 1,- ("id", "cohort", None): 1,- ("tag_name", "element", None): 1,- ("group_prop", "group", 2): 1,- },- )-- # Breakdown cases- filter = BASE_FILTER.shallow_clone({"breakdown": "some_prop", "breakdown_type": "person"})- self.assertEqual(properties_used_in_filter(filter), {("some_prop", "person", None): 1})-- filter = BASE_FILTER.shallow_clone({"breakdown": "some_prop", "breakdown_type": "event"})- self.assertEqual(properties_used_in_filter(filter), {("some_prop", "event", None): 1})-- filter = BASE_FILTER.shallow_clone({"breakdown": [11], "breakdown_type": "cohort"})- self.assertEqual(properties_used_in_filter(filter), {})-- filter = BASE_FILTER.shallow_clone(- {- "breakdown": "some_prop",- "breakdown_type": "group",- "breakdown_group_type_index": 1,- }- )- self.assertEqual(properties_used_in_filter(filter), {("some_prop", "group", 1): 1})-- # Funnel Correlation cases- filter = BASE_FILTER.shallow_clone(- {- "funnel_correlation_type": "events",- "funnel_correlation_names": ["random_column"],- }- )- self.assertEqual(properties_used_in_filter(filter), {})-- filter = BASE_FILTER.shallow_clone(- {- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["random_column", "$browser"],- }- )- self.assertEqual(- properties_used_in_filter(filter),- {("random_column", "person", None): 1, ("$browser", "person", None): 1},- )-- filter = BASE_FILTER.shallow_clone(- {- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["random_column", "$browser"],- "aggregation_group_type_index": 2,- }- )- self.assertEqual(- properties_used_in_filter(filter),- {("random_column", "group", 2): 1, ("$browser", "group", 2): 1},- )-- filter = BASE_FILTER.shallow_clone({"funnel_correlation_type": "properties"})- self.assertEqual(properties_used_in_filter(filter), {})-- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "type": "events",- "order": 0,- "math": "sum",- "math_property": "numeric_prop",- "properties": PROPERTIES_OF_ALL_TYPES,- }- ]- }- )- self.assertEqual(- properties_used_in_filter(filter),- {- ("numeric_prop", "event", None): 1,- ("event_prop", "event", None): 1,- ("person_prop", "person", None): 1,- ("id", "cohort", None): 1,- ("tag_name", "element", None): 1,- ("group_prop", "group", 2): 1,- },- )-- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "type": "events",- "order": 0,- "math": "unique_group",- "math_group_type_index": 1,- }- ]- }- )- self.assertEqual(properties_used_in_filter(filter), {("$group_1", "event", None): 1})-- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "type": "events",- "order": 0,- "math": "unique_session",- }- ]- }- )- self.assertEqual(properties_used_in_filter(filter), {("$session_id", "event", None): 1})-- def test_properties_used_in_filter_with_actions(self):- action = Action.objects.create(- team=self.team,- steps_json=[- {- "event": "$autocapture",- "url": "https://example.com/donate",- "url_matching": "exact",- },- {- "event": "$autocapture",- "tag_name": "button",- "text": "Pay $10",- "properties": [{"key": "$browser", "value": "Chrome", "type": "person"}],- },- ],- )-- filter = Filter(data={"actions": [{"id": action.id, "math": "dau"}]})- self.assertEqual(- EnterpriseColumnOptimizer(filter, self.team.id).properties_used_in_filter,- {("$current_url", "event", None): 1, ("$browser", "person", None): 1},- )-- filter = BASE_FILTER.shallow_clone({"exclusions": [{"id": action.id, "type": "actions"}]})- self.assertEqual(- EnterpriseColumnOptimizer(filter, self.team.id).properties_used_in_filter,- {("$current_url", "event", None): 1, ("$browser", "person", None): 1},- )-- retention_filter = RetentionFilter(data={"target_entity": {"id": action.id, "type": "actions"}})- self.assertEqual(- EnterpriseColumnOptimizer(retention_filter, self.team.id).properties_used_in_filter,- {("$current_url", "event", None): 2, ("$browser", "person", None): 2},- )-- def test_materialized_columns_checks(self):- optimizer = lambda: EnterpriseColumnOptimizer(- self._legacy_events_schema_filter(FILTER_WITH_PROPERTIES.to_dict()), self.team.id- )- optimizer_groups = lambda: EnterpriseColumnOptimizer(- self._legacy_events_schema_filter(FILTER_WITH_GROUPS.to_dict()), self.team.id- )-- self.assertEqual(optimizer().event_columns_to_query, {"properties"})- self.assertEqual(optimizer().person_columns_to_query, {"properties"})- self.assertEqual(optimizer_groups().event_columns_to_query, {"properties"})- self.assertEqual(optimizer_groups().person_columns_to_query, {"properties"})-- materialize("events", "event_prop")- materialize("person", "person_prop")-- self.assertEqual(optimizer().event_columns_to_query, {"mat_event_prop"})- self.assertEqual(optimizer().person_columns_to_query, {"pmat_person_prop"})- self.assertEqual(optimizer_groups().event_columns_to_query, {"mat_event_prop"})- self.assertEqual(optimizer_groups().person_columns_to_query, {"pmat_person_prop"})-- def test_materialized_columns_checks_person_on_events(self):- optimizer = lambda: EnterpriseColumnOptimizer(- self._legacy_events_schema_filter(- {- **BASE_FILTER.to_dict(),- "properties": [- {- "key": "person_prop",- "value": ["value"],- "operator": "exact",- "type": "person",- },- ],- }- ),- self.team.id,- )-- self.assertEqual(optimizer().person_on_event_columns_to_query, {"person_properties"})-- # materialising the props on `person` table should make no difference- materialize("person", "person_prop")-- self.assertEqual(optimizer().person_on_event_columns_to_query, {"person_properties"})-- materialize("events", "person_prop", table_column="person_properties")-- self.assertEqual(optimizer().person_on_event_columns_to_query, {"mat_pp_person_prop"})-- def test_group_types_to_query(self):- group_types_to_query = lambda filter: EnterpriseColumnOptimizer(filter, self.team.id).group_types_to_query-- self.assertEqual(group_types_to_query(BASE_FILTER), set())- self.assertEqual(group_types_to_query(FILTER_WITH_PROPERTIES), {2})- self.assertEqual(group_types_to_query(FILTER_WITH_GROUPS), {2})diff --git a/ee/clickhouse/queries/test/test_person_query.py b/ee/clickhouse/queries/test/test_person_query.pydeleted file mode 100644index 0225582d82c4..000000000000--- a/ee/clickhouse/queries/test/test_person_query.py+++ /dev/null@@ -1,408 +0,0 @@-import pytest-from posthog.test.base import _create_person, cleanup_materialized_columns--from posthog.clickhouse.client import sync_execute-from posthog.models.filters import Filter-from posthog.models.property import Property-from posthog.models.team import Team-from posthog.queries.person_query import PersonQuery--from products.cohorts.backend.models.cohort import Cohort--from ee.clickhouse.materialized_columns.columns import materialize---def person_query(team: Team, filter: Filter, **kwargs):- return PersonQuery(filter, team.pk, **kwargs).get_query()[0]---def run_query(team: Team, filter: Filter, **kwargs):- query, params = PersonQuery(filter, team.pk, **kwargs).get_query()- rows = sync_execute(query, {**params, **filter.hogql_context.values, "team_id": team.pk})- if len(rows) > 0:- return {"rows": len(rows), "columns": len(rows[0])}- else:- return {"rows": 0}---def testdata(db, team):- materialize("person", "email")- _create_person(- distinct_ids=["1"],- team_id=team.pk,- properties={"email": "[email protected]", "$os": "windows", "$browser": "chrome"},- )- _create_person(- distinct_ids=["2"],- team_id=team.pk,- properties={"email": "[email protected]", "$os": "Mac", "$browser": "firefox"},- )- _create_person(- distinct_ids=["3"],- team_id=team.pk,- properties={- "email": "[email protected]",- "$os": "windows",- "$browser": "mozilla",- },- )- yield- cleanup_materialized_columns()---def test_person_query(testdata, team, snapshot):- filter = Filter(data={"properties": []})-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 3, "columns": 1}-- filter = Filter(- data={- "properties": [- {"key": "event_prop", "value": "value"},- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- ]- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 2, "columns": 1}---def test_person_query_with_multiple_cohorts(testdata, team, snapshot):- filter = Filter(data={"properties": []})-- for i in range(10):- _create_person(- team_id=team.pk,- distinct_ids=[f"person{i}"],- properties={"group": str(i), "email": f"{i}@hey.com"},- )-- cohort1 = Cohort.objects.create(- team=team,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {"key": "group", "value": "none", "type": "person"},- {"key": "group", "value": ["1", "2", "3"], "type": "person"},- ],- }- ],- }- },- name="cohort1",- )-- cohort2 = Cohort.objects.create(- team=team,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "group",- "value": ["1", "2", "3", "4", "5", "6"],- "type": "person",- },- ],- }- ],- }- },- name="cohort2",- )-- cohort1.calculate_people_ch(pending_version=0)- cohort2.calculate_people_ch(pending_version=0)-- cohort_filters = [- Property(key="id", type="cohort", value=cohort1.pk),- Property(key="id", type="cohort", value=cohort2.pk),- ]-- filter = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- ]- }- )-- filter2 = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "hey",- "operator": "icontains",- },- ]- }- )-- assert run_query(team, filter) == {"rows": 2, "columns": 1}-- # 3 rows because the intersection between cohorts 1 and 2 is person1, person2, and person3,- # with their respective group properties- assert run_query(team, filter2, cohort_filters=cohort_filters) == {- "rows": 3,- "columns": 1,- }- assert person_query(team, filter2, cohort_filters=cohort_filters) == snapshot---def test_person_query_with_anded_property_groups(testdata, team, snapshot):- filter = Filter(- data={- "properties": {- "type": "AND",- "values": [- {"key": "event_prop", "value": "value"},- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- {- "key": "$os",- "type": "person",- "value": "windows",- "operator": "exact",- },- {- "key": "$browser",- "type": "person",- "value": "chrome",- "operator": "exact",- },- ],- }- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 1, "columns": 1}---def test_person_query_with_and_and_or_property_groups(testdata, team, snapshot):- filter = Filter(- data={- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- {- "key": "$browser",- "type": "person",- "value": "karl",- "operator": "icontains",- },- ],- },- {- "type": "OR",- "values": [- {"key": "event_prop", "value": "value"},- {- "key": "$os",- "type": "person",- "value": "windows",- "operator": "exact",- }, # this can't be pushed down- # so person query should return only rows from the first OR group- ],- },- ],- }- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 2, "columns": 2}---def test_person_query_with_extra_requested_fields(testdata, team, snapshot):- filter = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- }- ],- "breakdown": "person_prop_4326",- "breakdown_type": "person",- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 2, "columns": 2}-- filter = filter.shallow_clone({"breakdown": "email", "breakdown_type": "person"})- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 2, "columns": 2}---def test_person_query_with_entity_filters(testdata, team, snapshot):- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "properties": [- {- "key": "email",- "type": "person",- "value": "karl",- "operator": "icontains",- }- ],- }- ]- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 3, "columns": 2}-- assert person_query(team, filter, entity=filter.entities[0]) == snapshot- assert run_query(team, filter, entity=filter.entities[0]) == {- "rows": 1,- "columns": 1,- }---def test_person_query_with_extra_fields(testdata, team, snapshot):- filter = Filter(- data={- "properties": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- }- ]- }- )-- assert person_query(team, filter, extra_fields=["person_props", "pmat_email"]) == snapshot- assert run_query(team, filter, extra_fields=["person_props", "pmat_email"]) == {- "rows": 2,- "columns": 3,- }---def test_person_query_with_entity_filters_and_property_group_filters(testdata, team, snapshot):- filter = Filter(- data={- "events": [- {- "id": "$pageview",- "properties": {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "marius",- "operator": "icontains",- },- {- "key": "$os",- "type": "person",- "value": "windows",- "operator": "icontains",- },- ],- },- }- ],- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "posthog",- "operator": "icontains",- },- {- "key": "$browser",- "type": "person",- "value": "karl",- "operator": "icontains",- },- ],- },- {- "type": "OR",- "values": [- {"key": "event_prop", "value": "value"},- {- "key": "$os",- "type": "person",- "value": "windows",- "operator": "exact",- },- ],- },- ],- },- }- )-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 2, "columns": 3}-- assert person_query(team, filter, entity=filter.entities[0]) == snapshot- assert run_query(team, filter, entity=filter.entities[0]) == {- "rows": 2,- "columns": 2,- }---def test_person_query_with_updated_after(testdata, team, snapshot):- filter = Filter(data={"updated_after": "2023-04-04"})-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 3, "columns": 1}-- filter = Filter(data={"updated_after": "2055-04-04"})-- assert person_query(team, filter) == snapshot- assert run_query(team, filter) == {"rows": 0}diff --git a/ee/clickhouse/queries/test/test_property_optimizer.py b/ee/clickhouse/queries/test/test_property_optimizer.pydeleted file mode 100644index 907c035b64b3..000000000000--- a/ee/clickhouse/queries/test/test_property_optimizer.py+++ /dev/null@@ -1,552 +0,0 @@-import unittest--from posthog.models.filters import Filter-from posthog.queries.property_optimizer import PropertyOptimizer--PROPERTIES_OF_ALL_TYPES = [- {"key": "event_prop", "value": ["foo", "bar"], "type": "event"},- {"key": "person_prop", "value": "efg", "type": "person"},- {"key": "id", "value": 1, "type": "cohort"},- {"key": "tag_name", "value": ["label"], "operator": "exact", "type": "element"},- {- "key": "group_prop",- "value": ["value"],- "operator": "exact",- "type": "group",- "group_type_index": 2,- },-]--BASE_FILTER = Filter({"events": [{"id": "$pageview", "type": "events", "order": 0}]})-FILTER_WITH_GROUPS = BASE_FILTER.shallow_clone({"properties": {"type": "AND", "values": PROPERTIES_OF_ALL_TYPES}})-TEAM_ID = 3---class TestPersonPropertySelector(unittest.TestCase):- def test_basic_selector(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "OR",- "values": [- {"key": "person_prop", "value": "efg", "type": "person"},- {"key": "person_prop2", "value": "efg2", "type": "person"},- ],- }- }- )- self.assertTrue(PropertyOptimizer.using_only_person_properties(filter.property_groups))-- def test_multilevel_selector(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- },- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- },- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- },- {- "key": "person_prop",- "value": "efg",- "type": "person",- },- ],- },- ],- }- }- )-- self.assertFalse(PropertyOptimizer.using_only_person_properties(filter.property_groups))-- def test_multilevel_selector_with_valid_OR_persons(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "person",- },- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- },- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "person",- },- {- "key": "person_prop",- "value": "efg",- "type": "person",- },- ],- },- ],- }- }- )-- self.assertTrue(PropertyOptimizer.using_only_person_properties(filter.property_groups))---class TestPersonPushdown(unittest.TestCase):- maxDiff = None-- def test_basic_pushdowns(self):- property_groups = PropertyOptimizer().parse_property_groups(FILTER_WITH_GROUPS.property_groups)- inner = property_groups.inner- outer = property_groups.outer-- assert inner is not None- assert outer is not None-- self.assertEqual(- inner.to_dict(),- {- "type": "AND",- "values": [{"key": "person_prop", "value": "efg", "type": "person"}],- },- )-- self.assertEqual(- outer.to_dict(),- {- "type": "AND",- "values": [- {"key": "event_prop", "value": ["foo", "bar"], "type": "event"},- {"key": "id", "value": 1, "type": "cohort"},- {- "key": "tag_name",- "value": ["label"],- "operator": "exact",- "type": "element",- },- {- "key": "group_prop",- "value": ["value"],- "operator": "exact",- "type": "group",- "group_type_index": 2,- },- ],- },- )-- def test_person_properties_mixed_with_event_properties(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- },- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- },- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- },- {- "key": "person_prop",- "value": "efg",- "type": "person",- },- ],- },- ],- }- }- )-- property_groups = PropertyOptimizer().parse_property_groups(filter.property_groups)- inner = property_groups.inner- outer = property_groups.outer-- assert inner is not None- assert outer is not None-- self.assertEqual(- inner.to_dict(),- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [{"key": "person_prop", "value": "efg", "type": "person"}],- }- ],- },- )-- self.assertEqual(- outer.to_dict(),- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- },- {"key": "person_prop2", "value": "efg2", "type": "person"},- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- },- # {"key": "person_prop", "value": "efg", "type": "person", }, # this was pushed down- ],- },- ],- },- )-- def test_person_properties_with_or_not_mixed_with_event_properties(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "person_prop2",- "value": ["foo2", "bar2"],- "type": "person",- },- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- },- ],- },- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- },- {- "key": "person_prop",- "value": "efg",- "type": "person",- },- ],- },- ],- }- }- )-- property_groups = PropertyOptimizer().parse_property_groups(filter.property_groups)- inner = property_groups.inner- outer = property_groups.outer-- assert inner is not None- assert outer is not None-- self.assertEqual(- inner.to_dict(),- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "person_prop2",- "value": ["foo2", "bar2"],- "type": "person",- },- {"key": "person_prop2", "value": "efg2", "type": "person"},- ],- },- {- "type": "AND",- "values": [{"key": "person_prop", "value": "efg", "type": "person"}],- },- ],- },- )-- self.assertEqual(- outer.to_dict(),- {- "type": "AND",- "values": [- # OR group was pushed down, so not here anymore- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- },- # {"key": "person_prop", "value": "efg", "type": "person", }, # this was pushed down- ],- }- ],- },- )-- def test_person_properties_mixed_with_event_properties_with_misdirection_using_nested_groups(self):- filter = BASE_FILTER.shallow_clone(- {- "properties": {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- }- ],- }- ],- },- {- "type": "AND",- "values": [- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- }- ],- },- ],- }- ],- },- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- }- ],- }- ],- },- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "person_prop",- "value": "efg",- "type": "person",- }- ],- }- ],- }- ],- },- ],- },- ],- }- }- )-- property_groups = PropertyOptimizer().parse_property_groups(filter.property_groups)- inner = property_groups.inner- outer = property_groups.outer-- assert inner is not None- assert outer is not None-- self.assertEqual(- inner.to_dict(),- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "person_prop",- "value": "efg",- "type": "person",- }- ],- }- ],- }- ],- }- ],- }- ],- },- )-- self.assertEqual(- outer.to_dict(),- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "event_prop2",- "value": ["foo2", "bar2"],- "type": "event",- }- ],- }- ],- },- {- "type": "AND",- "values": [- {- "key": "person_prop2",- "value": "efg2",- "type": "person",- }- ],- },- ],- }- ],- },- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "key": "event_prop",- "value": ["foo", "bar"],- "type": "event",- }- ],- }- ],- },- # {"type": "OR", "values": [- # {"type": "AND", "values": [- # {"type": "OR", "values": [{"key": "person_prop", "value": "efg", "type": "person"}]}]- # }]}- # this was pushed down- ],- },- ],- },- )---# TODO: add macobo-groups in mixture to tests as welldiff --git a/posthog/models/filters/path_filter.py b/posthog/models/filters/path_filter.pyindex b6253e3d2c1b..6f80c621e6fa 100644--- a/posthog/models/filters/path_filter.py+++ b/posthog/models/filters/path_filter.py@@ -62,7 +62,7 @@ class PathFilter(OffsetMixin,PathLimitsMixin,GroupsAggregationMixin,- FunnelCorrelationMixin, # Typing pain because ColumnOptimizer expects a uniform filter+ FunnelCorrelationMixin, # Kept so all filter classes expose the same attribute surfaceClientQueryIdMixin,SimplifyFilterMixin,IncludeRecordingsMixin,diff --git a/posthog/models/filters/retention_filter.py b/posthog/models/filters/retention_filter.pyindex dbc6ea906a64..5133cab77a87 100644--- a/posthog/models/filters/retention_filter.py+++ b/posthog/models/filters/retention_filter.py@@ -38,7 +38,7 @@ class RetentionFilter(OffsetMixin,LimitMixin,GroupsAggregationMixin,- FunnelCorrelationMixin, # Typing pain because ColumnOptimizer expects a uniform filter+ FunnelCorrelationMixin, # Kept so all filter classes expose the same attribute surface# TODO: proper fix for EventQuery abstraction, make filters uniformClientQueryIdMixin,SimplifyFilterMixin,diff --git a/posthog/models/property/util.py b/posthog/models/property/util.pyindex 9a0d60cbb41b..13c3ce0292b1 100644--- a/posthog/models/property/util.py+++ b/posthog/models/property/util.py@@ -186,18 +186,6 @@ def parse_prop_clauses()params = {**params, **cohort_filter_params}final.append(f"{property_operator} {person_id_query}")- elif prop.type == "person" and person_properties_mode == PersonPropertiesMode.DIRECT_ON_PERSONS:- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend,- prop_var="properties",- allow_denormalized_props=allow_denormalized_props,- property_operator=property_operator,- table_name=table_name,- )- final.append(f" {filter_query}")- params.update(filter_params)elif prop.type == "person" and person_properties_mode in [PersonPropertiesMode.DIRECT_ON_EVENTS,PersonPropertiesMode.DIRECT_ON_EVENTS_WITH_POE_V2,@@ -214,7 +202,7 @@ def parse_prop_clauses()final.append(filter_query)params.update(filter_params)- elif prop.type == "person" and person_properties_mode != PersonPropertiesMode.DIRECT:+ elif prop.type == "person":# :TODO: Clean this up by using PersonQuery over GET_DISTINCT_IDS_BY_PROPERTY_SQL to have access# to materialized columns# :TODO: (performance) Avoid subqueries whenever possible, use joins instead@@ -244,20 +232,6 @@ def parse_prop_clauses())params.update(filter_params)- elif prop.type == "person" and person_properties_mode == PersonPropertiesMode.DIRECT:- # this setting is used to generate the PersonQuery SQL.- # When using direct mode, there should only be person properties in the entire- # property group- filter_query, filter_params = prop_filter_json_extract(- prop,- idx,- prepend=f"personquery_{prepend}",- allow_denormalized_props=True,- transform_expression=lambda column_name: f"argMax(person.{column_name}, version)",- property_operator=property_operator,- )- final.append(filter_query)- params.update(filter_params)elif prop.type == "event":filter_query, filter_params = prop_filter_json_extract(prop,diff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 68b91c85fd22..0914fd7e0ad6 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -20,7 +20,6 @@ import pydanticfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_contextfrom posthog.cloud_utils import is_cloudfrom posthog.helpers.session_recording_playlist_templates import DEFAULT_PLAYLISTS-from posthog.models.filters.filter import Filterfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.instance_setting import get_instance_setting@@ -53,6 +52,8 @@ from .team_caching import get_team_in_cache, set_team_in_cacheif TYPE_CHECKING:from posthog.schema import PathCleaningFilter+ from posthog.hogql.database.database import Database+from posthog.models.user import UserTIMEZONES = [(tz, tz) for tz in pytz.all_timezones]@@ -880,21 +881,29 @@ class Team(UUIDTClassicModel):@cached_propertydef persons_seen_so_far(self) -> int:- from posthog.clickhouse.client import sync_execute- from posthog.queries.person_query import PersonQuery+ return self.count_persons_seen_so_far()++ def count_persons_seen_so_far(self, database: Optional["Database"] = None) -> int:+ from posthog.schema import HogQLQueryModifiers- filter = Filter(data={"full": "true"})- person_query, person_query_params = PersonQuery(filter, self.id).get_query()+ from posthog.hogql.context import HogQLContext+ from posthog.hogql.query import execute_hogql_query++ from posthog.schema_enums import PersonsArgMaxVersionwith tags_context(product=Product.FEATURE_FLAGS, feature=Feature.QUERY):- return sync_execute(- f"""- SELECT count(1) FROM (- {person_query}- )- """,- {**person_query_params, **filter.hogql_context.values},- )[0][0]+ return execute_hogql_query(+ "SELECT count() FROM persons",+ team=self,+ query_type="persons_seen_so_far",+ # Pin v1 because the v2 persons path pushes the executor's default LIMIT into its+ # dedup subquery, which caps a bare count() at ~101 for teams pinned to v2 (see #87323).+ modifiers=HogQLQueryModifiers(personsArgMaxVersion=PersonsArgMaxVersion.V1),+ # A caller that runs several queries can pass a prebuilt database to skip a rebuild.+ # The v1 pin survives a shared database: the persons table reads the dedup mode from+ # each query's modifiers at print time, not from the database.+ context=HogQLContext(team_id=self.pk, database=database),+ ).results[0][0]@lru_cache(maxsize=5) # noqa: B019 - TODO: refactor to module-level cachedef groups_seen_so_far(self, group_type_index: GroupTypeIndex) -> int:diff --git a/posthog/queries/column_optimizer/__init__.py b/posthog/queries/column_optimizer/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/queries/column_optimizer/column_optimizer.py b/posthog/queries/column_optimizer/column_optimizer.pydeleted file mode 100644index bfc32a6eb550..000000000000--- a/posthog/queries/column_optimizer/column_optimizer.py+++ /dev/null@@ -1,11 +0,0 @@-# isort: skip_file-from posthog.settings import EE_AVAILABLE--if EE_AVAILABLE:- from ee.clickhouse.queries.column_optimizer import (- EnterpriseColumnOptimizer as ColumnOptimizer,- )-else:- from posthog.queries.column_optimizer.foss_column_optimizer import ( # type: ignore- FOSSColumnOptimizer as ColumnOptimizer, # noqa: F401- )diff --git a/posthog/queries/column_optimizer/foss_column_optimizer.py b/posthog/queries/column_optimizer/foss_column_optimizer.pydeleted file mode 100644index e21bdcd32a1a..000000000000--- a/posthog/queries/column_optimizer/foss_column_optimizer.py+++ /dev/null@@ -1,180 +0,0 @@-from collections import (- Counter,- Counter as TCounter,-)-from collections.abc import Generator-from typing import Union, cast--from posthog.clickhouse.materialized_columns import ColumnName, get_materialized_column_for_property-from posthog.constants import TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType-from posthog.models.entity import Entity-from posthog.models.filters import Filter-from posthog.models.filters.mixins.utils import cached_property-from posthog.models.filters.path_filter import PathFilter-from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter-from posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.stickiness_filter import StickinessFilter-from posthog.models.filters.utils import GroupTypeIndex-from posthog.models.property import PropertyIdentifier, PropertyType, TableColumn, TableWithProperties-from posthog.models.property.util import box_value, extract_tables_and_properties-from posthog.queries.property_optimizer import PropertyOptimizer--from products.actions.backend.models.util import get_action_tables_and_properties---class FOSSColumnOptimizer:- """- This class is responsible for figuring out what columns can and should be materialized based on the query filter.-- This speeds up queries since clickhouse ends up selecting less data.- """-- def __init__(- self,- filter: Union[- Filter,- PathFilter,- RetentionFilter,- StickinessFilter,- PropertiesTimelineFilter,- ],- team_id: int,- ):- self.filter = filter- self.team_id = team_id- self.property_optimizer = PropertyOptimizer()-- @cached_property- def event_columns_to_query(self) -> set[ColumnName]:- "Returns a list of event table columns containing materialized properties that this query needs"-- return self.columns_to_query("events", set(self.used_properties_with_type("event")))-- @cached_property- def person_on_event_columns_to_query(self) -> set[ColumnName]:- "Returns a list of event table person columns containing materialized properties that this query needs"-- return self.columns_to_query("events", set(self.used_properties_with_type("person")), "person_properties")-- @cached_property- def person_columns_to_query(self) -> set[ColumnName]:- "Returns a list of person table columns containing materialized properties that this query needs"-- return self.columns_to_query("person", set(self.used_properties_with_type("person")))-- def columns_to_query(- self,- table: TableWithProperties,- used_properties: set[PropertyIdentifier],- table_column: TableColumn = "properties",- ) -> set[ColumnName]:- "Transforms a list of property names to what columns are needed for that query"- if not used_properties:- return set()- # The native-JSON events schema has no mat_* columns; property SQL reads subcolumns off the- # JSON column itself, so that column is all a query needs to select.- if table == "events" and self.filter.hogql_context.uses_new_events_schema():- return {table_column}- column_names = set()- for property_name, _, _ in used_properties:- column = get_materialized_column_for_property(table, table_column, property_name)- if column is not None and not column.is_nullable:- column_names.add(column.name)- else:- column_names.add(table_column)- return column_names-- @cached_property- def is_using_person_properties(self) -> bool:- return len(self.used_properties_with_type("person")) > 0-- @cached_property- def is_using_cohort_propertes(self) -> bool:- return (- len(self.used_properties_with_type("cohort")) > 0- or len(self.used_properties_with_type("precalculated-cohort")) > 0- or len(self.used_properties_with_type("static-cohort")) > 0- )-- @cached_property- def group_types_to_query(self) -> set[GroupTypeIndex]:- return set()-- @cached_property- def properties_used_in_filter(self) -> TCounter[PropertyIdentifier]:- "Returns collection of properties + types that this query would use"- counter: TCounter[PropertyIdentifier] = extract_tables_and_properties(- self.filter.property_groups.flat, team_id=self.team_id- )-- if not isinstance(self.filter, StickinessFilter):- # Some breakdown types read properties- if self.filter.breakdown_type in ["event", "person"]:- boxed_breakdown = box_value(self.filter.breakdown)- for b in boxed_breakdown:- if isinstance(b, str):- counter[- (- b,- self.filter.breakdown_type,- self.filter.breakdown_group_type_index,- )- ] += 1-- # If we have a breakdowns attribute then make sure we pull in everything we- # need to calculate it- for breakdown in self.filter.breakdowns or []:- counter[- (- breakdown["property"],- breakdown["type"],- self.filter.breakdown_group_type_index,- )- ] += 1-- # Both entities and funnel exclusions can contain nested property filters- for entity in self.entities_used_in_filter():- counter += extract_tables_and_properties(entity.property_groups.flat, team_id=self.team_id)-- # Math properties are also implicitly used.- #- # See posthog/queries/trends/util.py#process_math- if entity.math_property:- counter[(entity.math_property, "event", None)] += 1-- # :TRICKY: If action contains property filters, these need to be included- #- # See ee/clickhouse/models/action.py#format_action_filter for an example- if entity.type == TREND_FILTER_TYPE_ACTIONS:- counter += get_action_tables_and_properties(entity.get_action(self.team_id))-- if (- not isinstance(self.filter, StickinessFilter | PropertiesTimelineFilter)- and self.filter.correlation_type == FunnelCorrelationType.PROPERTIES- and self.filter.correlation_property_names- ):- for prop_value in self.filter.correlation_property_names:- counter[(prop_value, "person", None)] += 1-- return counter-- def used_properties_with_type(self, property_type: PropertyType) -> TCounter[PropertyIdentifier]:- return Counter(- {- (name, type, group_type_index): count- for (- name,- type,- group_type_index,- ), count in self.properties_used_in_filter.items()- if type == property_type- }- )-- def entities_used_in_filter(self) -> Generator[Entity]:- yield from self.filter.entities- yield from cast(list[Entity], self.filter.exclusions)-- if isinstance(self.filter, RetentionFilter):- yield self.filter.target_entity- yield self.filter.returning_entitydiff --git a/posthog/queries/person_query.py b/posthog/queries/person_query.pydeleted file mode 100644index 0b0b30b80625..000000000000--- a/posthog/queries/person_query.py+++ /dev/null@@ -1,462 +0,0 @@-from typing import Any, Optional, Union, cast-from uuid import UUID--from posthog.clickhouse.materialized_columns import ColumnName-from posthog.constants import PropertyOperatorType-from posthog.models import Filter-from posthog.models.entity import Entity-from posthog.models.filters.path_filter import PathFilter-from posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.stickiness_filter import StickinessFilter-from posthog.models.property import Property, PropertyGroup-from posthog.models.property.util import (- extract_tables_and_properties,- parse_prop_grouped_clauses,- prop_filter_json_extract,-)-from posthog.queries.column_optimizer.column_optimizer import ColumnOptimizer-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query-from posthog.queries.trends.util import COUNT_PER_ACTOR_MATH_FUNCTIONS-from posthog.queries.util import PersonPropertiesMode--from products.cohorts.backend.models.cohort import Cohort-from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID, GET_STATIC_COHORTPEOPLE_BY_COHORT_ID-from products.cohorts.backend.models.util import format_precalculated_cohort_query, format_static_cohort_query---class PersonQuery:- """- Query class responsible for joining with `person` clickhouse table-- For sake of performance, this class:- - Tries to do as much person property filtering as possible here- - Minimizes the amount of columns read- """-- PERSON_PROPERTIES_ALIAS = "person_props"- COHORT_TABLE_ALIAS = "cohort_persons"- ALIASES = {"properties": "person_props"}-- _filter: Union[Filter, PathFilter, RetentionFilter, StickinessFilter]- _team_id: int- _column_optimizer: ColumnOptimizer- _extra_fields: set[ColumnName]- _inner_person_properties: Optional[PropertyGroup]- _cohort: Optional[Cohort]- _include_distinct_ids: Optional[bool] = False-- def __init__(- self,- filter: Union[Filter, PathFilter, RetentionFilter, StickinessFilter],- team_id: int,- column_optimizer: Optional[ColumnOptimizer] = None,- cohort: Optional[Cohort] = None,- *,- entity: Optional[Entity] = None,- extra_fields: Optional[list[ColumnName]] = None,- # A sub-optimal version of the `cohort` parameter above, the difference being that- # this supports multiple cohort filters, but is not as performant as the above.- cohort_filters: Optional[list[Property]] = None,- include_distinct_ids: Optional[bool] = False,- ) -> None:- self._filter = filter- self._team_id = team_id- self._entity = entity- self._cohort = cohort- self._column_optimizer = column_optimizer or ColumnOptimizer(self._filter, self._team_id)- self._extra_fields = set(extra_fields) if extra_fields else set()- self._cohort_filters = cohort_filters- self._include_distinct_ids = include_distinct_ids-- if self.PERSON_PROPERTIES_ALIAS in self._extra_fields:- self._extra_fields = self._extra_fields - {self.PERSON_PROPERTIES_ALIAS} | {"properties"}-- properties = self._filter.property_groups.combine_property_group(- PropertyOperatorType.AND,- self._entity.property_groups if self._entity else None,- )-- self._inner_person_properties = self._column_optimizer.property_optimizer.parse_property_groups(- properties- ).inner-- def get_query(- self,- prepend: Optional[Union[str, int]] = None,- paginate: bool = False,- filter_future_persons: bool = False,- ) -> tuple[str, dict]:- prepend = str(prepend) if prepend is not None else ""-- fields = "id" + " ".join(- f", argMax({column_name}, version) as {alias}" for column_name, alias in self._get_fields()- )-- (- person_filters_prefiltering_condition,- person_filters_finalization_condition,- person_filters_params,- ) = self._get_person_filter_clauses(prepend=prepend)- (- multiple_cohorts_condition,- multiple_cohorts_params,- ) = self._get_multiple_cohorts_clause(prepend=prepend)- single_cohort_join, single_cohort_params = self._get_fast_single_cohort_clause()- if paginate:- order = "ORDER BY argMax(person.created_at, version) DESC, id DESC" if paginate else ""- limit_offset, limit_params = self._get_limit_offset_clause()- else:- order = ""- limit_offset, limit_params = "", {}- (- search_prefiltering_condition,- search_finalization_condition,- search_params,- ) = self._get_search_clauses(prepend=prepend)- distinct_id_condition, distinct_id_params = self._get_distinct_id_clause()- email_condition, email_params = self._get_email_clause()- filter_future_persons_condition = (- "AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY" if filter_future_persons else ""- )- updated_after_condition, updated_after_params = self._get_updated_after_clause()-- # If there are person filters or search, we do a prefiltering lookup so that the dataset is as small- # as possible BEFORE the `HAVING` clause (but without eliminating any rows that should be matched).- # This greatly reduces memory usage because in this lookup we don't aggregate by person version.- # Additionally, if we're doing prefiltering, it's more efficient to filter by the single cohort inner join here.- prefiltering_lookup = (- f"""AND id IN (- SELECT id FROM person- {single_cohort_join}- WHERE team_id = %(team_id)s- {person_filters_prefiltering_condition}- {search_prefiltering_condition}- )- """- if person_filters_prefiltering_condition or search_prefiltering_condition- else ""- )- # If we're not prefiltering, the single cohort inner join needs to be at the top level.- top_level_single_cohort_join = single_cohort_join if not prefiltering_lookup else ""-- return self._add_distinct_id_join_if_needed(- f"""- SELECT {fields}- FROM person- {top_level_single_cohort_join}- WHERE team_id = %(team_id)s- {prefiltering_lookup}- {multiple_cohorts_condition}- {email_condition}- GROUP BY id- HAVING max(is_deleted) = 0- {filter_future_persons_condition} {updated_after_condition}- {person_filters_finalization_condition} {search_finalization_condition}- {distinct_id_condition}- {order}- {limit_offset}- SETTINGS optimize_aggregation_in_order = 1- """,- {- **updated_after_params,- **person_filters_params,- **single_cohort_params,- **limit_params,- **search_params,- **distinct_id_params,- **email_params,- **multiple_cohorts_params,- "team_id": self._team_id,- },- )-- def get_uniq_count(self) -> tuple[str, dict]:- """- Returns a simplified query that counts unique person IDs using uniq(id).- This is more efficient than the full get_query() for counting purposes.- Ignores prefiltering optimizations and is_deleted checks for simplicity.- """- (- person_filters_prefiltering_condition,- _,- person_filters_params,- ) = self._get_person_filter_clauses()- (- multiple_cohorts_condition,- multiple_cohorts_params,- ) = self._get_multiple_cohorts_clause()- single_cohort_join, single_cohort_params = self._get_fast_single_cohort_clause()- (- search_prefiltering_condition,- _,- search_params,- ) = self._get_search_clauses()- distinct_id_condition, distinct_id_params = self._get_distinct_id_clause()- email_condition, email_params = self._get_email_clause()-- return (- f"""- SELECT uniq(id)- FROM person- {single_cohort_join}- WHERE team_id = %(team_id)s- {multiple_cohorts_condition}- {email_condition}- {person_filters_prefiltering_condition} {search_prefiltering_condition}- {distinct_id_condition}- """,- {- **person_filters_params,- **single_cohort_params,- **search_params,- **distinct_id_params,- **email_params,- **multiple_cohorts_params,- "team_id": self._team_id,- },- )-- @property- def fields(self) -> list[ColumnName]:- "Returns person table fields this query exposes"- return [alias for column_name, alias in self._get_fields()]-- @property- def is_used(self):- "Returns whether properties or any other columns are actually being queried"- if any(self._uses_person_id(prop) for prop in self._filter.property_groups.flat):- return True- for entity in self._filter.entities:- is_count_per_user = entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS and entity.math_group_type_index is None- if is_count_per_user or any(self._uses_person_id(prop) for prop in entity.property_groups.flat):- return True-- return len(self._column_optimizer.person_columns_to_query) > 0-- def _uses_person_id(self, prop: Property) -> bool:- return prop.type in ("person", "static-cohort", "precalculated-cohort")-- def _get_fields(self) -> list[tuple[str, str]]:- # :TRICKY: Figure out what fields we want to expose - minimizing this set is good for performance.- # We use the result from column_optimizer to figure out counts of all properties to be filtered and queried.- # Here, we remove the ones only to be used for filtering.- # The same property might be present for both querying and filtering, and hence the Counter.- properties_to_query = self._column_optimizer.used_properties_with_type("person")- if self._inner_person_properties:- properties_to_query -= extract_tables_and_properties(- self._inner_person_properties.flat, team_id=self._team_id- )-- columns = self._column_optimizer.columns_to_query("person", set(properties_to_query)) | set(self._extra_fields)-- return [(column_name, self.ALIASES.get(column_name, column_name)) for column_name in sorted(columns)]-- def _get_person_filter_clauses(self, prepend: str = "") -> tuple[str, str, dict]:- finalization_conditions, params = parse_prop_grouped_clauses(- self._team_id,- self._inner_person_properties,- has_person_id_joined=False,- group_properties_joined=False,- person_properties_mode=PersonPropertiesMode.DIRECT,- prepend=f"person_filter_fin_{prepend}",- hogql_context=self._filter.hogql_context,- )- prefiltering_conditions, prefiltering_params = parse_prop_grouped_clauses(- self._team_id,- self._inner_person_properties,- has_person_id_joined=False,- group_properties_joined=False,- # The above kwargs are the same as for finalization EXCEPT this one - we use the property- # from the person BEFORE aggregation by version here, to eliminate persons early on- person_properties_mode=PersonPropertiesMode.DIRECT_ON_PERSONS,- prepend=f"person_filter_pre_{prepend}",- hogql_context=self._filter.hogql_context,- )- params.update(prefiltering_params)- return prefiltering_conditions, finalization_conditions, params-- def _get_fast_single_cohort_clause(self) -> tuple[str, dict]:- if self._cohort:- cohort_table = (- GET_STATIC_COHORTPEOPLE_BY_COHORT_ID if self._cohort.is_static else GET_COHORTPEOPLE_BY_COHORT_ID- )- return (- f"""- INNER JOIN (- {cohort_table}- ) {self.COHORT_TABLE_ALIAS}- ON {self.COHORT_TABLE_ALIAS}.person_id = person.id- """,- {- "team_id": self._team_id,- "cohort_id": self._cohort.pk,- "version": self._cohort.version,- },- )- else:- return "", {}-- def _get_multiple_cohorts_clause(self, prepend: str = "") -> tuple[str, dict]:- if self._cohort_filters:- query = []- params: dict[str, Any] = {}-- # TODO: doesn't support non-caclculated cohorts- for index, property in enumerate(self._cohort_filters):- try:- cohort = Cohort.objects.get(pk=cast(str | int, property.value), team_id=self._team_id)- if property.type == "static-cohort":- subquery, subquery_params = format_static_cohort_query(cohort, index, prepend)- else:- subquery, subquery_params = format_precalculated_cohort_query(cohort, index, prepend)- query.append(f"AND id in ({subquery})")- params.update(**subquery_params)- except Cohort.DoesNotExist:- continue-- return " ".join(query), params- else:- return "", {}-- def _get_limit_offset_clause(self) -> tuple[str, dict]:- if not isinstance(self._filter, Filter):- return "", {}-- if not (self._filter.limit or self._filter.offset):- return "", {}-- clause = ""-- params = {}-- if self._filter.limit:- clause += " LIMIT %(limit)s"- params.update({"limit": self._filter.limit})-- if self._filter.offset:- clause += " OFFSET %(offset)s"- params.update({"offset": self._filter.offset})-- return clause, params-- def _get_search_clauses(self, prepend: str = "") -> tuple[str, str, dict]:- """- Return - respectively - the prefiltering search clause (not aggregated by is_deleted or version, which is great- for memory usage), the final search clause (aggregated for true results, more expensive), and new params.- """- if not isinstance(self._filter, Filter):- return "", "", {}-- if self._filter.search:- id_conditions_param = f"id_conditions_{prepend}"- id_conditions_sql = f"""- id IN (- SELECT person_id FROM ({get_team_distinct_ids_query(self._team_id)})- WHERE distinct_id = %({id_conditions_param})s- )- """- try:- UUID(self._filter.search)- except ValueError:- pass- else:- id_conditions_sql = f"(id = %({id_conditions_param})s OR {id_conditions_sql})"-- prop_group = PropertyGroup(- type=PropertyOperatorType.AND,- values=[- Property(- key="email",- operator="icontains",- value=self._filter.search,- type="person",- )- ],- )- finalization_conditions_sql, params = parse_prop_grouped_clauses(- team_id=self._team_id,- property_group=prop_group,- prepend=f"search_fin_{prepend}",- has_person_id_joined=False,- group_properties_joined=False,- person_properties_mode=PersonPropertiesMode.DIRECT,- _top_level=False,- hogql_context=self._filter.hogql_context,- )- finalization_sql = f"AND ({finalization_conditions_sql} OR {id_conditions_sql})"-- (- prefiltering_conditions_sql,- prefiltering_params,- ) = parse_prop_grouped_clauses(- team_id=self._team_id,- property_group=prop_group,- prepend=f"search_pre_{prepend}",- has_person_id_joined=False,- group_properties_joined=False,- # The above kwargs are the same as for finalization EXCEPT this one - we use the property- # from the person BEFORE aggregation by version here, to eliminate persons early on- person_properties_mode=PersonPropertiesMode.DIRECT_ON_PERSONS,- _top_level=False,- hogql_context=self._filter.hogql_context,- )- params.update(prefiltering_params)- prefiltering_sql = f"""AND ({prefiltering_conditions_sql} OR {id_conditions_sql})"""-- params.update({id_conditions_param: self._filter.search})-- return prefiltering_sql, finalization_sql, params-- return "", "", {}-- def _get_distinct_id_clause(self) -> tuple[str, dict]:- if not isinstance(self._filter, Filter):- return "", {}-- if self._filter.distinct_id:- distinct_id_clause = f"""- AND id IN (- SELECT person_id FROM ({get_team_distinct_ids_query(self._team_id)}) where distinct_id = %(distinct_id_filter)s- )- """- return distinct_id_clause, {"distinct_id_filter": self._filter.distinct_id}- return "", {}-- def _add_distinct_id_join_if_needed(self, query: str, params: dict[Any, Any]) -> tuple[str, dict[Any, Any]]:- if not self._include_distinct_ids:- return query, params- return (- """- SELECT person.*, groupArray(pdi.distinct_id) as distinct_ids- FROM ({person_query}) person- LEFT JOIN ({distinct_id_query}) as pdi ON person.id=pdi.person_id- GROUP BY person.*- ORDER BY created_at desc, id desc- """.format(- person_query=query,- distinct_id_query=get_team_distinct_ids_query(self._team_id),- ),- params,- )-- def _get_email_clause(self) -> tuple[str, dict]:- if not isinstance(self._filter, Filter):- return "", {}-- if self._filter.email:- return prop_filter_json_extract(- Property(key="email", value=self._filter.email, type="person"),- 0,- prepend="_email",- )- return "", {}-- def _get_updated_after_clause(self) -> tuple[str, dict]:- if not isinstance(self._filter, Filter):- return "", {}-- if self._filter.updated_after:- return "and max(_timestamp) > parseDateTimeBestEffort(%(updated_after)s)", {- "updated_after": self._filter.updated_after- }- return "", {}diff --git a/posthog/queries/property_optimizer.py b/posthog/queries/property_optimizer.pydeleted file mode 100644index b11be666fd68..000000000000--- a/posthog/queries/property_optimizer.py+++ /dev/null@@ -1,101 +0,0 @@-from dataclasses import dataclass-from typing import Optional, cast--from rest_framework.exceptions import ValidationError--from posthog.constants import PropertyOperatorType-from posthog.models.property import Property, PropertyGroup---@dataclass(frozen=True)-class PropertyGroups:- outer: Optional[PropertyGroup]- inner: Optional[PropertyGroup]---class PropertyOptimizer:- """- This class is responsible for figuring out what person or group properties can and should be pushed down to their- respective tables in the query filter.-- This speeds up queries since clickhouse ends up selecting less data.- """-- def parse_property_groups(self, property_group: PropertyGroup) -> PropertyGroups:- "Returns outer and inner property groups for persons"-- if len(property_group.values) == 0:- return PropertyGroups(None, None)-- # If all person properties, push them down- if property_group.type == PropertyOperatorType.OR:- # with OR'ed properties, we can't push properties down,- # unless they're all person properties- if self.using_only_person_properties(property_group):- return PropertyGroups(None, property_group)- else:- return PropertyGroups(property_group, None)-- else:- # Top level type is AND.- # If all person properties, push them down- if self.using_only_person_properties(property_group):- return PropertyGroups(None, property_group)- else:- # Mixed, look into each individual group- if isinstance(property_group.values[0], PropertyGroup):- # multiple nested property groups- # we care about selecting AND groups with person properties- outer_property_group_values = []- inner_property_group_values = []- for group in property_group.values:- assert isinstance(group, PropertyGroup)-- subquery_groups = self.parse_property_groups(group)- if subquery_groups.outer:- outer_property_group_values.append(subquery_groups.outer)-- if subquery_groups.inner:- inner_property_group_values.append(subquery_groups.inner)-- return PropertyGroups(- PropertyGroup(PropertyOperatorType.AND, outer_property_group_values),- PropertyGroup(PropertyOperatorType.AND, inner_property_group_values),- )-- elif isinstance(property_group.values[0], Property):- # list of properties that have been AND'ed, safe to push- # all person properties down, rest go to outer group- outer_property_values = []- inner_property_values = []- for property in property_group.values:- assert isinstance(property, Property)-- if property.type == "person":- inner_property_values.append(property)- else:- outer_property_values.append(property)- return PropertyGroups(- PropertyGroup(PropertyOperatorType.AND, outer_property_values),- PropertyGroup(PropertyOperatorType.AND, inner_property_values),- )-- else:- raise ValidationError("Invalid property group values")-- @staticmethod- def using_only_person_properties(property_group: PropertyGroup) -> bool:- if len(property_group.values) == 0:- return True-- if isinstance(property_group.values[0], Property):- return all(property.type == "person" for property in property_group.values)-- elif isinstance(property_group.values[0], PropertyGroup):- return all(- PropertyOptimizer.using_only_person_properties(group)- for group in cast(list[PropertyGroup], property_group.values)- )-- else:- raise ValidationError("Invalid property group values")diff --git a/posthog/queries/test/test_person_query.py b/posthog/queries/test/test_person_query.pydeleted file mode 100644index b3a0230ce6e1..000000000000--- a/posthog/queries/test/test_person_query.py+++ /dev/null@@ -1,86 +0,0 @@-import re--from freezegun import freeze_time-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events--from posthog.clickhouse.client import sync_execute-from posthog.models import Filter-from posthog.queries.column_optimizer.column_optimizer import ColumnOptimizer-from posthog.queries.person_query import PersonQuery--from products.cohorts.backend.models.cohort import Cohort---class TestPersonQuery(ClickhouseTestMixin, APIBaseTest):- @freeze_time("2021-01-01T00:00:00Z")- def test_cohort_join_moves_into_prefiltering_subquery_with_person_property_filters(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"in_cohort": "yes", "color": "blue"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"in_cohort": "yes", "color": "blue"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["p3"],- properties={"in_cohort": "yes", "color": "red"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["p4"],- properties={"in_cohort": "no", "color": "blue"},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["p5"],- properties={"in_cohort": "no", "color": "red"},- )- flush_persons_and_events()-- cohort = Cohort.objects.create(- team=self.team,- name="in_cohort_yes",- groups=[{"properties": [{"key": "in_cohort", "value": "yes", "type": "person"}]}],- )- cohort.calculate_people_ch(pending_version=0)-- filter = Filter(- data={- "properties": [- {"key": "color", "value": "blue", "type": "person"},- ],- }- )-- column_optimizer = ColumnOptimizer(filter, self.team.pk)- person_query = PersonQuery(- filter=filter,- team_id=self.team.pk,- column_optimizer=column_optimizer,- cohort=cohort,- )-- sql, params = person_query.get_query()-- # When person property filters are present (causing prefiltering), the cohort INNER JOIN- # should be inside the prefiltering subquery, not at the top level.- # Extract the prefiltering subquery using regex to avoid brittle index-based parsing.- prefiltering_match = re.search(r"AND id IN\s*\((.*?)\)\s*(?:GROUP BY|$)", sql, re.DOTALL)- assert prefiltering_match is not None, "Expected a prefiltering subquery (AND id IN (...))"-- prefiltering_subquery = prefiltering_match.group(1)- assert "INNER JOIN" in prefiltering_subquery, (- "Expected the cohort INNER JOIN to be inside the prefiltering subquery"- )-- # The top-level query (outside the prefiltering subquery) should NOT have the cohort join- top_level_sql = sql[: prefiltering_match.start()] + sql[prefiltering_match.end() :]- assert "INNER JOIN" not in top_level_sql, "Expected no top-level INNER JOIN when prefiltering is active"-- # Execute the query and verify the correct number of results- results = sync_execute(sql, params)- assert len(results) == 2, f"Expected 2 persons (in cohort + color=blue), got {len(results)}"diff --git a/posthog/queries/trends/util.py b/posthog/queries/trends/util.pyindex 3db2b5a83fe4..23fb1ca4ea08 100644--- a/posthog/queries/trends/util.py+++ b/posthog/queries/trends/util.py@@ -6,8 +6,7 @@ from zoneinfo import ZoneInfoimport structlogfrom dateutil.relativedelta import relativedelta-from posthog.constants import NON_TIME_SERIES_DISPLAY_TYPES, UNIQUE_GROUPS-from posthog.models.entity import Entity+from posthog.constants import NON_TIME_SERIES_DISPLAY_TYPESfrom posthog.models.filters import Filterfrom posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterfrom posthog.models.team import Team@@ -43,12 +42,6 @@ ALL_SUPPORTED_MATH_FUNCTIONS = []-def is_series_group_based(entity: Entity) -> bool:- return entity.math == UNIQUE_GROUPS or (- entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS and entity.math_group_type_index is not None- )--F = TypeVar("F", Filter, PropertiesTimelineFilter)diff --git a/posthog/queries/util.py b/posthog/queries/util.pyindex 62c3e853224b..f2baf580c18f 100644--- a/posthog/queries/util.py+++ b/posthog/queries/util.py@@ -14,16 +14,6 @@ from posthog.schema_enums import PersonsOnEventsModeclass PersonPropertiesMode(Enum):USING_SUBQUERY = auto()USING_PERSON_PROPERTIES_COLUMN = auto()- # Used for generating query on Person table- DIRECT = auto()- """Get person property from the persons table, selecting the latest version of the person."""- DIRECT_ON_PERSONS = auto()- """- Get person property from the persons table WITHOUT aggregation by version. Not fully accurate, as old versions- of the person will be matched, but useful for prefiltering on whether _any_ version of the person has ever matched.- That's a good way of eliminating most persons early on in the query pipeline, which can greatly reduce the overall- memory usage of a query (as aggregation by version happens in-memory).- """DIRECT_ON_EVENTS = auto()"""Get person property from the events table (persons-on-events v1 - no person ID overrides),diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex b501c0bc0fed..5ec5a4b38d26 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -1,4 +1,79 @@# serializer version: 1+# name: TestBlastRadius.test_persons_seen_so_far_ignores_team_v2_argmax_modifier+ '''+ SELECT count() AS `count()`+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestBlastRadius.test_persons_seen_so_far_ignores_team_v2_argmax_modifier.1+ '''+ SELECT count(DISTINCT persons.id) AS `count(DISTINCT persons.id)`+ FROM+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'group'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___group,+ argMax(person.team_id, person.version) AS team_id,+ person.id AS id+ FROM person+ WHERE and(equals(person.team_id, 99999), in(id,+ (SELECT where_optimization.id AS id+ FROM person AS where_optimization+ WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'group'), ''), 'null'), '^"|"$', ''), '0'), 0)))))+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons+ WHERE and(equals(persons.team_id, 99999), ifNull(equals(persons.properties___group, '0'), 0))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestBlastRadius.test_persons_seen_so_far_ignores_team_v2_argmax_modifier.2+ '''+ SELECT count() AS `count()`+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestBlastRadius.test_user_blast_radius'''/* user_id:0 request:_snapshot_ */@@ -32,13 +107,25 @@# name: TestBlastRadius.test_user_blast_radius.1'''/* user_id:0 request:_snapshot_ */- SELECT count(1)+ SELECT count() AS `count()`FROM- (SELECT id+ (SELECT person.id AS idFROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestBlastRadius.test_user_blast_radius_with_group_key_property@@ -242,13 +329,25 @@# name: TestBlastRadius.test_user_blast_radius_with_multiple_precalculated_cohorts.3'''/* user_id:0 request:_snapshot_ */- SELECT count(1)+ SELECT count() AS `count()`FROM- (SELECT id+ (SELECT person.id AS idFROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts@@ -300,13 +399,25 @@# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.2'''/* user_id:0 request:_snapshot_ */- SELECT count(1)+ SELECT count() AS `count()`FROM- (SELECT id+ (SELECT person.id AS idFROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.3@@ -360,6 +471,30 @@use_hive_partitioning=0'''# ---+# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.5+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT count() AS `count()`+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestBlastRadius.test_user_blast_radius_with_single_cohort'''/* user_id:0 request:_snapshot_ */@@ -393,13 +528,25 @@# name: TestBlastRadius.test_user_blast_radius_with_single_cohort.1'''/* user_id:0 request:_snapshot_ */- SELECT count(1)+ SELECT count() AS `count()`FROM- (SELECT id+ (SELECT person.id AS idFROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestBlastRadius.test_user_blast_radius_with_single_cohort.2@@ -447,6 +594,30 @@use_hive_partitioning=0'''# ---+# name: TestBlastRadius.test_user_blast_radius_with_single_cohort.4+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT count() AS `count()`+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestFeatureFlag.test_creating_static_cohort'''SELECT "posthog_user"."id",diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 8e8de5291496..0d02dc8e3f74 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -28,6 +28,8 @@ from rest_framework import statusfrom rest_framework.relations import ManyRelatedFieldfrom rest_framework.response import Response+from posthog.hogql.database.database import Database+from posthog import redisfrom posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flagfrom posthog.api.services.flags_service import FlagVersionConflictError@@ -9360,6 +9362,38 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):response_json = response.json()self.assertLessEqual({"affected": 4, "total": 10}.items(), response_json.items())+ @snapshot_clickhouse_queries+ def test_persons_seen_so_far_ignores_team_v2_argmax_modifier(self):+ team = Team.objects.create(organization=self.organization, modifiers={"personsArgMaxVersion": "v2"})+ for i in range(3):+ _create_person(team_id=team.pk, distinct_ids=[f"seen_person_{i}"], properties={"group": f"{i}"})++ with self.capture_select_queries() as queries:+ assert team.persons_seen_so_far == 3++ assert queries+ for query in queries:+ # A truncated start of the v2 dedup semi-join, on purpose. The expression continues+ # with a subquery, so a balanced paren would build a string that never occurs and+ # the assertion would always pass.+ assert "in(tuple(person.id, person.version)" not in query++ # The filtered path builds one database and shares it between its two counts.+ # The denominator must keep the pinned v1 shape even then.+ with patch.object(Database, "create_for", wraps=Database.create_for) as create_for_spy:+ with self.capture_select_queries() as queries:+ result = get_user_blast_radius(+ team,+ {"properties": [{"key": "group", "type": "person", "value": ["0"], "operator": "exact"}]},+ )++ assert (result.affected, result.total) == (1, 3)+ assert create_for_spy.call_count == 1+ denominator_queries = [query for query in queries if "count(DISTINCT" not in query]+ assert denominator_queries+ for query in denominator_queries:+ assert "in(tuple(person.id, person.version)" not in query+@parameterized.expand([(diff --git a/products/feature_flags/backend/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.pyindex c1471ee6e822..b317e7dcd954 100644--- a/products/feature_flags/backend/user_blast_radius.py+++ b/products/feature_flags/backend/user_blast_radius.py@@ -143,6 +143,8 @@ def get_user_blast_radius_persons(def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:"""Calculate blast radius for person-based feature flags using HogQL."""+ from posthog.hogql.context import HogQLContext+ from posthog.hogql.database.database import Databasefrom posthog.hogql.query import execute_hogql_queryproperties = filter.property_groups.flat@@ -157,13 +159,18 @@ def _get_person_blast_radius(team: Team, filter: Filter) -> BlastRadiusResult:# Execute the querytag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY)+ # Build the team's HogQL database once and share it between the two counts below.+ # 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)response = execute_hogql_query(query=select_query,team=team,+ context=HogQLContext(team_id=team.pk, database=database),)total_count = response.results[0][0] if response.results else 0- total_users = team.persons_seen_so_far+ total_users = team.count_persons_seen_so_far(database=database)blast_radius = min(total_count, total_users)return BlastRadiusResult(affected=blast_radius, total=total_users)