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.

perf(cohorts): pre-filter flag and insight scans in used-in lookup (#62820)

Phil Haackfc821d6234d3
diff --git a/ee/api/rbac/test/test_access_control.py b/ee/api/rbac/test/test_access_control.py
index 0c6af3063d9a..e0ea02c34cb6 100644
--- a/ee/api/rbac/test/test_access_control.py
+++ b/ee/api/rbac/test/test_access_control.py
@@ -12,6 +12,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rbac.user_access_control import AccessSource
from posthog.utils import render_template
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
@@ -2015,3 +2016,60 @@ class TestAccessControlMembersEndpoint(BaseAccessControlTest):
res = self.client.get("/api/projects/@current/access_control_members")
member_data = self._find_member(res.json()["results"], self.user2_membership.id)
assert member_data["project"]["access_level"] == "member"
+
+
+class TestCohortUsedInAccessControl(BaseAccessControlTest):
+ def setUp(self):
+ super().setUp()
+ self.other_user = self._create_user("other_user")
+
+ def _cohort_flag_filters(self, cohort_id: int) -> dict:
+ return {"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]}
+
+ def _create_cohort_with_restricted_flag(self) -> Cohort:
+ # Two flags reference the cohort; "hidden-flag" gets object-level "none" access.
+ # Leaves the current user as an org ADMIN.
+ cohort = Cohort.objects.create(team=self.team, name="Target Cohort")
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="visible-flag",
+ name="Visible Flag",
+ filters=self._cohort_flag_filters(cohort.id),
+ )
+ hidden_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.other_user,
+ key="hidden-flag",
+ name="Hidden Flag",
+ filters=self._cohort_flag_filters(cohort.id),
+ )
+
+ self._org_membership(OrganizationMembership.Level.ADMIN)
+ res = self.client.put(
+ f"/api/projects/@current/feature_flags/{hidden_flag.id}/access_controls",
+ {"access_level": "none"},
+ )
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ return cohort
+
+ def test_used_in_excludes_flags_without_access(self):
+ cohort = self._create_cohort_with_restricted_flag()
+ self._org_membership(OrganizationMembership.Level.MEMBER)
+
+ res = self.client.get(f"/api/projects/@current/cohorts/{cohort.id}/used_in")
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ block = res.json()["feature_flags"]
+ assert [flag["key"] for flag in block["results"]] == ["visible-flag"]
+ assert block["total"] == 1
+ assert block["has_more"] is False
+
+ def test_used_in_includes_restricted_flags_for_org_admins(self):
+ cohort = self._create_cohort_with_restricted_flag()
+
+ res = self.client.get(f"/api/projects/@current/cohorts/{cohort.id}/used_in")
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ block = res.json()["feature_flags"]
+ assert [flag["key"] for flag in block["results"]] == ["visible-flag", "hidden-flag"]
+ assert block["total"] == 2
+ assert block["has_more"] is False
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index b4dc833ffbab..f924ba06cdf4 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -2,6 +2,7 @@ import { api } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -28,6 +29,8 @@ import {
TimeUnitType,
} from '~/types'
+import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
+
jest.mock('uuid', () => ({
v4: jest.fn().mockReturnValue('mocked-uuid'),
}))
@@ -43,7 +46,7 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
},
}))
-const mockUsedInResponse = {
+const mockUsedInResponse: CohortUsedInResponseApi = {
feature_flags: {
results: [{ id: 7, key: 'my-flag', name: 'My Flag' }],
total: 1,
@@ -103,6 +106,52 @@ describe('cohortEditLogic', () => {
expect(logic.values.usedIn).toEqual(mockUsedInResponse)
})
+ it('swallows used-in 404s without reporting them', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/used_in/': () => [404, { detail: 'Not found.' }],
+ },
+ })
+ await initCohortLogic({ id: 1 })
+ // The loader swallows the error and returns a value, so Success (not Failure) fires.
+ await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+
+ expect(logic.values.usedIn).toEqual(null)
+ expect(posthog.captureException).not.toHaveBeenCalled()
+ })
+
+ it('reports non-404 used-in failures', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/used_in/': () => [500, { detail: 'Server error' }],
+ },
+ })
+ await initCohortLogic({ id: 1 })
+ // The loader still returns a value on non-404 errors, so Success (not Failure) fires.
+ await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+
+ expect(logic.values.usedIn).toEqual(null)
+ expect(posthog.captureException).toHaveBeenCalled()
+ })
+
+ it('keeps the previously loaded value when a refresh fails', async () => {
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+ expect(logic.values.usedIn).toEqual(mockUsedInResponse)
+
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/used_in/': () => [500, { detail: 'Server error' }],
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.loadUsedIn()
+ }).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+
+ // The failed refresh returns the prior value instead of blanking the banner.
+ expect(logic.values.usedIn).toEqual(mockUsedInResponse)
+ })
+
it('loads new cohort on mount', async () => {
await initCohortLogic({ id: 'new' })
await expectLogic(logic).toDispatchActions(['setCohort'])
@@ -177,13 +226,9 @@ describe('cohortEditLogic', () => {
},
})
logic.actions.submitCohort()
- }).toDispatchActions([
- 'setCohort',
- 'submitCohort',
- 'submitCohortSuccess',
- 'saveCohortSuccess',
- 'loadUsedIn',
- ])
+ })
+ .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortSuccess', 'saveCohortSuccess'])
+ .toNotHaveDispatchedActions(['loadUsedIn'])
expect(api.update).toHaveBeenCalledTimes(1)
})
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index d8cf43ca1c9f..acbc934d0ba9 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -609,7 +609,8 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
if (!(error instanceof ApiError) || error.status !== 404) {
posthog.captureException(error, { feature: 'cohort-used-in' })
}
- return null
+ // Keep any previously loaded value so a failed refresh doesn't blank the banner.
+ return values.usedIn
}
},
},
@@ -661,11 +662,6 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
'There was an error submitting this cohort. Make sure the cohort filters are correct.',
})
},
- // Refresh once the save request actually resolves; submitCohortSuccess fires as soon
- // as the synchronous submit handler dispatches saveCohort.
- saveCohortSuccess: () => {
- actions.loadUsedIn()
- },
checkIfFinishedCalculating: async ({ cohort }, breakpoint) => {
const isPendingCalculation = checkIsPendingCalculation(cohort)
const isCalculatingOrPending = cohort.is_calculating || isPendingCalculation
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 9e8dbd80e4c1..86d835509130 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -1177,6 +1177,11 @@ class CohortSerializer(serializers.ModelSerializer):
return representation
+def _used_in_block(page: list[dict], total: int) -> dict[str, Any]:
+ """Build one ``{results, total, has_more}`` block of the used_in response."""
+ return {"results": page, "total": total, "has_more": total > len(page)}
+
+
def _truncate_used_in_queryset(qs: QuerySet) -> tuple[list[dict], int]:
"""Return up to COHORT_USED_IN_PAGE_SIZE rows plus the total count.
@@ -1190,32 +1195,79 @@ def _truncate_used_in_queryset(qs: QuerySet) -> tuple[list[dict], int]:
return page[:COHORT_USED_IN_PAGE_SIZE], qs.count()
-def get_active_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:
- """Return active, non-deleted feature flags that reference this cohort.
+def _flags_with_cohort_filters(cohort: Cohort) -> QuerySet[FeatureFlag]:
+ """Return non-deleted flags in the cohort's project whose filters contain any cohort property.
+
+ DB-side pre-filter for the ``get_cohort_ids()`` expansion in the callers below, so
+ only flags that reference some cohort are loaded into Python instead of every flag
+ in the project. Matching any cohort-type property — rather than this specific cohort
+ id — is required for correctness: a flag that only transitively references this
+ cohort (via another cohort) still directly references some cohort, so this predicate
+ is a strict superset of the flags the expansion can match.
+ """
+ return (
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static predicate, no user input)
+ FeatureFlag.objects.filter(team__project_id=cohort.team.project_id, deleted=False)
+ .extra(where=["""jsonb_path_exists(filters, '$.** ? (@.type == "cohort")')"""])
+ .select_related("team")
+ )
+
- Used by deletion protection — only live flags should block cohort deletion.
+def _directly_referenced_cohort_ids(flags: list[FeatureFlag]) -> set[int]:
+ """Cohort ids each flag references directly in its filter conditions.
+
+ Mirrors the cohort-property walk in ``FeatureFlag.get_cohort_ids``, used to bulk-load
+ those cohorts so the expansion doesn't point-query them one at a time.
+ """
+ return {
+ int(prop["value"])
+ for flag in flags
+ for condition in flag.conditions
+ for prop in condition.get("properties", [])
+ if prop.get("type") == "cohort" and str(prop.get("value")).lstrip("-").isdigit()
+ }
+
+
+def _filter_flags_referencing_cohort(flags: QuerySet[FeatureFlag], cohort: Cohort) -> list[FeatureFlag]:
+ """Expand each flag's cohort references in Python and keep flags that reach this cohort.
+
+ The cache is seeded with the target cohort and bulk-loaded with every cohort the
+ flags reference directly, so ``get_cohort_ids()`` only point-queries for cohorts
+ nested behind another cohort's filters. Seeding the target also means a soft-deleted
+ target still resolves: ``used_in`` reports flags referencing a deleted cohort, which
+ matches the insights and cohorts blocks (neither checks the target's deleted state).
"""
- active_flags = FeatureFlag.objects.filter(
- team__project_id=cohort.team.project_id, active=True, deleted=False
- ).select_related("team")
- seen_cohorts_cache: dict[int, CohortOrEmpty] = {}
- return [flag for flag in active_flags if cohort.id in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache)]
+ flag_list = list(flags)
+ seen_cohorts_cache: dict[int, CohortOrEmpty] = {cohort.id: cohort}
+ direct_ids = _directly_referenced_cohort_ids(flag_list) - seen_cohorts_cache.keys()
+ if direct_ids:
+ for direct_cohort in Cohort.objects.filter(
+ pk__in=direct_ids, team__project_id=cohort.team.project_id, deleted=False
+ ):
+ seen_cohorts_cache[direct_cohort.pk] = direct_cohort
+ for missing_id in direct_ids - seen_cohorts_cache.keys():
+ seen_cohorts_cache[missing_id] = ""
+ return [flag for flag in flag_list if cohort.id in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache)]
-def get_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:
- """Return all non-deleted feature flags (active or inactive) that reference this cohort.
+def get_active_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:
+ """Return active, non-deleted feature flags that reference this cohort.
- Used by the informational ``used_in`` endpoint — surfaces inactive flags too so users
- are aware before flipping one back on. Excludes soft-deleted flags for consistency
- with ``get_insights_using_cohort`` and ``get_cohorts_using_cohort``.
+ Used by deletion protection: only live flags should block cohort deletion.
"""
- flags = FeatureFlag.objects.filter(team__project_id=cohort.team.project_id, deleted=False).select_related("team")
- seen_cohorts_cache: dict[int, CohortOrEmpty] = {}
- return [flag for flag in flags if cohort.id in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache)]
+ return _filter_flags_referencing_cohort(_flags_with_cohort_filters(cohort).filter(active=True), cohort)
def get_insights_using_cohort(cohort: Cohort) -> QuerySet[Insight]:
- """Return insights that reference this cohort in their query filters or breakdown."""
+ """Return insights that reference this cohort in their query filters or breakdown.
+
+ The LIKE guard is load-bearing: any insight the jsonpath or breakdown branch can
+ match necessarily contains the literal ``"cohort"`` in its query JSON, so the guard
+ is a strict superset that short-circuits the recursive (un-indexable) jsonpath for
+ insights mentioning no cohort at all. It also keeps the planner's row estimate
+ selective; without it, ORDER BY/LIMIT on large teams degrades to a whole-table
+ primary-key walk.
+ """
return (
# nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
Insight.objects.filter(
@@ -1224,11 +1276,16 @@ def get_insights_using_cohort(cohort: Cohort) -> QuerySet[Insight]:
)
.extra(
where=[
- """jsonb_path_exists(query, '$.** ? (@.type == "cohort" && @.value == %s)', '{"cohort_id": %s}'::jsonb)
- OR (query->'source'->'breakdownFilter'->>'breakdown_type' = 'cohort'
- AND query->'source'->'breakdownFilter'->'breakdown' @> '[%s]'::jsonb)"""
+ """query::text LIKE %s
+ AND (
+ jsonb_path_exists(query, '$.** ? (@.type == "cohort" && @.value == %s)', '{"cohort_id": %s}'::jsonb)
+ OR (
+ query->'source'->'breakdownFilter'->>'breakdown_type' = 'cohort'
+ AND query->'source'->'breakdownFilter'->'breakdown' @> '[%s]'::jsonb
+ )
+ )"""
],
- params=[cohort.id, cohort.id, cohort.id],
+ params=['%"cohort"%', cohort.id, cohort.id, cohort.id],
)
.order_by("id")
)
@@ -1672,13 +1729,13 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
# access-level filtering on the flag/insight list endpoints.
uac = self.user_access_control
- flag_ids = [flag.id for flag in get_flags_using_cohort(cohort)]
+ # Access-filter before the Python-side expansion so denied flags are never
+ # loaded or expanded.
flags_qs = uac.filter_queryset_by_access_level(
- # nosemgrep: idor-lookup-without-team (flag_ids are already team-scoped via get_flags_using_cohort)
- FeatureFlag.objects.filter(id__in=flag_ids),
- include_all_if_admin=True,
+ _flags_with_cohort_filters(cohort), include_all_if_admin=True
).order_by("id")
- flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name} for flag in flags_qs]
+ flags = _filter_flags_referencing_cohort(flags_qs, cohort)
+ flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name} for flag in flags]
insights_qs = uac.filter_queryset_by_access_level(get_insights_using_cohort(cohort))
insights_page, insights_total = _truncate_used_in_queryset(
@@ -1699,21 +1756,9 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
return Response(
{
- "feature_flags": {
- "results": flags_data[:COHORT_USED_IN_PAGE_SIZE],
- "total": len(flags_data),
- "has_more": len(flags_data) > COHORT_USED_IN_PAGE_SIZE,
- },
- "insights": {
- "results": insights_data,
- "total": insights_total,
- "has_more": insights_total > len(insights_data),
- },
- "cohorts": {
- "results": cohorts_data,
- "total": cohorts_total,
- "has_more": cohorts_total > len(cohorts_data),
- },
+ "feature_flags": _used_in_block(flags_data[:COHORT_USED_IN_PAGE_SIZE], len(flags_data)),
+ "insights": _used_in_block(insights_data, insights_total),
+ "cohorts": _used_in_block(cohorts_data, cohorts_total),
}
)
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 91748b11e226..c01387759c43 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -5256,6 +5256,39 @@ [email protected],
class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):
+ def _create_flag_referencing_cohort_transitively(self) -> tuple[int, int]:
+ # Cohort B references cohort A; the flag references only cohort B directly.
+ # Returns (cohort_a_id, cohort_b_id).
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Cohort A", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_a_id = response.json()["id"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={
+ "name": "Cohort B",
+ "filters": {
+ "properties": {
+ "type": "OR",
+ "values": [{"type": "OR", "values": [{"type": "cohort", "key": "id", "value": cohort_a_id}]}],
+ }
+ },
+ },
+ )
+ cohort_b_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_b_id, "type": "cohort"}]}]},
+ name="Transitive Flag",
+ key="transitive-flag",
+ created_by=self.user,
+ active=True,
+ )
+ return cohort_a_id, cohort_b_id
+
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
def test_used_in_returns_feature_flags(self, patch_calculate_cohort, patch_capture):
@@ -5327,6 +5360,107 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(flags), 1)
self.assertEqual(flags[0]["key"], "inactive-flag")
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_returns_flags_referencing_cohort_transitively(self, patch_calculate_cohort, patch_capture):
+ # The flag references only cohort B directly; it must still show up for cohort A.
+ cohort_a_id, _ = self._create_flag_referencing_cohort_transitively()
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_a_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ flags = response.json()["feature_flags"]["results"]
+ self.assertEqual(len(flags), 1)
+ self.assertEqual(flags[0]["key"], "transitive-flag")
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_excludes_flags_referencing_a_different_cohort(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Target Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ target_id = response.json()["id"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Other Cohort", "groups": [{"properties": {"team_id": 6}}]},
+ )
+ other_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": target_id, "type": "cohort"}]}]},
+ name="Matching Flag",
+ key="matching-flag",
+ created_by=self.user,
+ active=True,
+ )
+ # This flag passes the any-cohort pre-filter but must be dropped by the expansion.
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": other_id, "type": "cohort"}]}]},
+ name="Other Flag",
+ key="other-cohort-flag",
+ created_by=self.user,
+ active=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{target_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ flags = response.json()["feature_flags"]
+ self.assertEqual([flag["key"] for flag in flags["results"]], ["matching-flag"])
+ self.assertEqual(flags["total"], 1)
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_returns_flags_for_soft_deleted_cohort(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Doomed Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ # Inactive, so it doesn't block deletion but still appears in used_in.
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="Lingering Flag",
+ key="lingering-flag",
+ created_by=self.user,
+ active=False,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}",
+ data={"deleted": True},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ flags = response.json()["feature_flags"]
+ self.assertEqual([flag["key"] for flag in flags["results"]], ["lingering-flag"])
+ self.assertEqual(flags["total"], 1)
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_excludes_flag_through_soft_deleted_intermediate_cohort(
+ self, patch_calculate_cohort, patch_capture
+ ):
+ # Flag → cohort B → cohort A. Soft-deleting B breaks the B→A hop, so the flag drops
+ # out of A's used_in. Pins the cache-seeding behavior, which matches master.
+ cohort_a_id, cohort_b_id = self._create_flag_referencing_cohort_transitively()
+
+ # Soft-delete the intermediate directly: the API delete guard would block it because
+ # the active flag references B.
+ Cohort.objects.filter(id=cohort_b_id).update(deleted=True)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_a_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ flags = response.json()["feature_flags"]
+ self.assertEqual(flags["results"], [])
+ self.assertEqual(flags["total"], 0)
+
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
def test_used_in_returns_dependent_cohorts(self, patch_calculate_cohort, patch_capture):
@@ -5690,6 +5824,22 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_deletion_protection_blocks_on_transitively_referencing_flag(self, patch_calculate_cohort, patch_capture):
+ # The flag references only cohort B directly; deleting cohort A must still be blocked.
+ cohort_a_id, _ = self._create_flag_referencing_cohort_transitively()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort_a_id}",
+ data={"deleted": True},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn(
+ "This cohort is used in 1 active feature flag(s): Transitive Flag",
+ response.json()["detail"],
+ )
+
class TestCalculateCohortCommand(APIBaseTest):
def test_calculate_cohort_command_success(self):