Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(filters): delete the legacy entity class and filters package (#127983)

Thomas Obermüller8da9a9e4a93b
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index d77b98e120e6..2e7181ab8c7b 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -89,7 +89,6 @@ from posthog.models.activity_logging.activity_page import (
parse_activity_page_params,
)
from posthog.models.async_deletion import AsyncDeletion, DeletionType
-from posthog.models.filters.utils import earliest_timestamp_func
from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENT, FLAG_EVALUATIONS_TTL_DAYS
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
from posthog.models.property.parse import expand_cohort_properties, parse_property_group_data
@@ -1294,7 +1293,6 @@ def _completed_calculations_newest_first(cohort: Any) -> QuerySet[CohortCalculat
class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
- earliest_timestamp_func = earliest_timestamp_func
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
_create_static_person_ids = serializers.ListField(
required=False,
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 1437b4945fcc..bd22668aec2a 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -1,7 +1,7 @@
import os
import re
import copy
-from typing import TYPE_CHECKING, Any, get_args
+from typing import TYPE_CHECKING, Any, Literal, get_args
from uuid import UUID
from django.core.exceptions import ImproperlyConfigured
@@ -25,7 +25,6 @@ from rest_framework.exceptions import PermissionDenied
from rest_framework_dataclasses.fields import EnumField as DataclassEnumField
from posthog.enums import LabeledEnumType
-from posthog.models.entity import MathType
from posthog.models.property import OperatorType, PropertyType
from posthog.models.property.property import SemverOperator
from posthog.permissions import APIScopePermission
@@ -744,6 +743,35 @@ class PersonPropertiesSerializer(serializers.Serializer):
properties = PropertySerializer(required=False, many=True, help_text="Filter Persons by person properties.")
+MathType = Literal[
+ "total",
+ "dau",
+ "weekly_active",
+ "monthly_active",
+ "unique_group",
+ "unique_session",
+ "hogql",
+ # Equivalent to *PROPERTY_MATH_FUNCTIONS.keys(),
+ "sum",
+ "min",
+ "max",
+ "avg",
+ "median",
+ "p75",
+ "p90",
+ "p95",
+ "p99",
+ # Equivalent to *COUNT_PER_ACTOR_MATH_FUNCTIONS.keys()
+ "min_count_per_actor",
+ "max_count_per_actor",
+ "avg_count_per_actor",
+ "median_count_per_actor",
+ "p75_count_per_actor",
+ "p90_count_per_actor",
+ "p95_count_per_actor",
+ "p99_count_per_actor",
+]
+
math_help_text = """How to aggregate results, shown as \"counted by\" in the interface.
- `total` (default): no aggregation, count by events
- `dau`: count by unique users. Despite the name, if you select the `interval` to be weekly or monthly, this will show weekly or monthly active users respectively
diff --git a/posthog/api/team/team_config.py b/posthog/api/team/team_config.py
index 757bc8eeae60..c598a8fe0cc6 100644
--- a/posthog/api/team/team_config.py
+++ b/posthog/api/team/team_config.py
@@ -7,7 +7,7 @@ from rest_framework import serializers
from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models import Team, TeamRevenueAnalyticsConfig
-from posthog.models.filters.utils import validate_group_type_index
+from posthog.models.property import validate_group_type_index
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
from products.customer_analytics.backend.facade.account_property_pins import (
diff --git a/posthog/constants.py b/posthog/constants.py
index e3fe4ab13bdd..671a3f644c8e 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -231,6 +231,7 @@ class BreakdownAttributionType(StrEnum):
MAX_SLUG_LENGTH = 48
GROUP_TYPES_LIMIT = 5
+GroupTypeIndex = Literal[0, 1, 2, 3, 4]
class EventDefinitionType(StrEnum):
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index a043052fcc09..ab48f579aac8 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -17,7 +17,6 @@ from .data_deletion_request import DataDeletionRequest
from .data_color_theme import DataColorTheme
from .element import Element
from .element_group import ElementGroup
-from .entity import Entity
from .events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig
from .event.event import Event
from .event_buffer import EventBuffer
@@ -106,7 +105,6 @@ __all__ = [
"DeletionType",
"Element",
"ElementGroup",
- "Entity",
"Event",
"EventBuffer",
"EventDefinition",
diff --git a/posthog/models/entity/__init__.py b/posthog/models/entity/__init__.py
deleted file mode 100644
index 1aaf2fc47536..000000000000
--- a/posthog/models/entity/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .entity import Entity, MathType
-
-__all__ = ["Entity", "MathType"]
diff --git a/posthog/models/entity/entity.py b/posthog/models/entity/entity.py
deleted file mode 100644
index 21c8ad856cdf..000000000000
--- a/posthog/models/entity/entity.py
+++ /dev/null
@@ -1,226 +0,0 @@
-import json
-from collections import Counter
-from typing import TYPE_CHECKING, Any, Literal, Optional
-
-from django.conf import settings
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import (
- ACTIONS,
- DATA_WAREHOUSE_ENTITIES,
- EVENTS,
- TREND_FILTER_TYPE_ACTIONS,
- TREND_FILTER_TYPE_DATA_WAREHOUSE,
- TREND_FILTER_TYPE_EVENTS,
-)
-from posthog.models.filters.mixins.property import PropertyMixin
-from posthog.models.filters.utils import validate_group_type_index
-from posthog.models.property import GroupTypeIndex
-from posthog.models.utils import sane_repr
-
-from products.actions.backend.models.action import Action
-
-if TYPE_CHECKING:
- from posthog.schema import RevenueCurrencyPropertyConfig
-
-MathType = Literal[
- "total",
- "dau",
- "weekly_active",
- "monthly_active",
- "unique_group",
- "unique_session",
- "hogql",
- # Equivalent to *PROPERTY_MATH_FUNCTIONS.keys(),
- "sum",
- "min",
- "max",
- "avg",
- "median",
- "p75",
- "p90",
- "p95",
- "p99",
- # Equivalent to *COUNT_PER_ACTOR_MATH_FUNCTIONS.keys()
- "min_count_per_actor",
- "max_count_per_actor",
- "avg_count_per_actor",
- "median_count_per_actor",
- "p75_count_per_actor",
- "p90_count_per_actor",
- "p95_count_per_actor",
- "p99_count_per_actor",
-]
-
-
-class Entity(PropertyMixin):
- """
- Entities represent either Action or Event objects, nested in Filter objects.
- This object isn't a table in the database. It gets stored against the specific models itself as JSON.
- This class just allows for stronger typing of this object.
- """
-
- id: Optional[int | str]
- type: Literal["events", "actions", "data_warehouse"]
- order: Optional[int]
- name: Optional[str]
- custom_name: Optional[str]
- math: Optional[MathType]
- math_property: Optional[str]
- math_property_revenue_currency: Optional["RevenueCurrencyPropertyConfig"]
- math_hogql: Optional[str]
- math_group_type_index: Optional[GroupTypeIndex]
- # Index is not set at all by default (meaning: access = AttributeError) - it's populated in parse_entities
- # Used for identifying entities within a single query during query building,
- # which generally uses Entity objects processed by parse_entities
- # The clean room way to do this would be passing the index _alongside_ the object, but OOP abuse is much less work
- index: int
-
- # data warehouse fields
- id_field: Optional[str]
- timestamp_field: Optional[str]
- distinct_id_field: Optional[str]
- table_name: Optional[str]
-
- def __init__(self, data: dict[str, Any]) -> None:
- self.id = data.get("id")
- if data.get("type") not in [
- TREND_FILTER_TYPE_ACTIONS,
- TREND_FILTER_TYPE_EVENTS,
- TREND_FILTER_TYPE_DATA_WAREHOUSE,
- ]:
- raise ValueError(
- "Type needs to be either TREND_FILTER_TYPE_ACTIONS or TREND_FILTER_TYPE_EVENTS OR TREND_FILTER_TYPE_DATA_WAREHOUSE"
- )
- self.type = data["type"]
- order_provided = data.get("order")
- if order_provided is not None:
- order_provided = int(order_provided)
- self.order = order_provided
- self.name = data.get("name")
- custom_name = data.get("custom_name")
- if custom_name is not None:
- custom_name = str(custom_name).strip() or None
- self.custom_name = custom_name
- self.math = data.get("math")
- self.math_property = data.get("math_property")
- self.math_property_revenue_currency = data.get("math_property_revenue_currency")
- self.math_hogql = data.get("math_hogql")
- self.math_group_type_index = validate_group_type_index(
- "math_group_type_index", data.get("math_group_type_index")
- )
- self.id_field = data.get("id_field")
- self.timestamp_field = data.get("timestamp_field")
- self.distinct_id_field = data.get("distinct_id_field")
- self.table_name = data.get("table_name")
-
- self._action: Optional[Action] = None
- self._data = data # push data to instance object so mixins are handled properly
-
- if self.type == TREND_FILTER_TYPE_EVENTS and not self.name:
- self.name = "All events" if self.id is None else str(self.id)
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "id": self.id,
- "type": self.type,
- "order": self.order,
- "name": self.name,
- "custom_name": self.custom_name,
- "math": self.math,
- "math_property": self.math_property,
- "math_property_revenue_currency": dict(self.math_property_revenue_currency)
- if self.math_property_revenue_currency
- else None,
- "math_hogql": self.math_hogql,
- "math_group_type_index": self.math_group_type_index,
- "properties": self.property_groups.to_dict(),
- "id_field": self.id_field,
- "timestamp_field": self.timestamp_field,
- "distinct_id_field": self.distinct_id_field,
- "table_name": self.table_name,
- }
-
- def equals(self, other) -> bool:
- """Checks if two entities are semantically equal."""
- # Not using __eq__ since that affects hashability
-
- if self.id != other.id:
- return False
-
- if self.type != other.type:
- return False
-
- # TODO: Check operators as well, not just the properties.
- # Effectively check within each property group, that they're the same.
- self_properties = sorted(str(prop) for prop in self.property_groups.flat)
- other_properties = sorted(str(prop) for prop in other.property_groups.flat)
- if self_properties != other_properties:
- return False
-
- return True
-
- def is_superset(self, other) -> bool:
- """Checks if this entity is a superset version of other. The ids match and the properties of (this) is a subset of the properties of (other)"""
-
- self_properties = Counter([str(prop) for prop in self.property_groups.flat])
- other_properties = Counter([str(prop) for prop in other.property_groups.flat])
-
- return self.id == other.id and len(self_properties - other_properties) == 0
-
- def get_action(self, team_id: int) -> Action:
- if self.type != TREND_FILTER_TYPE_ACTIONS:
- raise ValueError(
- f"Action can only be fetched for entities of type {TREND_FILTER_TYPE_ACTIONS}, not {self.type}!"
- )
-
- if self._action and not settings.TEST:
- return self._action
-
- if self.id is None:
- raise ValidationError("Action ID cannot be None!")
-
- try:
- self._action = Action.objects.get(id=self.id, team_id=team_id)
- return self._action
- except:
- raise ValidationError(f"Action ID {self.id} does not exist!")
-
- __repr__ = sane_repr(
- "id",
- "type",
- "order",
- "name",
- "custom_name",
- "math",
- "math_property",
- "math_property_revenue_currency",
- "math_hogql",
- "properties",
- "id_field",
- "timestamp_field",
- "distinct_id_field",
- "table_name",
- )
-
-
-def parse_entities(data: dict) -> list["Entity"]:
- """Build the ordered entity list from an insight-style filter dict."""
- processed_entities: list[Entity] = []
- for key, entity_type in (
- (ACTIONS, TREND_FILTER_TYPE_ACTIONS),
- (EVENTS, TREND_FILTER_TYPE_EVENTS),
- (DATA_WAREHOUSE_ENTITIES, TREND_FILTER_TYPE_DATA_WAREHOUSE),
- ):
- raw = data.get(key)
- if not raw:
- continue
- if isinstance(raw, str):
- raw = json.loads(raw)
- processed_entities.extend([Entity({**entity, "type": entity_type}) for entity in raw])
-
- processed_entities.sort(key=lambda entity: entity.order if entity.order else -1)
- for index, entity in enumerate(processed_entities):
- entity.index = index
- return processed_entities
diff --git a/posthog/models/filters/__init__.py b/posthog/models/filters/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/models/filters/mixins/__init__.py b/posthog/models/filters/mixins/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/models/filters/mixins/base.py b/posthog/models/filters/mixins/base.py
deleted file mode 100644
index 86e8e12be2b8..000000000000
--- a/posthog/models/filters/mixins/base.py
+++ /dev/null
@@ -1,2 +0,0 @@
-class BaseParamMixin:
- _data: dict
diff --git a/posthog/models/filters/mixins/property.py b/posthog/models/filters/mixins/property.py
deleted file mode 100644
index e77dcc070a76..000000000000
--- a/posthog/models/filters/mixins/property.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from functools import cached_property
-
-from posthog.constants import PROPERTIES
-from posthog.models.filters.mixins.base import BaseParamMixin
-from posthog.models.property import PropertyGroup
-from posthog.models.property.parse import parse_property_group_data
-
-
-class PropertyMixin(BaseParamMixin):
- @cached_property
- def property_groups(self) -> PropertyGroup:
- return self._parse_data(key=PROPERTIES)
-
- def _parse_data(self, key: str) -> PropertyGroup:
- return parse_property_group_data(self._data.get(key))
diff --git a/posthog/models/filters/mixins/test/__init__.py b/posthog/models/filters/mixins/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/models/filters/utils.py b/posthog/models/filters/utils.py
deleted file mode 100644
index 1fb384f5ffe5..000000000000
--- a/posthog/models/filters/utils.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from typing import Any, Literal, cast
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import GROUP_TYPES_LIMIT
-
-GroupTypeIndex = Literal[0, 1, 2, 3, 4]
-
-
-def earliest_timestamp_func(team_id: int):
- # Imported here to break a circular import: hogql_queries pulls in filter machinery.
- from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered # noqa: PLC0415
- from posthog.models.team import Team # noqa: PLC0415
-
- return get_earliest_timestamp_unfiltered(Team.objects.get(pk=team_id))
-
-
-def validate_group_type_index(param_name: str, value: Any, required=False) -> GroupTypeIndex | None:
- error = ValidationError(
- f"{param_name} is required to be at least 0 and less than {GROUP_TYPES_LIMIT}",
- code="invalid",
- )
-
- if required and value is None:
- raise error
-
- if value is not None:
- try:
- value = int(value)
- except:
- raise error
- if not (0 <= value < GROUP_TYPES_LIMIT):
- raise error
-
- return cast(GroupTypeIndex | None, value)
diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.py
index 4ff02fd8678a..e9094e4bc2c4 100644
--- a/posthog/models/group/test_util.py
+++ b/posthog/models/group/test_util.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
-from posthog.models.filters.utils import GroupTypeIndex
+from posthog.constants import GroupTypeIndex
from posthog.models.group.util import (
create_group,
get_group_by_key,
diff --git a/posthog/models/group/util.py b/posthog/models/group/util.py
index f889aa19318c..e3d22615be91 100644
--- a/posthog/models/group/util.py
+++ b/posthog/models/group/util.py
@@ -10,9 +10,9 @@ from django.utils.timezone import now
import structlog
from dateutil.parser import isoparse
+from posthog.constants import GroupTypeIndex
from posthog.kafka_client.client import ClickhouseProducer
from posthog.kafka_client.topics import KAFKA_GROUPS
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group.group import Group
from posthog.models.group.sql import INSERT_GROUP_SQL
diff --git a/posthog/models/property/property.py b/posthog/models/property/property.py
index d9a8ca5e8579..58fb722421a7 100644
--- a/posthog/models/property/property.py
+++ b/posthog/models/property/property.py
@@ -6,8 +6,9 @@ from typing import Any, Literal, Optional, Union, cast
from django.db import models
-from posthog.constants import PropertyOperatorType
-from posthog.models.filters.utils import GroupTypeIndex, validate_group_type_index
+from rest_framework.exceptions import ValidationError
+
+from posthog.constants import GROUP_TYPES_LIMIT, GroupTypeIndex, PropertyOperatorType
# Relocated to the Django-free posthog.property_columns module so the HogQL engine can use them
# without booting Django; re-exported here for existing callers.
@@ -253,6 +254,26 @@ VALIDATE_BEHAVIORAL_PROP_TYPES = {
}
+def validate_group_type_index(param_name: str, value: Any, required=False) -> GroupTypeIndex | None:
+ error = ValidationError(
+ f"{param_name} is required to be at least 0 and less than {GROUP_TYPES_LIMIT}",
+ code="invalid",
+ )
+
+ if required and value is None:
+ raise error
+
+ if value is not None:
+ try:
+ value = int(value)
+ except:
+ raise error
+ if not (0 <= value < GROUP_TYPES_LIMIT):
+ raise error
+
+ return cast(GroupTypeIndex | None, value)
+
+
class PropertyValidationError(ValueError):
"""Every failure to construct a valid Property from prop_params raises this (a
ValueError subclass, so existing `except ValueError` callers are unaffected) — one
diff --git a/posthog/models/filters/mixins/test/test_property.py b/posthog/models/property/test/test_property_group_parsing.py
similarity index 68%
rename from posthog/models/filters/mixins/test/test_property.py
rename to posthog/models/property/test/test_property_group_parsing.py
index e2df10ae631e..8e9821be8e1f 100644
--- a/posthog/models/filters/mixins/test/test_property.py
+++ b/posthog/models/property/test/test_property_group_parsing.py
@@ -8,141 +8,123 @@ from unittest.mock import patch
from posthoganalytics.contexts import get_capture_exception_code_variables_context
from rest_framework.exceptions import ValidationError
-from posthog.models.entity import Entity
from posthog.models.property import Property, PropertyGroup, PropertyValidationError
-
-
-def _entity(data: dict[str, Any]) -> Entity:
- return Entity({"id": "$pageview", "type": "events", **data})
+from posthog.models.property.parse import parse_property_group_data
@pytest.mark.parametrize("encode", [lambda data: data, json.dumps], ids=["dict", "json"])
def test_property_group_multi_level_parsing(encode: Callable[[dict[str, Any]], Any]):
- entity = _entity(
- {
- "properties": encode(
- {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- ],
- },
- {"type": "OR", "values": [{"key": "attr", "value": "val_2"}]},
- ],
- }
- )
- }
+ property_groups = parse_property_group_data(
+ encode(
+ {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ ],
+ },
+ {"type": "OR", "values": [{"key": "attr", "value": "val_2"}]},
+ ],
+ }
+ )
)
- assert entity.property_groups.type == "AND"
- assert isinstance(entity.property_groups.values[0], PropertyGroup)
- assert entity.property_groups.values[0].type == "AND"
- assert isinstance(entity.property_groups.values[0].values[0], Property)
- assert entity.property_groups.values[0].values[0].key == "attr"
- assert entity.property_groups.values[0].values[0].value == "val_1"
- assert isinstance(entity.property_groups.values[0].values[1], Property)
- assert entity.property_groups.values[0].values[1].key == "attr_2"
- assert entity.property_groups.values[0].values[1].value == "val_2"
+ assert property_groups.type == "AND"
+ assert isinstance(property_groups.values[0], PropertyGroup)
+ assert property_groups.values[0].type == "AND"
+ assert isinstance(property_groups.values[0].values[0], Property)
+ assert property_groups.values[0].values[0].key == "attr"
+ assert property_groups.values[0].values[0].value == "val_1"
+ assert isinstance(property_groups.values[0].values[1], Property)
+ assert property_groups.values[0].values[1].key == "attr_2"
+ assert property_groups.values[0].values[1].value == "val_2"
- assert isinstance(entity.property_groups.values[1], PropertyGroup)
- assert entity.property_groups.values[1].type == "OR"
- assert isinstance(entity.property_groups.values[1].values[0], Property)
- assert entity.property_groups.values[1].values[0].key == "attr"
- assert entity.property_groups.values[1].values[0].value == "val_2"
+ assert isinstance(property_groups.values[1], PropertyGroup)
+ assert property_groups.values[1].type == "OR"
+ assert isinstance(property_groups.values[1].values[0], Property)
+ assert property_groups.values[1].values[0].key == "attr"
+ assert property_groups.values[1].values[0].value == "val_2"
@pytest.mark.parametrize("encode", [lambda data: data, json.dumps], ids=["dict", "json"])
def test_property_group_simple_parsing(encode: Callable[[dict[str, Any]], Any]):
- entity = _entity(
- {
- "properties": encode(
- {
- "type": "AND",
- "values": [
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- ],
- }
- )
- }
+ property_groups = parse_property_group_data(
+ encode(
+ {
+ "type": "AND",
+ "values": [
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ ],
+ }
+ )
)
- assert entity.property_groups.type == "AND"
- assert isinstance(entity.property_groups.values[0], Property)
- assert entity.property_groups.values[0].key == "attr"
- assert entity.property_groups.values[0].value == "val_1"
- assert isinstance(entity.property_groups.values[1], Property)
- assert entity.property_groups.values[1].key == "attr_2"
- assert entity.property_groups.values[1].value == "val_2"
+ assert property_groups.type == "AND"
+ assert isinstance(property_groups.values[0], Property)
+ assert property_groups.values[0].key == "attr"
+ assert property_groups.values[0].value == "val_1"
+ assert isinstance(property_groups.values[1], Property)
+ assert property_groups.values[1].key == "attr_2"
+ assert property_groups.values[1].value == "val_2"
def test_property_group_empty_parsing():
- entity = _entity({"properties": {}})
+ property_groups = parse_property_group_data({})
- assert entity.property_groups.type == "AND"
- assert entity.property_groups.values == []
+ assert property_groups.type == "AND"
+ assert property_groups.values == []
def test_property_group_invalid_parsing():
- entity = _entity(
- {
- "properties": {
- "type": "XaND",
- "values": [
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- ],
- }
- }
- )
+ data = {
+ "type": "XaND",
+ "values": [
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ ],
+ }
with pytest.raises(ValidationError):
- entity.property_groups # noqa: B018
+ parse_property_group_data(data)
def test_property_group_includes_unhomogenous_groups():
- entity = _entity(
- {
- "properties": {
- "type": "AND",
- "values": [
- {"type": "or", "values": [{"key": "attr", "value": "val_1"}]},
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- {"type": "OR", "values": []},
- ],
- }
- }
- )
+ data = {
+ "type": "AND",
+ "values": [
+ {"type": "or", "values": [{"key": "attr", "value": "val_1"}]},
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ {"type": "OR", "values": []},
+ ],
+ }
with pytest.raises(ValidationError):
- entity.property_groups # noqa: B018
+ parse_property_group_data(data)
def test_property_multi_level_to_dict():
- entity = _entity(
+ property_groups = parse_property_group_data(
{
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- ],
- },
- {"type": "OR", "values": [{"key": "attr", "value": "val_2"}]},
- ],
- }
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ ],
+ },
+ {"type": "OR", "values": [{"key": "attr", "value": "val_2"}]},
+ ],
}
)
- assert entity.property_groups.to_dict() == {
+ assert property_groups.to_dict() == {
"type": "AND",
"values": [
{
@@ -161,19 +143,17 @@ def test_property_multi_level_to_dict():
def test_property_group_simple_to_dict():
- entity = _entity(
+ property_groups = parse_property_group_data(
{
- "properties": {
- "type": "AND",
- "values": [
- {"key": "attr", "value": "val_1"},
- {"key": "attr_2", "value": "val_2"},
- ],
- }
+ "type": "AND",
+ "values": [
+ {"key": "attr", "value": "val_1"},
+ {"key": "attr_2", "value": "val_2"},
+ ],
}
)
- assert entity.property_groups.to_dict() == {
+ assert property_groups.to_dict() == {
"type": "AND",
"values": [
{"key": "attr", "value": "val_1", "type": "event"},
@@ -247,17 +227,13 @@ def test_property_group_parsing_reports_and_skips_unparsable_property(
# with no visibility at all. It must still be dropped (callers across the codebase
# rely on best-effort parsing of legacy/malformed data), but the failure must now be
# reported — regardless of which internal check inside Property.__init__ rejected it.
- entity = _entity(
- {
- "properties": {
- "type": "AND",
- "values": [{"key": "attr", "value": "val_1"}, invalid_property],
- }
- }
- )
+ data = {
+ "type": "AND",
+ "values": [{"key": "attr", "value": "val_1"}, invalid_property],
+ }
with patch("posthog.models.property.parse.capture_exception") as mock_capture_exception:
- properties = entity.property_groups.values
+ properties = parse_property_group_data(data).values
assert len(properties) == 1
assert isinstance(properties[0], Property)
@@ -278,10 +254,10 @@ def test_property_group_parsing_reports_non_mapping_property():
# `Property(**prop_params)` unpacking with TypeError, before __init__ even runs. The
# grouped-properties path can't reach this: a non-mapping element trips the "cannot
# contain both PropertyGroup and Property objects" check first.
- entity = _entity({"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})
+ data = [{"key": "attr", "value": "val_1"}, "not-a-mapping"]
with patch("posthog.models.property.parse.capture_exception") as mock_capture_exception:
- properties = entity.property_groups.values
+ properties = parse_property_group_data(data).values
assert len(properties) == 1
assert isinstance(properties[0], Property)
@@ -307,12 +283,12 @@ def test_property_group_parsing_disables_code_variable_capture_for_reported_exce
def fake_capture_exception(error, additional_properties=None):
observed_context_values.append(get_capture_exception_code_variables_context())
- entity = _entity({"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})
+ data = [{"key": "attr", "value": "val_1"}, "not-a-mapping"]
with patch(
"posthog.models.property.parse.capture_exception", side_effect=fake_capture_exception
) as mock_capture_exception:
- _ = entity.property_groups.values
+ _ = parse_property_group_data(data).values
mock_capture_exception.assert_called_once()
assert observed_context_values == [False]
diff --git a/posthog/models/filters/mixins/test/test_groups.py b/posthog/models/property/test/test_validate_group_type_index.py
similarity index 93%
rename from posthog/models/filters/mixins/test/test_groups.py
rename to posthog/models/property/test/test_validate_group_type_index.py
index f55efe4d9c5e..b46173d9c5a0 100644
--- a/posthog/models/filters/mixins/test/test_groups.py
+++ b/posthog/models/property/test/test_validate_group_type_index.py
@@ -2,7 +2,7 @@ import pytest
from rest_framework.exceptions import ValidationError
-from posthog.models.filters.utils import validate_group_type_index
+from posthog.models.property import validate_group_type_index
def test_validate_group_type_index():
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index ec5956d22d0d..240154d91e91 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -20,9 +20,9 @@ import pydantic
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_context
from posthog.cloud_utils import is_cloud
+from posthog.constants import GroupTypeIndex
from posthog.helpers.session_recording_playlist_templates import DEFAULT_PLAYLISTS
from posthog.migration_helpers import deprecate_field
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.project_secret_api_key import (
diff --git a/posthog/models/test/test_entity_model.py b/posthog/models/test/test_entity_model.py
deleted file mode 100644
index a352532aaf39..000000000000
--- a/posthog/models/test/test_entity_model.py
+++ /dev/null
@@ -1,263 +0,0 @@
-from django.test import SimpleTestCase
-
-from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_EVENTS
-from posthog.models.entity import Entity
-
-
-class TestEntity(SimpleTestCase):
- def test_can_init_without_id(self):
- entity = Entity({"type": TREND_FILTER_TYPE_EVENTS}) # This is an "All events" entity
-
- self.assertEqual(entity.id, None)
-
- def test_inclusion(self):
- entity1 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "email", "value": "[email protected]", "type": "person"},
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- },
- ],
- }
- )
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- }
- ],
- }
- )
-
- self.assertTrue(entity2.is_superset(entity1))
- self.assertFalse(entity1.is_superset(entity2))
-
- def test_inclusion_unordered(self):
- entity1 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "browser", "value": "chrome", "type": "person"},
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- },
- {"key": "email", "value": "[email protected]", "type": "person"},
- ],
- }
- )
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- }
- ],
- }
- )
-
- self.assertTrue(entity2.is_superset(entity1))
- self.assertFalse(entity1.is_superset(entity2))
-
- def test_equality_with_ids(self):
- entity1 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_ACTIONS})
- entity2 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_ACTIONS})
-
- self.assertTrue(entity1.equals(entity2))
-
- entity2 = Entity({"id": "e2", "type": TREND_FILTER_TYPE_ACTIONS})
-
- self.assertFalse(entity1.equals(entity2))
-
- def test_equality_with_type(self):
- entity1 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_EVENTS})
- entity2 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_EVENTS})
-
- self.assertTrue(entity1.equals(entity2))
-
- entity1 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_EVENTS})
- entity2 = Entity({"id": "e1", "type": TREND_FILTER_TYPE_ACTIONS})
-
- self.assertFalse(entity1.equals(entity2))
-
- def test_equality_with_simple_properties(self):
- entity1 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "email", "value": "[email protected]", "type": "person"},
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- },
- ],
- }
- )
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {
- "key": "current_url",
- "value": "[email protected]",
- "type": "element",
- },
- {"key": "email", "value": "[email protected]", "type": "person"},
- ],
- }
- )
-
- self.assertTrue(entity1.equals(entity2))
-
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {
- "key": "current$url",
- "value": "[email protected]",
- "type": "element",
- },
- {"key": "email", "value": "[email protected]", "type": "person"},
- ],
- }
- )
-
- self.assertFalse(entity1.equals(entity2))
-
- def test_equality_with_complex_operator_properties(self):
- entity1 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "count", "operator": "lt", "value": 12, "type": "element"},
- {
- "key": "email",
- "operator": "in",
- "value": ["a, b"],
- "type": "person",
- },
- {
- "key": "selector",
- "value": [".btn"],
- "operator": "exact",
- "type": "element",
- },
- {"key": "test_prop", "value": 1.2, "operator": "gt"},
- ],
- }
- )
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "test_prop", "value": 1.20, "operator": "gt"},
- {"key": "count", "operator": "lt", "value": 12, "type": "element"},
- {
- "key": "selector",
- "value": [".btn"],
- "operator": "exact",
- "type": "element",
- },
- {
- "key": "email",
- "operator": "in",
- "value": ["a, b"],
- "type": "person",
- },
- ],
- }
- )
-
- self.assertTrue(entity1.equals(entity2))
-
- # playing with decimals
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "test_prop", "value": 1.200, "operator": "gt"},
- {"key": "count", "operator": "lt", "value": 12, "type": "element"},
- {
- "key": "selector",
- "value": [".btn"],
- "operator": "exact",
- "type": "element",
- },
- {
- "key": "email",
- "operator": "in",
- "value": ["a, b"],
- "type": "person",
- },
- ],
- }
- )
-
- self.assertTrue(entity1.equals(entity2))
-
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [
- {"key": "test_prop", "value": 1.2001, "operator": "gt"},
- {"key": "count", "operator": "lt", "value": 12, "type": "element"},
- {
- "key": "selector",
- "value": [".btn"],
- "operator": "exact",
- "type": "element",
- },
- {
- "key": "email",
- "operator": "in",
- "value": ["a, b"],
- "type": "person",
- },
- ],
- }
- )
-
- self.assertFalse(entity1.equals(entity2))
-
- def test_equality_with_old_style_and_new_style_properties(self):
- entity1 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": {"key": "value"},
- }
- )
- entity2 = Entity(
- {
- "id": "e1",
- "type": TREND_FILTER_TYPE_EVENTS,
- "properties": [{"key": "key", "value": "value"}],
- }
- )
-
- self.assertTrue(entity1.equals(entity2))
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index e86c17d48ce8..aadc8b9fab6e 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -47,7 +47,7 @@ from posthog.session_recordings.queries.utils import (
from posthog.types import AnyPropertyFilter
from posthog.utils import get_instance_region
-ENTITY_TYPES_ACCEPTED_BY_LEGACY_ENTITY = frozenset(
+ENTITY_TYPES_WITH_NODES = frozenset(
{TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS}
)
@@ -953,17 +953,15 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
@staticmethod
def _entity_node(raw_entity: dict[str, Any], default_type: str) -> EventsNode | ActionsNode | DataWarehouseNode:
- # RecordingsQuery accepts untyped entity dicts, and Entity rejects any type it does not
- # know, so fall back to the type the source list implies.
+ # RecordingsQuery accepts untyped entity dicts, and _node_from_entity rejects any type it
+ # does not know, so fall back to the type the source list implies.
entity = (
- raw_entity
- if raw_entity.get("type") in ENTITY_TYPES_ACCEPTED_BY_LEGACY_ENTITY
- else {**raw_entity, "type": default_type}
+ raw_entity if raw_entity.get("type") in ENTITY_TYPES_WITH_NODES else {**raw_entity, "type": default_type}
)
try:
return _node_from_entity(entity)
except ValueError as e:
- # Entity and the node models raise plain ValueErrors for a dict they can't build from
+ # _node_from_entity and the node models raise plain ValueErrors for a dict they can't build from
# (pydantic's ValidationError subclasses it), and those escape as a 500. The dict is
# caller input, so report it as a bad request. DRF's ValidationError is not a
# ValueError, so a field that already validates itself still reports its own message.
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index 9a8927175204..45982b2bbd4b 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -24,9 +24,9 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.property import action_to_expr
-from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE
+from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS
from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_entity_properties
-from posthog.models import Entity, Team
+from posthog.models import Team
from posthog.types import AnyPropertyFilter
from products.actions.backend.models.action import Action
@@ -207,27 +207,35 @@ def poe_is_active(team: Team) -> bool:
def _node_from_entity(raw_entity: dict[str, Any]) -> EventsNode | ActionsNode | DataWarehouseNode:
- entity = Entity(raw_entity)
+ entity_id = raw_entity.get("id")
+ entity_type = raw_entity.get("type")
+ custom_name = raw_entity.get("custom_name")
+ if custom_name is not None:
+ custom_name = str(custom_name).strip() or None
# Replay selects sessions and never aggregates, so the entity's math fields have no effect on
# the node and are left out.
shared: dict[str, Any] = {
- "name": entity.name,
- "custom_name": entity.custom_name,
+ "name": raw_entity.get("name"),
+ "custom_name": custom_name,
"properties": clean_entity_properties(raw_entity.get("properties")),
}
- if entity.type == TREND_FILTER_TYPE_ACTIONS:
- return ActionsNode(id=entity.id, **shared)
- if entity.type == TREND_FILTER_TYPE_DATA_WAREHOUSE:
+ if entity_type == TREND_FILTER_TYPE_ACTIONS:
+ return ActionsNode(id=entity_id, **shared)
+ if entity_type == TREND_FILTER_TYPE_DATA_WAREHOUSE:
return DataWarehouseNode(
- id=entity.id,
- id_field=entity.id_field,
- distinct_id_field=entity.distinct_id_field,
- timestamp_field=entity.timestamp_field,
- table_name=entity.table_name,
+ id=entity_id,
+ id_field=raw_entity.get("id_field"),
+ distinct_id_field=raw_entity.get("distinct_id_field"),
+ timestamp_field=raw_entity.get("timestamp_field"),
+ table_name=raw_entity.get("table_name"),
**shared,
)
- return EventsNode(event=entity.id, **shared)
+ if entity_type != TREND_FILTER_TYPE_EVENTS:
+ raise ValueError(f"Unsupported entity type: {entity_type}")
+ # _entity_to_expr matches events on the node name, so an unnamed event entity takes its event as the name.
+ shared["name"] = shared["name"] or ("All events" if entity_id is None else str(entity_id))
+ return EventsNode(event=entity_id, **shared)
def _entity_to_expr(entity: EventsNode | ActionsNode, team: Team) -> ast.Expr:
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 9f6f83b17d7a..965749d6244c 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -40,7 +40,15 @@ from posthog.api.cohort import (
)
from posthog.api.utils import ServiceRequest
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.constants import AvailableFeature
+from posthog.constants import (
+ ACTIONS,
+ DATA_WAREHOUSE_ENTITIES,
+ EVENTS,
+ TREND_FILTER_TYPE_ACTIONS,
+ TREND_FILTER_TYPE_DATA_WAREHOUSE,
+ TREND_FILTER_TYPE_EVENTS,
+ AvailableFeature,
+)
from posthog.event_usage import EventSource, report_user_action
from posthog.exceptions import (
ClickHouseEstimatedQueryExecutionTimeTooLong,
@@ -50,8 +58,8 @@ from posthog.exceptions import (
from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
from posthog.models.activity_logging.model_activity import is_impersonated_session
from posthog.models.activity_logging.utils import get_changed_fields_local
-from posthog.models.entity.entity import Entity, parse_entities
from posthog.models.person.util import get_person_ids_and_uuids_by_uuids
+from posthog.models.property.parse import parse_property_group_data
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -369,6 +377,28 @@ def _apply_holdout(filters: dict, holdout: ExperimentHoldout | None) -> dict:
)
+def _first_legacy_filter_entity(filter_data: dict) -> dict[str, Any] | None:
+ """Returns the first action, event or data warehouse entry of a legacy insight filter, with its `type` set."""
+ entities: list[dict[str, Any]] = []
+ for key, entity_type in (
+ (ACTIONS, TREND_FILTER_TYPE_ACTIONS),
+ (EVENTS, TREND_FILTER_TYPE_EVENTS),
+ (DATA_WAREHOUSE_ENTITIES, TREND_FILTER_TYPE_DATA_WAREHOUSE),
+ ):
+ raw = filter_data.get(key)
+ if not raw:
+ continue
+ if isinstance(raw, str):
+ raw = json.loads(raw)
+ entities.extend({**entity, "type": entity_type} for entity in raw)
+ # An entry with order 0 or no order sorts first, the same as legacy insight filter parsing.
+ return min(
+ entities,
+ key=lambda entity: (int(entity["order"]) if entity.get("order") is not None else 0) or -1,
+ default=None,
+ )
+
+
def _tracked_health_finding(finding: ExperimentHealthFinding) -> str:
# pinned: `code:subcode:severity:reason`, as on the page's `experiment health checked`. Insights split each
# string on `:`, so every field is present, empty when the finding has none.
@@ -4261,9 +4291,7 @@ class ExperimentService:
raise ValidationError("Experiment already has an exposure cohort")
exposure_filter_data = (experiment.parameters or {}).get("custom_exposure_filter")
- exposure_entities: list[Entity] = []
- if exposure_filter_data:
- exposure_entities = parse_entities(exposure_filter_data)
+ entity = _first_legacy_filter_entity(exposure_filter_data) if exposure_filter_data else None
target_entities: Sequence[int | str]
target_entity_type = "events"
@@ -4276,20 +4304,19 @@ class ExperimentService:
}
]
- entity = exposure_entities[0] if exposure_entities else None
- if entity is not None and entity.id:
- if entity.type == "actions":
+ if entity is not None and entity.get("id"):
+ if entity["type"] == "actions":
target_entity_type = "actions"
try:
- target_entities = [int(entity.id)]
+ target_entities = [int(entity["id"])]
except ValueError:
raise ValidationError("Invalid action ID")
else:
- target_entities = exposure_event_names(str(entity.id))
+ target_entities = exposure_event_names(str(entity["id"]))
target_filters = [
prop.to_dict()
- for prop in entity.property_groups.flat
+ for prop in parse_property_group_data(entity.get("properties")).flat
if prop.type in ("event", "feature", "element", "hogql")
]
else:
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
index aa77acf3376d..ab23a65a997b 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
@@ -28,7 +28,7 @@ from posthog.schema import (
StepOrderValue,
)
-from posthog.models.filters.utils import GroupTypeIndex
+from posthog.constants import GroupTypeIndex
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py
index e21f886cdd6f..c4846e4e1a00 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from posthog.test.base import _create_event, _create_person
-from posthog.models.filters.utils import GroupTypeIndex
+from posthog.constants import GroupTypeIndex
from posthog.models.group.util import create_group
from posthog.models.team.team import Team
from posthog.test.persons import create_group_type_mapping
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 36f4c6b820d2..04691bf9935f 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -5426,6 +5426,36 @@ class TestExperimentService(APIBaseTest):
assert criterion["event_type"] == "events"
assert criterion["event_filters"] == [flag_filter]
+ @parameterized.expand(
+ [
+ # (name, legacy custom_exposure_filter, expected exposure event)
+ ("empty_actions_string", {"actions": "", "events": [{"id": "signed_up", "order": 0}]}, "signed_up"),
+ (
+ "string_and_int_zero_order",
+ {"events": [{"id": "first_event", "order": "0"}, {"id": "second_event", "order": 0}]},
+ "first_event",
+ ),
+ ]
+ )
+ def test_create_exposure_cohort_reads_legacy_custom_exposure_filter(
+ self, name: str, custom_exposure_filter: dict, expected_event: str
+ ) -> None:
+ flag_key = f"cohort-legacy-{name}"
+ self._create_flag(key=flag_key)
+ service = self._service()
+ experiment = service.create_experiment(
+ name=f"Legacy {name}",
+ feature_flag_key=flag_key,
+ start_date=timezone.now(),
+ parameters={"custom_exposure_filter": custom_exposure_filter},
+ )
+
+ cohort = service.create_exposure_cohort(experiment)
+
+ assert cohort.filters is not None
+ criteria = cohort.filters["properties"]["values"][0]["values"]
+ assert [criterion["key"] for criterion in criteria] == [expected_event]
+
def test_create_exposure_cohort_without_start_date_raises(self):
self._create_flag(key="cohort-no-start")
service = self._service()
diff --git a/products/groups/backend/logic/related_actors_query.py b/products/groups/backend/logic/related_actors_query.py
index c629a75667c0..e9d0c33cf03c 100644
--- a/products/groups/backend/logic/related_actors_query.py
+++ b/products/groups/backend/logic/related_actors_query.py
@@ -20,9 +20,8 @@ from posthog.hogql_queries.serialized_actors import (
get_serialized_people,
)
from posthog.models import Team
-from posthog.models.filters.utils import validate_group_type_index
from posthog.models.group_type_mapping import get_group_types_for_project
-from posthog.models.property import GroupTypeIndex
+from posthog.models.property import GroupTypeIndex, validate_group_type_index
from posthog.personhog_client.caller_tag import personhog_caller_tag
diff --git a/products/groups/backend/presentation/views.py b/products/groups/backend/presentation/views.py
index 774f3dfe004f..440f98d8d7dd 100644
--- a/products/groups/backend/presentation/views.py
+++ b/products/groups/backend/presentation/views.py
@@ -27,12 +27,12 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SerializedGroupActorSerializer, SerializedPersonActorSerializer
from posthog.api.utils import action
from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.constants import GroupTypeIndex
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.helpers.impersonation import is_impersonated
from posthog.models import GroupUsageMetric
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group import Group
from posthog.models.group.util import (
GroupAlreadyExistsError,
diff --git a/products/groups/backend/tests/test_clickhouse_groups.py b/products/groups/backend/tests/test_clickhouse_groups.py
index 40783dfa82ce..b8f5bfd85095 100644
--- a/products/groups/backend/tests/test_clickhouse_groups.py
+++ b/products/groups/backend/tests/test_clickhouse_groups.py
@@ -28,10 +28,9 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
-from posthog.constants import AvailableFeature
+from posthog.constants import AvailableFeature, GroupTypeIndex
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.models import GroupUsageMetric, PropertyDefinition
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group.group import Group
from posthog.models.group.util import ListGroupsResult, create_group, list_groups, raw_create_group_ch
from posthog.models.group_type_mapping import (
diff --git a/products/groups/backend/tests/test_related_actors_query.py b/products/groups/backend/tests/test_related_actors_query.py
index 84f04c936c4e..5e8fdc1f9601 100644
--- a/products/groups/backend/tests/test_related_actors_query.py
+++ b/products/groups/backend/tests/test_related_actors_query.py
@@ -18,9 +18,9 @@ from parameterized import parameterized
from posthog.schema import PersonsOnEventsMode
from posthog.clickhouse.client import sync_execute
+from posthog.constants import GroupTypeIndex
from posthog.models import Group
from posthog.models.event.util import create_event
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group.util import create_group
from posthog.test.persons import create_group_type_mapping
diff --git a/products/notebooks/evals/seeders.py b/products/notebooks/evals/seeders.py
index 0efa727e80fe..fdaa6da06d6b 100644
--- a/products/notebooks/evals/seeders.py
+++ b/products/notebooks/evals/seeders.py
@@ -18,9 +18,9 @@ from typing import Any
from django.utils import timezone
+from posthog.constants import GroupTypeIndex
from posthog.models import Team
from posthog.models.event.util import bulk_create_events
-from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.group.util import raw_create_group_ch
from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.persons_db import persons_db_connection
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
index 20c03789a9e6..d0dfed9422a4 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
@@ -1,7 +1,7 @@
import uuid
import dataclasses
from datetime import datetime
-from typing import Any, Optional, Union
+from typing import Any, Optional
from zoneinfo import ZoneInfo
import pytest
@@ -56,9 +56,8 @@ from posthog.schema import (
)
from posthog.clickhouse.client import sync_execute
-from posthog.constants import TREND_FILTER_TYPE_EVENTS
from posthog.hogql_queries.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL
-from posthog.models import Entity, Organization, Person
+from posthog.models import Organization, Person
from posthog.models.event.util import events_only_in_active_schema
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting, override_instance_config
@@ -76,23 +75,6 @@ from products.product_analytics.backend.hogql_queries.trends.test.test_trends_pe
from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import TrendsQueryRunner
-def breakdown_label(entity: Entity, value: Union[str, int]) -> dict[str, Optional[Union[str, int]]]:
- ret_dict: dict[str, Optional[Union[str, int]]] = {}
- if not value or not isinstance(value, str) or "cohort_" not in value:
- label = value if (value or isinstance(value, bool)) and value != "None" and value != "nan" else "Other"
- ret_dict["label"] = f"{entity.name} - {label}"
- ret_dict["breakdown_value"] = label
- else:
- if value == "cohort_all":
- ret_dict["label"] = f"{entity.name} - all users"
- ret_dict["breakdown_value"] = "all"
- else:
- cohort = Cohort.objects.get(pk=value.replace("cohort_", ""))
- ret_dict["label"] = f"{entity.name} - {cohort.name}"
- ret_dict["breakdown_value"] = cohort.pk
- return ret_dict
-
-
def _create_cohort(
*,
team: Team,
@@ -3399,33 +3381,6 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["labels"][23], "2-Jan 23:00")
self.assertEqual(response[0]["data"][23], 1.0)
- def test_breakdown_label(self):
- entity = Entity({"id": "$pageview", "name": "$pageview", "type": TREND_FILTER_TYPE_EVENTS})
- num_label = breakdown_label(entity, 1)
- self.assertEqual(num_label, {"label": "$pageview - 1", "breakdown_value": 1})
-
- string_label = breakdown_label(entity, "Chrome")
- self.assertEqual(string_label, {"label": "$pageview - Chrome", "breakdown_value": "Chrome"})
-
- nan_label = breakdown_label(entity, "nan")
- self.assertEqual(nan_label, {"label": "$pageview - Other", "breakdown_value": "Other"})
-
- none_label = breakdown_label(entity, "None")
- self.assertEqual(none_label, {"label": "$pageview - Other", "breakdown_value": "Other"})
-
- cohort_all_label = breakdown_label(entity, "cohort_all")
- self.assertEqual(
- cohort_all_label,
- {"label": "$pageview - all users", "breakdown_value": "all"},
- )
-
- cohort = _create_cohort(team=self.team, name="cohort1", groups=[{"properties": {"name": "Jane"}}])
- cohort_label = breakdown_label(entity, f"cohort_{cohort.pk}")
- self.assertEqual(
- cohort_label,
- {"label": f"$pageview - {cohort.name}", "breakdown_value": cohort.pk},
- )
-
@also_test_with_materialized_columns(["key"])
def test_breakdown_with_filter(self):
self._create_person(