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): reject saves that include a deleted cohort (#113688)

Phil Haack401d7e8a544a
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index ef5c283bbcd3..823060cb9bb7 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -86,7 +86,7 @@ from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.ph_client import feature_enabled_or_false
from posthog.renderers import SafeJSONRenderer
from posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_event
-from posthog.utils import format_query_params_absolute_url, str_to_bool
+from posthog.utils import format_query_params_absolute_url, safe_int, str_to_bool
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.cdp.backend.filters import build_behavioral_event_expr
@@ -1335,6 +1335,10 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
return str_to_bool(self.initial_data["is_static"])
return bool(getattr(self.instance, "is_static", False))
+ def _reactivates_static_cohort(self, attrs: dict) -> bool:
+ 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
@@ -1396,7 +1400,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
can change - `filters`, the legacy `groups` field, and query-based cohorts' `query`."""
instance = cast(Optional[Cohort], self.instance)
# Flipping a static cohort to dynamic activates its preserved definition.
- reactivating_static = instance is not None and instance.is_static and attrs.get("is_static") is False
+ reactivating_static = self._reactivates_static_cohort(attrs)
if not reactivating_static and not any(field in attrs for field in ("filters", "groups", "query")):
return
team = self._team_for_warehouse_access_check()
@@ -1440,20 +1444,75 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
# Only access denials gate saving; other compile problems surface elsewhere.
return
+ def _validate_cohort_references(self, attrs: dict) -> None:
+ """Reject criteria that include a cohort that is deleted or does not exist.
+
+ The flag evaluator loads only non-deleted cohorts. A flag on a cohort that includes a
+ deleted one therefore fails on every request. This check covers only this cohort's own
+ references. Each included cohort's own save checks its references. A deeper check here
+ would block this save because of a fault in another cohort.
+ """
+ instance = cast(Optional[Cohort], self.instance)
+ # The delete call sends the whole cohort, criteria included. Checking it would block
+ # deleting a cohort that includes a deleted cohort.
+ if instance is not None and attrs.get("deleted"):
+ return
+ restoring = instance is not None and instance.deleted and attrs.get("deleted") is False
+ if not (restoring or self._reactivates_static_cohort(attrs) or "filters" in attrs or "groups" in attrs):
+ return
+ # Static criteria run once, when the cohort is created. The editor resends them on every save.
+ if instance is not None and self._cohort_will_be_static():
+ return
+
+ team = _team_from_serializer_context(self.context)
+ if team is None:
+ return
+ effective = self._effective_filters_after_update(attrs, team=team)
+ if not effective:
+ return
+ referenced_ids = [
+ prop.value for prop in parse_property_group_data(effective.get("properties")).flat if prop.type == "cohort"
+ ]
+ if not referenced_ids:
+ return
+
+ # The lookup includes deleted cohorts so that the error can name the cohort.
+ cohorts_by_id = Cohort.objects.filter(team__project_id=team.project_id).in_bulk(
+ {cohort_id for cohort_id in map(safe_int, referenced_ids) if cohort_id is not None}
+ )
+ # A deleted cohort's page has no criteria editor. The restore messages therefore do not ask the user to remove the criterion.
+ for value in referenced_ids:
+ cohort = cohorts_by_id.get(safe_int(value))
+ if cohort is None:
+ detail = (
+ f"This cohort can't be restored because it includes cohort with id {value}, which does not exist. Create a new cohort instead."
+ if restoring
+ else f"Cohort with id {value} does not exist. Choose another cohort or remove this criterion."
+ )
+ raise ValidationError(detail=detail, code="cohort_does_not_exist")
+ if cohort.deleted:
+ label = f"'{cohort.name}' (ID {cohort.pk})" if cohort.name else f"with id {cohort.pk}"
+ detail = (
+ f"This cohort includes cohort {label}, which has been deleted. Restore that cohort first."
+ if restoring
+ else f"Cohort {label} has been deleted. Choose another cohort or remove this criterion."
+ )
+ raise ValidationError(detail=detail, code="cohort_does_not_exist")
+
def validate(self, attrs: dict) -> dict:
# Field-level validate_filters only runs when the PATCH body includes `filters`. This
# object-level guard covers the static-to-dynamic flip when it does not, re-checking the
# instance's preserved behavioral filters against the feature-flag rule.
attrs = super().validate(attrs)
+ self._validate_cohort_references(attrs)
self._validate_warehouse_access(attrs)
self._validate_no_new_hidden_event_criteria(attrs)
if self.context["request"].method != "PATCH" or self.instance is None:
return attrs
- instance = cast(Cohort, self.instance)
- if instance.is_static and attrs.get("is_static") is False:
+ if self._reactivates_static_cohort(attrs):
effective_filters = self._effective_filters_after_update(attrs)
if effective_filters is not None and cohort_filters_have_values(effective_filters):
self._validate_feature_flag_constraints(effective_filters, cohort_will_be_static=False)
@@ -1534,7 +1593,13 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
self._validate_nested_cohort_behavioral_filters(prop, cohort_used_in_flags)
def _validate_nested_cohort_behavioral_filters(self, prop: Any, cohort_used_in_flags: bool):
- nested_cohort = Cohort.objects.get(pk=prop.value, team__project_id=self.context["project_id"])
+ try:
+ nested_cohort = Cohort.objects.get(
+ pk=prop.value, team__project_id=self.context["project_id"], deleted=False
+ )
+ except Cohort.DoesNotExist:
+ # _validate_cohort_references reports a missing or deleted cohort with an error that names it.
+ return
dependency_cohorts = get_all_cohort_dependencies(nested_cohort, stop_traversal_at_static=True)
for dependency_cohort in [nested_cohort, *dependency_cohorts]:
@@ -1881,6 +1946,8 @@ def get_insights_using_cohort(cohort: Cohort) -> QuerySet[Insight]:
def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:
"""Return other cohorts that include this cohort as criteria."""
+ # Legacy groups can store the cohort id as a string.
+ path_vars = json.dumps({"id": cohort.id, "id_text": str(cohort.id)})
return (
# nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
Cohort.objects.filter(
@@ -1890,9 +1957,10 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:
.exclude(id=cohort.id)
.extra(
where=[
- """jsonb_path_exists(filters, '$.** ? (@.type == "cohort" && @.value == %s)', '{"cohort_id": %s}'::jsonb)"""
+ # Cohort.properties reads groups only when filters is empty.
+ """jsonb_path_exists(COALESCE(NULLIF(filters, '{}'::jsonb), groups), '$.** ? (@.type == "cohort" && (@.value == $id || @.value == $id_text))', %s::jsonb)"""
],
- params=[cohort.id, cohort.id],
+ params=[path_vars],
)
.order_by("id")
)
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 51ae5c39e102..fc737091e857 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -3133,36 +3133,195 @@ [email protected],
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(get_total_calculation_calls(), 4)
+ @parameterized.expand(
+ [
+ (
+ "missing_id_in_legacy_groups_on_update",
+ "update",
+ "groups",
+ "missing",
+ "Cohort with id 99999 does not exist. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "missing_id_on_create",
+ "create",
+ "filters",
+ "missing",
+ "Cohort with id 99999 does not exist. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "missing_id_on_update",
+ "update",
+ "filters",
+ "missing",
+ "Cohort with id 99999 does not exist. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "deleted_cohort_on_update",
+ "update",
+ "filters",
+ "deleted",
+ "Cohort 'Retired cohort' (ID {id}) has been deleted. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "deleted_cohort_on_create",
+ "create",
+ "filters",
+ "deleted",
+ "Cohort 'Retired cohort' (ID {id}) has been deleted. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "deleted_cohort_on_create_of_deleted_cohort",
+ "create_deleted",
+ "filters",
+ "deleted",
+ "Cohort 'Retired cohort' (ID {id}) has been deleted. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "static_cohort_turned_dynamic",
+ "reactivate_static",
+ "filters",
+ "deleted",
+ "Cohort 'Retired cohort' (ID {id}) has been deleted. Choose another cohort or remove this criterion.",
+ ),
+ (
+ "restore_of_cohort_that_includes_deleted_cohort",
+ "restore",
+ "filters",
+ "deleted",
+ "This cohort includes cohort 'Retired cohort' (ID {id}), which has been deleted. Restore that cohort first.",
+ ),
+ (
+ "restore_of_cohort_that_includes_missing_cohort",
+ "restore",
+ "filters",
+ "missing",
+ "This cohort can't be restored because it includes cohort with id 99999, which does not exist. Create a new cohort instead.",
+ ),
+ ]
+ )
@patch("django.db.transaction.on_commit", side_effect=lambda func: func())
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
- def test_creating_update_and_calculating_with_invalid_cohort(
- self, patch_calculate_cohort, patch_capture, patch_on_commit
+ def test_saving_a_reference_to_a_missing_or_deleted_cohort_is_rejected(
+ self,
+ _name,
+ save,
+ field,
+ target,
+ expected_detail,
+ patch_calculate_cohort,
+ patch_capture,
+ patch_on_commit,
):
- # Cohort A
- response_a = self.client.post(
- f"/api/projects/{self.team.id}/cohorts",
- data={"name": "cohort A", "groups": [{"properties": {"team_id": 5}}]},
- )
- self.assertEqual(patch_calculate_cohort.call_count, 1)
-
- # Update Cohort A to depend on an invalid cohort
- response = self.client.patch(
- f"/api/projects/{self.team.id}/cohorts/{response_a.json()['id']}",
- data={
- "name": "Cohort A, reloaded",
- "groups": [{"properties": [{"type": "cohort", "value": "99999", "key": "id"}]}],
+ retired = Cohort.objects.create(
+ team=self.team,
+ name="Retired cohort",
+ deleted=True,
+ # _validate_nested_cohort_behavioral_filters rejects a behavioral cohort. The deleted_cohort_on_update row fails if its lookup stops excluding deleted cohorts.
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 1,
+ "time_interval": "day",
+ }
+ ],
+ }
+ ],
+ }
},
)
+ target_id = 99999 if target == "missing" else retired.pk
+ criteria: dict[str, Any] = (
+ {"groups": [{"properties": [{"type": "cohort", "key": "id", "value": str(target_id)}]}]}
+ if field == "groups"
+ else {
+ "filters": {
+ "properties": {
+ "type": "AND",
+ "values": [{"type": "AND", "values": [{"type": "cohort", "key": "id", "value": target_id}]}],
+ }
+ }
+ }
+ )
+ cohorts_url = f"/api/projects/{self.team.id}/cohorts"
+
+ if save == "create":
+ response = self.client.post(cohorts_url, data={"name": "cohort A", **criteria})
+ elif save == "create_deleted":
+ response = self.client.post(cohorts_url, data={"name": "cohort A", "deleted": True, **criteria})
+ elif save == "update":
+ cohort_a = Cohort.objects.create(team=self.team, name="cohort A")
+ # _validate_nested_cohort_behavioral_filters runs only on a PATCH to a cohort that an active flag uses.
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="cohort-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_a.pk, "type": "cohort"}]}]},
+ )
+ response = self.client.patch(
+ f"{cohorts_url}/{cohort_a.pk}", data={"name": "cohort A, reloaded", **criteria}
+ )
+ elif save == "reactivate_static":
+ cohort_a = Cohort.objects.create(team=self.team, name="cohort A", is_static=True, **criteria)
+ response = self.client.patch(f"{cohorts_url}/{cohort_a.pk}", data={"is_static": False})
+ else:
+ cohort_a = Cohort.objects.create(team=self.team, name="cohort A", deleted=True, **criteria)
+ response = self.client.patch(f"{cohorts_url}/{cohort_a.pk}", data={"deleted": False})
+
self.assertEqual(response.status_code, 400, response.content)
self.assertLessEqual(
{
- "detail": "Invalid Cohort ID in filter",
"type": "validation_error",
+ "code": "cohort_does_not_exist",
+ "detail": expected_detail.format(id=target_id),
}.items(),
response.json().items(),
)
- self.assertEqual(patch_calculate_cohort.call_count, 1)
+ self.assertEqual(patch_calculate_cohort.call_count, 0)
+
+ @parameterized.expand(
+ [
+ ("soft_delete_with_full_payload", False, lambda c: {"name": c.name, "filters": c.filters, "deleted": True}),
+ ("name_only_update", False, lambda c: {"name": "cohort A, renamed"}),
+ (
+ "static_cohort_rename_with_preserved_criteria",
+ True,
+ lambda c: {"name": "cohort A, renamed", "is_static": True, "filters": c.filters},
+ ),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_saving_a_cohort_with_a_stored_deleted_reference_without_writing_live_criteria_succeeds(
+ self, _name, is_static, build_payload, patch_calculate_cohort, patch_capture
+ ):
+ retired = Cohort.objects.create(team=self.team, name="Retired cohort", deleted=True)
+ filters = CohortFilters.model_validate(
+ {
+ "properties": {
+ "type": "AND",
+ "values": [{"type": "AND", "values": [{"type": "cohort", "key": "id", "value": retired.pk}]}],
+ }
+ },
+ context={"team": self.team},
+ ).model_dump(exclude_none=True)
+ cohort_a = Cohort.objects.create(team=self.team, name="cohort A", filters=filters, is_static=is_static)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort_a.pk}", data=build_payload(cohort_a)
+ )
+
+ self.assertEqual(response.status_code, 200, response.content)
@patch("django.db.transaction.on_commit", side_effect=lambda func: func())
@patch("posthog.api.cohort.report_user_action")
@@ -5980,9 +6139,19 @@ [email protected],
response.json()["detail"],
)
+ @parameterized.expand(
+ [
+ ("filters", "filters", int, status.HTTP_400_BAD_REQUEST),
+ ("legacy_groups", "groups", int, status.HTTP_400_BAD_REQUEST),
+ ("legacy_groups_with_string_id", "groups", str, status.HTTP_400_BAD_REQUEST),
+ ("legacy_groups_beside_filters", "groups_beside_filters", int, status.HTTP_200_OK),
+ ]
+ )
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
- def test_cannot_delete_cohort_used_in_another_cohort(self, patch_calculate_cohort, patch_capture):
+ def test_cannot_delete_cohort_used_in_another_cohort(
+ self, _name: str, field: str, id_type: type, expected_status: int, patch_calculate_cohort, patch_capture
+ ) -> None:
# Create base cohort
response = self.client.post(
f"/api/projects/{self.team.id}/cohorts",
@@ -5990,18 +6159,19 @@ [email protected],
)
base_cohort_id = response.json()["id"]
- # Create dependent cohort that references the base cohort
- dependent_response = self.client.post(
- f"/api/projects/{self.team.id}/cohorts",
- data={
- "name": "Dependent Cohort",
- "filters": {
- "properties": {
- "type": "AND",
- "values": [{"type": "cohort", "key": "id", "value": base_cohort_id}],
- }
- },
+ reference = {"type": "cohort", "key": "id", "value": id_type(base_cohort_id)}
+ email_filter = {"type": "person", "key": "email", "operator": "icontains", "value": "@example.com"}
+ criteria_by_field: dict[str, dict[str, Any]] = {
+ "filters": {"filters": {"properties": {"type": "AND", "values": [reference]}}},
+ "groups": {"groups": [{"properties": [reference]}]},
+ # Cohort.properties ignores groups when filters is set.
+ "groups_beside_filters": {
+ "filters": {"properties": {"type": "AND", "values": [email_filter]}},
+ "groups": [{"properties": [reference]}],
},
+ }
+ dependent_response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts", data={"name": "Dependent Cohort", **criteria_by_field[field]}
)
self.assertEqual(dependent_response.status_code, status.HTTP_201_CREATED)
@@ -6011,11 +6181,12 @@ [email protected],
data={"deleted": True},
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn(
- "This cohort is used as criteria in 1 other cohort(s): Dependent Cohort",
- response.json()["detail"],
- )
+ self.assertEqual(response.status_code, expected_status)
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ self.assertIn(
+ "This cohort is used as criteria in 1 other cohort(s): Dependent Cohort",
+ response.json()["detail"],
+ )
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
index 75048f522bae..d5ca0872becd 100644
--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
@@ -1503,6 +1503,34 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
traverse(destination_head_cohort, 0)
+ def test_copy_feature_flag_fails_for_target_when_cohort_includes_deleted_cohort(self):
+ deleted_cohort = Cohort.objects.create(team=self.team, name="deleted child", deleted=True)
+ head_cohort = Cohort.objects.create(
+ team=self.team,
+ name="head",
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [{"key": "id", "type": "cohort", "value": deleted_cohort.pk}],
+ }
+ },
+ )
+ self.feature_flag_to_copy.filters = {
+ "groups": [{"properties": [{"key": "id", "type": "cohort", "value": head_cohort.pk}]}]
+ }
+ self.feature_flag_to_copy.save()
+
+ response = self._post_copy_flag(self.feature_flag_to_copy)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["success"], [])
+ self.assertEqual(len(body["failed"]), 1)
+ self.assertEqual(body["failed"][0]["project_id"], self.team_2.id)
+ self.assertIn("cohort_does_not_exist", body["failed"][0]["error_message"])
+ self.assertFalse(Cohort.objects.filter(team_id=self.team_2.id).exists())
+ self.assertFalse(FeatureFlag.objects.filter(team_id=self.team_2.id, key=self.feature_flag_key).exists())
+
def test_copy_feature_flag_destination_cohort_not_overridden(self):
cohort_name = "cohort-1"
target_project = self.team_2