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.

fix(cohorts): derive filters from legacy groups in API and resave_cohorts (#124884)

Patricio6785fa87d129
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 653bb5b70039..d5b83fed3dee 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -6,7 +6,6 @@ import uuid
import hashlib
from collections import defaultdict
from collections.abc import Iterable, Iterator, Sequence
-from copy import deepcopy
from typing import Annotated, Any, ClassVar, Literal, NoReturn, Optional, Union, cast
from django.conf import settings
@@ -118,6 +117,7 @@ from products.cohorts.backend.models.util import (
cohort_filters_have_values,
get_all_cohort_dependencies,
get_friendly_error_message,
+ legacy_groups_to_filters,
validate_actors_query_for_cohort,
)
from products.cohorts.backend.models.validation import CohortTypeValidationSerializer
@@ -1577,10 +1577,9 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
instance = cast(Optional[Cohort], self.instance)
return instance is not None and instance.is_static and attrs.get("is_static") is False
- def _effective_filters_after_update(self, attrs: dict, team: Optional[Team] = None) -> dict | None:
- # Derive the properties that survive the save, mirroring Cohort.properties precedence:
- # filters win over the legacy groups field, so clearing filters re-activates preserved
- # groups. Pass team on the create path, where there's no instance to read it from.
+ def _effective_filters_after_update(self, attrs: dict) -> dict | None:
+ # Derive the properties that survive the save, mirroring Cohort.properties precedence: filters
+ # win over the legacy groups field, so clearing filters re-activates preserved groups.
instance = cast(Optional[Cohort], self.instance)
filters = attrs.get("filters", instance.filters if instance else None)
if filters:
@@ -1590,12 +1589,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
if not groups:
return None
- effective_team = team or (instance.team if instance else None)
- if effective_team is None:
- return None
-
- cohort = Cohort(team=effective_team, filters=None, groups=deepcopy(groups))
- return {"properties": cohort.properties.to_dict()}
+ return legacy_groups_to_filters(groups)
def validate_filters(self, raw: dict):
"""
@@ -1660,7 +1654,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
return
# Check what survives the save, not just the fields in the payload.
- effective = self._effective_filters_after_update(attrs, team=team)
+ effective = self._effective_filters_after_update(attrs)
properties = effective.get("properties") if effective else None
# A payload query is what's being saved; a flip re-activates the instance's preserved query.
query = attrs["query"] if "query" in attrs else (instance.query if reactivating_static and instance else None)
@@ -1705,7 +1699,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
team = _team_from_serializer_context(self.context)
if team is None:
return
- effective = self._effective_filters_after_update(attrs, team=team)
+ effective = self._effective_filters_after_update(attrs)
if not effective:
return
referenced_ids = [
@@ -1743,6 +1737,17 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
# instance's preserved behavioral filters against the feature-flag rule.
attrs = super().validate(attrs)
+ cohort_will_be_static = self._cohort_will_be_static()
+ if not attrs.get("filters") and attrs.get("groups") and not cohort_will_be_static:
+ derived_filters = legacy_groups_to_filters(attrs["groups"])
+ if not derived_filters:
+ raise ValidationError(
+ {"groups": "The provided legacy groups could not be converted to cohort filters."}
+ )
+
+ # Same schema and feature-flag checks as the `filters` field.
+ attrs["filters"] = self.validate_filters(derived_filters)
+
parsed_csv = self._parse_csv_upload(attrs)
if parsed_csv is not None:
attrs["_parsed_csv"] = parsed_csv
@@ -1783,9 +1788,9 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
team = _team_from_serializer_context(self.context)
# Passing no attrs reads the stored definition. Cohort.properties would rewrite the stored
# legacy groups in place.
- existing = self._effective_filters_after_update({}, team=team)
+ existing = self._effective_filters_after_update({})
hidden_event = added_hidden_event(
- _behavioral_event_names(_flat_properties(self._effective_filters_after_update(attrs, team=team))),
+ _behavioral_event_names(_flat_properties(self._effective_filters_after_update(attrs))),
_behavioral_event_names(_flat_properties(existing)),
)
if hidden_event and team is not None and hides_flag_calls_from_query_builders(team.organization_id):
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 2e656ace3f29..0a9a99f9c5f2 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -214,22 +214,17 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
self.user,
"cohort created",
{
- "filters": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [{"key": "team_id", "value": "5", "type": "person"}],
- }
- ],
- },
+ "filters": ANY,
"name_length": 8,
"deleted": False,
"is_static": False,
- # The legacy `groups` payload leaves `filters` empty, so neither classification
- # is computed for it.
- "cohort_type": None,
- "condition_type": None,
+ "cohort_type": "realtime",
+ "condition_type": {
+ "person_properties": True,
+ "behavioral": False,
+ "lifecycle": False,
+ "cohorts": False,
+ },
"realtime_enabled": False,
"realtime_level": "off",
},
@@ -237,6 +232,9 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
request=ANY,
)
+ leaf = patch_capture.call_args[0][2]["filters"]["values"][0]["values"][0]
+ self.assertEqual((leaf["key"], leaf["operator"], leaf["value"]), ("team_id", "exact", "5"))
+
with self.capture_queries_startswith("INSERT INTO cohortpeople") as insert_statements:
response = self.client.patch(
f"/api/projects/{self.team.id}/cohorts/{response.json()['id']}",
@@ -264,20 +262,17 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
self.user,
"cohort updated",
{
- "filters": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [{"key": "team_id", "value": "6", "type": "person"}],
- }
- ],
- },
+ "filters": ANY,
"name_length": 9,
"deleted": False,
"is_static": False,
- "cohort_type": None,
- "condition_type": None,
+ "cohort_type": "realtime",
+ "condition_type": {
+ "person_properties": True,
+ "behavioral": False,
+ "lifecycle": False,
+ "cohorts": False,
+ },
"realtime_enabled": False,
"realtime_level": "off",
"updated_by_creator": True,
@@ -286,6 +281,9 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
request=ANY,
)
+ leaf = patch_capture.call_args[0][2]["filters"]["values"][0]["values"][0]
+ self.assertEqual((leaf["key"], leaf["operator"], leaf["value"]), ("team_id", "exact", "6"))
+
@parameterized.expand(
[
("team_off_the_pipeline", None, False, "off"),
@@ -552,6 +550,140 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
self.assertEqual(response.status_code, 400, response.content)
self.assertIn(expected_detail, response.json()["detail"])
+ def test_create_cohort_with_legacy_groups_derives_filters_and_condition_type(self):
+ groups = [
+ {
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "is_set",
+ "operator": "is_set",
+ }
+ ]
+ }
+ ]
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Legacy group cohort", "groups": groups},
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ cohort = Cohort.objects.get(pk=response.json()["id"])
+ assert cohort.filters is not None
+ leaf = cohort.filters["properties"]["values"][0]["values"][0]
+ self.assertEqual((leaf["key"], leaf["type"], leaf["operator"]), ("email", "person", "is_set"))
+ self.assertEqual(
+ cohort.condition_type,
+ {
+ "person_properties": True,
+ "behavioral": False,
+ "lifecycle": False,
+ "cohorts": False,
+ },
+ )
+
+ def test_patch_cohort_with_legacy_groups_updates_derived_filters(self):
+ initial_groups = [
+ {
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "is_set",
+ "operator": "is_set",
+ }
+ ]
+ }
+ ]
+ create_res = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Legacy cohort to patch", "groups": initial_groups},
+ )
+ self.assertEqual(create_res.status_code, 201)
+ cohort_id = create_res.json()["id"]
+
+ updated_groups = [
+ {
+ "properties": [
+ {
+ "key": "name",
+ "type": "person",
+ "value": "Alice",
+ "operator": "exact",
+ }
+ ]
+ }
+ ]
+ patch_res = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}",
+ data={"groups": updated_groups},
+ )
+ self.assertEqual(patch_res.status_code, 200, patch_res.content)
+ cohort = Cohort.objects.get(pk=cohort_id)
+ assert cohort.filters is not None
+ leaf = cohort.filters["properties"]["values"][0]["values"][0]
+ self.assertEqual(
+ (leaf["key"], leaf["type"], leaf["operator"], leaf["value"]), ("name", "person", "exact", "Alice")
+ )
+
+ @parameterized.expand(
+ [
+ # Passes validate_groups, but the behavioral leaf has no time window, so conversion fails.
+ (
+ "unconvertible_behavioral",
+ {"event_type": "events", "key": "$pageview", "value": "performed_event", "type": "behavioral"},
+ "could not be converted",
+ ),
+ # Converts, but the filters schema rejects it, as it does when sent as `filters`.
+ ("hogql_leaf", {"type": "hogql", "key": "1 = 1"}, None),
+ ]
+ )
+ def test_create_cohort_with_invalid_legacy_groups_returns_400(
+ self, _name: str, leaf: dict, expected_detail: str | None
+ ) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Malformed legacy group cohort", "groups": [{"properties": [leaf]}]},
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ if expected_detail:
+ self.assertIn(expected_detail, response.json()["detail"])
+ self.assertFalse(Cohort.objects.filter(team=self.team, name="Malformed legacy group cohort").exists())
+
+ def test_patch_cohort_used_in_flag_rejects_behavioral_groups(self):
+ def cohort_filter(cohort_id: int) -> dict[str, Any]:
+ return {"key": "id", "value": cohort_id, "type": "cohort"}
+
+ person_filters = {
+ "properties": {
+ "type": "AND",
+ "values": [{"key": "email", "value": "is_set", "operator": "is_set", "type": "person"}],
+ }
+ }
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="cohort in flag",
+ filters=person_filters,
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [cohort_filter(cohort.pk)]}]},
+ name="Cohort-based flag",
+ key="cohort-flag",
+ created_by=self.user,
+ )
+
+ behavioral_groups = [{"event_id": "$pageview", "days": 7}]
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}",
+ data={"groups": behavioral_groups},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json()["code"], "behavioral_cohort_found")
+ self.assertIn("Behavioral filters cannot be added to cohorts used in feature flags", response.json()["detail"])
+
def test_static_cohort_csv_upload_end_to_end(self):
"""Test CSV upload end-to-end with actual celery task execution"""
self.team.app_urls = ["http://somewebsite.com"]
@@ -2795,28 +2927,19 @@ [email protected],
"end_date": None,
"event_id": None,
"action_id": None,
- "properties": [
- {
- "key": "prop",
- "type": "person",
- "value": "5",
- }
- ],
+ "properties": {"prop": "5"},
"start_date": None,
"count_operator": None,
}
],
- "after": [
- {
- "properties": [
- {
- "key": "prop",
- "type": "person",
- "value": "6",
- }
- ]
- }
- ],
+ "after": [{"properties": {"prop": "6"}}],
+ },
+ {
+ "type": "Cohort",
+ "action": "changed",
+ "field": "filters",
+ "before": mock.ANY,
+ "after": mock.ANY,
},
],
"trigger": None,
diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.py
index 88e229e1f4ed..cb6af363ff6a 100644
--- a/posthog/management/commands/resave_cohorts.py
+++ b/posthog/management/commands/resave_cohorts.py
@@ -16,7 +16,11 @@ from posthog.dataclasses import frozen
from posthog.models.team.team import Team
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, CohortType
-from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically
+from products.cohorts.backend.models.util import (
+ get_all_cohort_dependencies,
+ legacy_groups_to_filters,
+ sort_cohorts_topologically,
+)
from products.cohorts.backend.realtime_teams import (
backfill_triggers_suppressed,
is_processing_team,
@@ -385,6 +389,16 @@ class Command(BaseCommand):
) -> CohortResaveStats:
"""Process all cohorts for a single team."""
all_cohorts = self._load_team_cohorts(team, batch_size)
+ # Convert groups-only cohorts up front so the dependency map, the sort, and the recompute
+ # all read their filters. Static cohorts never evaluate filters, so they stay as they are.
+ # A cohort whose groups can't be converted stays unfixed, so it counts as an error.
+ unconvertible = 0
+ for loaded in all_cohorts:
+ if not loaded.filters and loaded.groups and not loaded.is_static:
+ loaded.filters = legacy_groups_to_filters(loaded.groups)
+ if not loaded.filters:
+ unconvertible += 1
+ logger.error("cohort_resave_groups_unconvertible", cohort_id=loaded.id, team_id=team.id)
seen_cohorts_cache: dict[int, CohortOrEmpty] = {c.id: c for c in all_cohorts}
cohort_dependencies, unreadable_ids = self._build_dependency_map(team, all_cohorts, seen_cohorts_cache)
@@ -396,7 +410,7 @@ class Command(BaseCommand):
total = len(unreadable_ids)
changed = 0
- errors = len(unreadable_ids)
+ errors = len(unreadable_ids) + unconvertible
validation_errors = 0
prospective_realtime = 0
diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.py
index 4003189374ce..04dff712ef0c 100644
--- a/posthog/management/commands/test/test_resave_cohorts.py
+++ b/posthog/management/commands/test/test_resave_cohorts.py
@@ -230,6 +230,62 @@ class TestResaveCohortsCommandSingleTeam(BaseTest):
for sql in cohort_selects:
assert 'posthog_team"."event_names"' not in sql
+ @parameterized.expand(
+ [
+ (
+ "list_properties",
+ [{"properties": [{"key": "email", "value": "is_set", "operator": "is_set", "type": "person"}]}],
+ ("email", "is_set", "is_set"),
+ ),
+ # Old dict-style groups carry no operator, which filters validation requires.
+ ("dict_properties", [{"properties": {"email": "[email protected]"}}], ("email", "exact", "[email protected]")),
+ ]
+ )
+ def test_resave_legacy_groups_cohort_derives_filters_and_condition_type(
+ self, _name: str, groups: list[dict], expected_leaf: tuple[str, str, str]
+ ) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="legacy_groups_cohort", groups=groups, filters=None)
+
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ cohort = Cohort.objects.get(pk=cohort.pk)
+ assert cohort.filters is not None
+ leaf = cohort.filters["properties"]["values"][0]["values"][0]
+ assert (leaf["key"], leaf["operator"], leaf["value"]) == expected_leaf
+ assert cohort.condition_type == {
+ "person_properties": True,
+ "behavioral": False,
+ "lifecycle": False,
+ "cohorts": False,
+ }
+
+ def test_resave_counts_unconvertible_legacy_groups_as_errors(self) -> None:
+ # A behavioral leaf without a time window converts to nothing.
+ leaf = {"event_type": "events", "key": "$pageview", "value": "performed_event", "type": "behavioral"}
+ cohort = Cohort.objects.create(
+ team=self.team, name="unconvertible_groups_cohort", groups=[{"properties": [leaf]}], filters=None
+ )
+ out = StringIO()
+
+ call_command("resave_cohorts", team_id=[self.team.id], stdout=out)
+
+ cohort = Cohort.objects.get(pk=cohort.pk)
+ assert not cohort.filters
+ assert "1 errors" in out.getvalue()
+
+ def test_resave_leaves_static_legacy_groups_cohort_untouched(self) -> None:
+ # The flags service assumes a static cohort is never realtime.
+ groups = [{"properties": [{"key": "email", "value": "is_set", "operator": "is_set", "type": "person"}]}]
+ cohort = Cohort.objects.create(
+ team=self.team, name="static_legacy_groups_cohort", groups=groups, filters=None, is_static=True
+ )
+
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ cohort = Cohort.objects.get(pk=cohort.pk)
+ assert not cohort.filters
+ assert cohort.cohort_type != "realtime"
+
class TestResaveCohortsCommandWithDependencies(BaseTest):
def test_cohort_dependency_blocks_realtime(self):
@@ -508,6 +564,49 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
# 3. Cohort A cannot be realtime (references B which has dependencies)
assert cohort_a.cohort_type is None
+ def test_cohort_referencing_legacy_groups_non_leaf_cannot_be_realtime(self):
+ """Same as above, with B defined only through legacy `groups`."""
+ team: Team = self.team
+
+ cohort_c = Cohort.objects.create(
+ team=team, name="cohort_c", filters=_make_person_only_filters(email="[email protected]")
+ )
+ cohort_b = Cohort.objects.create(
+ team=team,
+ name="cohort_b",
+ filters=None,
+ groups=[
+ {
+ "properties": [
+ {"type": "cohort", "key": "id", "value": cohort_c.id},
+ {"type": "person", "key": "name", "value": "B User"},
+ ]
+ }
+ ],
+ )
+ cohort_a = Cohort.objects.create(
+ team=team,
+ name="cohort_a",
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "cohort", "key": "id", "value": cohort_b.id},
+ {"type": "person", "key": "name", "operator": "exact", "value": "A User"},
+ ],
+ }
+ },
+ )
+
+ call_command("resave_cohorts", team_id=[team.id])
+
+ cohort_a.refresh_from_db()
+ cohort_b.refresh_from_db()
+
+ assert cohort_b.filters
+ assert cohort_b.cohort_type == "realtime"
+ assert cohort_a.cohort_type is None
+
class TestResaveCohortsCommandTwoTeams(BaseTest):
def test_resave_two_teams_each_five_types(self):
diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.py
index bc121ef95e00..9f8af39a640e 100644
--- a/products/cohorts/backend/models/test/test_util.py
+++ b/products/cohorts/backend/models/test/test_util.py
@@ -17,6 +17,7 @@ from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.hogql.hogql import HogQLContext
+from posthog.api.cohort import CohortFilters
from posthog.clickhouse.client import sync_execute
from posthog.errors import CHQueryErrorS3Error
from posthog.exceptions import (
@@ -41,6 +42,7 @@ from products.cohorts.backend.models.util import (
get_nested_cohort_ids,
get_static_cohort_size,
insert_cohort_query_actors_into_ch,
+ legacy_groups_to_filters,
parse_error_code,
print_cohort_hogql_query,
run_cohort_query,
@@ -135,6 +137,40 @@ class TestRunCohortQueryStatsScheduling(SimpleTestCase):
self.assertEqual(mock_capture.call_count, 2)
+class TestLegacyGroupsToFilters(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("person_without_operator", {"key": "email", "value": "[email protected]", "type": "person"}),
+ ("cohort_in", {"key": "id", "value": 1, "type": "cohort", "operator": "in"}),
+ ("cohort_not_in", {"key": "id", "value": 1, "type": "cohort", "operator": "not_in"}),
+ ]
+ )
+ def test_converted_filters_pass_filters_validation(self, _name: str, leaf: dict[str, Any]) -> None:
+ filters = legacy_groups_to_filters([{"properties": [leaf]}])
+
+ assert filters is not None
+ CohortFilters.model_validate(filters)
+
+ @parameterized.expand(
+ [
+ ("in", "in", False, False),
+ ("in_with_negation", "in", True, True),
+ ("not_in", "not_in", False, True),
+ ("not_in_with_negation", "not_in", True, True),
+ ]
+ )
+ def test_cohort_in_and_not_in_become_negation(
+ self, _name: str, operator: str, negation: bool, expected_negation: bool
+ ) -> None:
+ leaf_in = {"key": "id", "value": 1, "type": "cohort", "operator": operator, "negation": negation}
+ filters = legacy_groups_to_filters([{"properties": [leaf_in]}])
+
+ assert filters is not None
+ leaf = filters["properties"]["values"][0]["values"][0]
+ assert "operator" not in leaf
+ assert leaf.get("negation", False) is expected_negation
+
+
class TestCohortUtils(BaseTest):
def test_simplified_cohort_filter_properties_static_cohort(self):
_create_person(
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index 7e1b50b30360..83ff601afb7b 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -59,6 +59,7 @@ from posthog.schema_migrations.upgrade import upgrade
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.cohorts.backend.models.dependencies import get_cohort_dependents
+from products.cohorts.backend.models.leaf_shape import walk_filter_leaves
from products.cohorts.backend.models.sql import GET_COHORT_SIZE_SQL, RECALCULATE_COHORT_BY_ID
if TYPE_CHECKING:
@@ -185,6 +186,42 @@ COHORT_STATS_COLLECTION_DELAY_SECONDS = 60 # Short delay to allow query_log to
logger = structlog.get_logger(__name__)
+def _normalize_legacy_operators(properties: dict) -> None:
+ # Legacy groups store operators that filters validation rejects: person properties often omit
+ # `operator`, which every evaluator reads as exact, and cohort references use in/not_in where
+ # filters use `negation`.
+ for leaf in walk_filter_leaves(properties):
+ if leaf.get("type") in ("person", "person_metadata") and leaf.get("operator") is None:
+ leaf["operator"] = "exact"
+ elif leaf.get("type") == "cohort" and leaf.get("operator") in ("in", "not_in", None):
+ # Legacy readers negate when either `negation` or `not_in` is set, so the two never cancel out.
+ if leaf.pop("operator", None) == "not_in":
+ leaf["negation"] = True
+
+
+def legacy_groups_to_filters(groups: list[dict] | None) -> dict | None:
+ """Convert legacy `groups` into `filters`, or return None if they're empty or any group can't be converted.
+
+ Copies `groups` first, because `Cohort.properties` rewrites them in place.
+ """
+ if not groups:
+ return None
+ try:
+ dummy_cohort = Cohort(filters=None, groups=copy.deepcopy(groups))
+ prop_group = dummy_cohort.properties
+ if prop_group and prop_group.values:
+ properties = prop_group.to_dict()
+ # parse_property_group_data swallows an invalid group into an empty one, so reject any
+ # empty group rather than store filters that match nobody.
+ if not all(properties.get("values") or []):
+ return None
+ _normalize_legacy_operators(properties)
+ return {"properties": properties}
+ except Exception:
+ logger.warning("cohort_legacy_groups_conversion_failed", exc_info=True)
+ return None
+
+
def close_open_population_attempts(
cohort_id: int, *, finished_at: datetime, started_before: datetime | None = None
) -> int:
diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.py
index 5a076247dcb0..feb101af7204 100644
--- a/products/demo/backend/logic/products/hedgebox/matrix.py
+++ b/products/demo/backend/logic/products/hedgebox/matrix.py
@@ -285,18 +285,24 @@ class HedgeboxMatrix(Matrix):
team=team,
name="Signed-up users",
created_by=user,
- groups=[
- {
- "properties": [
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
{
- "key": "email",
- "type": "person",
- "value": "is_set",
- "operator": "is_set",
+ "type": "AND",
+ "values": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "is_set",
+ "operator": "is_set",
+ }
+ ],
}
- ]
+ ],
}
- ],
+ },
)
# Create the standard internal/test users cohort (same as non-demo teams get)
from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohort
diff --git a/products/demo/backend/logic/products/spikegpt/matrix.py b/products/demo/backend/logic/products/spikegpt/matrix.py
index ff1ccbc224df..c4b9f4b41219 100644
--- a/products/demo/backend/logic/products/spikegpt/matrix.py
+++ b/products/demo/backend/logic/products/spikegpt/matrix.py
@@ -33,18 +33,24 @@ class SpikeGPTMatrix(Matrix):
team=team,
name="Signed-up users",
created_by=user,
- groups=[
- {
- "properties": [
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
{
- "key": "email",
- "type": "person",
- "value": "is_set",
- "operator": "is_set",
+ "type": "AND",
+ "values": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "is_set",
+ "operator": "is_set",
+ }
+ ],
}
- ]
+ ],
}
- ],
+ },
)
# Create the standard internal/test users cohort (same as non-demo teams get)
from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohort