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.

feat(cohorts): add used-in references endpoint and UI (#54738)

Ricardothe3rd8e4796c2d9a8
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 3764dab71520..86a88ff834b6 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -39,7 +39,9 @@ import {
} from '~/layout/scenes/SceneLayout'
import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'
import { Query } from '~/queries/Query/Query'
-import { ActivityScope, CohortType, SidePanelTab } from '~/types'
+import { ActivityScope, CohortType, InsightShortId, SidePanelTab } from '~/types'
+
+import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
import { AddPersonToCohortModal } from './AddPersonToCohortModal'
import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
@@ -51,6 +53,65 @@ import { PersonDisplayNameType, RemovePersonFromCohortButton } from './RemovePer
const RESOURCE_TYPE = 'cohort'
+function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Element | null {
+ const sections = [
+ {
+ title: 'Feature flags',
+ block: usedIn.feature_flags,
+ items: usedIn.feature_flags.results.map((flag) => ({
+ key: `flag-${flag.id}`,
+ url: urls.featureFlag(flag.id),
+ label: flag.name || flag.key,
+ })),
+ },
+ {
+ title: 'Insights',
+ block: usedIn.insights,
+ items: usedIn.insights.results.map((insight) => ({
+ key: `insight-${insight.id}`,
+ url: urls.insightView(insight.short_id as InsightShortId),
+ label: insight.name,
+ })),
+ },
+ {
+ title: 'Cohorts',
+ block: usedIn.cohorts,
+ items: usedIn.cohorts.results.map((c) => ({
+ key: `cohort-${c.id}`,
+ url: urls.cohort(c.id),
+ label: c.name,
+ })),
+ },
+ ].filter((section) => section.items.length > 0)
+
+ if (sections.length === 0) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="info">
+ <h4 className="font-semibold mb-1">Used in</h4>
+ <div className="space-y-2">
+ {sections.map(({ title, block, items }) => (
+ <div key={title}>
+ <h5 className="text-xs font-semibold uppercase opacity-60 mb-0">
+ {title}
+ {block.has_more && ` (${block.results.length} of ${block.total} shown)`}
+ </h5>
+ <ul className="list-disc pl-4 mb-0 space-y-0.5">
+ {items.map(({ key, url, label }) => (
+ <li key={key}>
+ <Link to={url}>{label}</Link>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </LemonBanner>
+ )
+}
+
export interface CohortEditProps {
id?: CohortType['id']
attachTo?: BuiltLogic<Logic> | LogicWrapper<Logic>
@@ -97,6 +158,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
canRemovePersonFromCohort,
isPendingCalculation,
isCalculatingOrPending,
+ usedIn,
staticCohortMode,
activeTab,
} = useValues(logic)
@@ -429,6 +491,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</div>
</div>
</SceneSection>
+ {!isNewCohort && usedIn && <UsedInBanner usedIn={usedIn} />}
{cohort.is_static && staticCohortMode === 'criteria' ? (
<>
<SceneDivider />
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 3d5a82fef236..b4dc833ffbab 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -43,6 +43,16 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
},
}))
+const mockUsedInResponse = {
+ feature_flags: {
+ results: [{ id: 7, key: 'my-flag', name: 'My Flag' }],
+ total: 1,
+ has_more: false,
+ },
+ insights: { results: [], total: 0, has_more: false },
+ cohorts: { results: [], total: 0, has_more: false },
+}
+
describe('cohortEditLogic', () => {
let logic: ReturnType<typeof cohortEditLogic.build>
async function initCohortLogic(props: CohortLogicProps = { id: 'new' }): Promise<void> {
@@ -64,6 +74,7 @@ describe('cohortEditLogic', () => {
get: {
'/api/projects/:team_id/cohorts/': toPaginatedResponse([mockCohort]),
'/api/projects/:team_id/cohorts/:id/': mockCohort,
+ '/api/projects/:team_id/cohorts/:id/used_in/': mockUsedInResponse,
},
post: {
'/api/projects/:team_id/cohorts/': mockCohort,
@@ -81,7 +92,15 @@ describe('cohortEditLogic', () => {
await initCohortLogic({ id: 1 })
await expectLogic(logic).toDispatchActions(['fetchCohort'])
- expect(api.get).toHaveBeenCalledTimes(1)
+ // One call for the cohort itself, one for its used-in references
+ expect(api.get).toHaveBeenCalledTimes(2)
+ })
+
+ it('loads used-in references on mount before the cohort has resolved', async () => {
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+
+ expect(logic.values.usedIn).toEqual(mockUsedInResponse)
})
it('loads new cohort on mount', async () => {
@@ -158,7 +177,13 @@ describe('cohortEditLogic', () => {
},
})
logic.actions.submitCohort()
- }).toDispatchActions(['setCohort', 'submitCohort', 'submitCohortSuccess'])
+ }).toDispatchActions([
+ 'setCohort',
+ 'submitCohort',
+ 'submitCohortSuccess',
+ 'saveCohortSuccess',
+ 'loadUsedIn',
+ ])
expect(api.update).toHaveBeenCalledTimes(1)
})
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 963e4b1d45d7..d8cf43ca1c9f 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -19,6 +19,7 @@ import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { ENTITY_MATCH_TYPE } from 'lib/constants'
@@ -38,6 +39,7 @@ import {
validateGroup,
} from 'scenes/cohorts/cohortUtils'
import { personsLogic } from 'scenes/persons/personsLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
@@ -59,6 +61,9 @@ import {
PropertyType,
} from '~/types'
+import { cohortsUsedInRetrieve } from 'products/cohorts/frontend/generated/api'
+import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
+
import type { cohortEditLogicType } from './cohortEditLogicType'
export type CohortLogicProps = {
@@ -89,6 +94,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
key((props) => (props.id === 'new' || !props.id ? 'new' : props.id)),
path(['scenes', 'cohorts', 'cohortLogicEdit']),
connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
actions: [eventUsageLogic, ['reportExperimentExposureCohortEdited']],
logic: [cohortsModel],
})),
@@ -369,7 +375,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
},
})),
- loaders(({ actions, values, key }) => ({
+ loaders(({ actions, values, key, props }) => ({
cohort: [
NEW_COHORT,
{
@@ -584,6 +590,30 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
},
},
],
+
+ usedIn: [
+ null as CohortUsedInResponseApi | null,
+ {
+ loadUsedIn: async () => {
+ // On mount `values.cohort` is still NEW_COHORT (fetchCohort hasn't resolved),
+ // so fall back to the id from props.
+ const id = values.cohort.id !== 'new' ? values.cohort.id : props.id
+ if (!id || id === 'new') {
+ return null
+ }
+ try {
+ return await cohortsUsedInRetrieve(String(values.currentProjectId), Number(id))
+ } catch (error) {
+ // A 404 just means the endpoint isn't deployed yet (deploy skew) or the
+ // cohort is gone; neither is worth reporting.
+ if (!(error instanceof ApiError) || error.status !== 404) {
+ posthog.captureException(error, { feature: 'cohort-used-in' })
+ }
+ return null
+ }
+ },
+ },
+ ],
})),
listeners(({ actions, values }) => ({
setCriteria: ({ newCriteria, groupIndex, criteriaIndex }) => {
@@ -631,6 +661,11 @@ 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
@@ -713,6 +748,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
}
} else {
actions.fetchCohort(props.id)
+ actions.loadUsedIn()
}
}),
beforeUnmount(({ values }) => {
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 6a3cdcb2bcd1..bf6248a864d6 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -390,6 +390,67 @@ class RemovePersonRequestSerializer(serializers.Serializer):
person_id = serializers.UUIDField(required=True, help_text="Person UUID to remove from the cohort")
+COHORT_USED_IN_PAGE_SIZE = 100
+
+
+class CohortUsedInFlagSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="Feature flag database ID")
+ key = serializers.CharField(help_text="Feature flag key (URL slug)")
+ name = serializers.CharField(allow_null=True, allow_blank=True, help_text="Feature flag display name")
+
+
+class CohortUsedInInsightSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="Insight database ID")
+ short_id = serializers.CharField(help_text="Insight short ID used for routing in the frontend")
+ name = serializers.CharField(
+ help_text="Insight display name; falls back to derived name, then to 'Unnamed' when both are empty"
+ )
+
+
+class CohortUsedInCohortSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="Cohort database ID")
+ name = serializers.CharField(help_text="Cohort display name; falls back to 'Unnamed' when empty")
+
+
+class CohortUsedInFlagsBlockSerializer(serializers.Serializer):
+ results = CohortUsedInFlagSerializer(
+ many=True, help_text=f"Feature flags referencing this cohort, capped at {COHORT_USED_IN_PAGE_SIZE} results"
+ )
+ total = serializers.IntegerField(
+ help_text="Total number of feature flags referencing this cohort, before truncation"
+ )
+ has_more = serializers.BooleanField(help_text="True when more feature flags exist beyond the truncation cap")
+
+
+class CohortUsedInInsightsBlockSerializer(serializers.Serializer):
+ results = CohortUsedInInsightSerializer(
+ many=True, help_text=f"Insights referencing this cohort, capped at {COHORT_USED_IN_PAGE_SIZE} results"
+ )
+ total = serializers.IntegerField(help_text="Total number of insights referencing this cohort, before truncation")
+ has_more = serializers.BooleanField(help_text="True when more insights exist beyond the truncation cap")
+
+
+class CohortUsedInCohortsBlockSerializer(serializers.Serializer):
+ results = CohortUsedInCohortSerializer(
+ many=True,
+ help_text=f"Cohorts that include this cohort as a criterion, capped at {COHORT_USED_IN_PAGE_SIZE} results",
+ )
+ total = serializers.IntegerField(help_text="Total number of cohorts referencing this cohort, before truncation")
+ has_more = serializers.BooleanField(help_text="True when more cohorts exist beyond the truncation cap")
+
+
+class CohortUsedInResponseSerializer(serializers.Serializer):
+ feature_flags = CohortUsedInFlagsBlockSerializer(
+ help_text="Feature flags (active and inactive, excluding soft-deleted) that reference this cohort in their targeting conditions, with truncation metadata",
+ )
+ insights = CohortUsedInInsightsBlockSerializer(
+ help_text="Insights referencing this cohort with truncation metadata"
+ )
+ cohorts = CohortUsedInCohortsBlockSerializer(
+ help_text="Other cohorts that include this cohort as a criterion, with truncation metadata"
+ )
+
+
class CohortCalculationHistorySerializer(serializers.ModelSerializer):
duration_seconds = serializers.ReadOnlyField()
is_completed = serializers.ReadOnlyField()
@@ -994,8 +1055,7 @@ class CohortSerializer(serializers.ModelSerializer):
is_deletion_change = deleted_state is not None and cohort.deleted != deleted_state
if is_deletion_change:
if deleted_state:
- flags_using_cohort = FeatureFlag.objects.filter(team__project_id=cohort.team.project_id, active=True)
- flags_with_cohort = [flag for flag in flags_using_cohort if cohort.id in flag.get_cohort_ids()]
+ flags_with_cohort = get_active_flags_using_cohort(cohort)
if flags_with_cohort:
flag_names = [flag.name or flag.key for flag in flags_with_cohort]
raise ValidationError(
@@ -1023,21 +1083,7 @@ class CohortSerializer(serializers.ModelSerializer):
)
# Check if cohort is used in insights
-
- # Use PostgreSQL's jsonb_path_exists for recursive JSONB searching
- # This finds cohort references at any depth in the JSON structure
- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
- insights_using_cohort = Insight.objects.filter(
- team_id=cohort.team_id,
- deleted=False,
- ).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)"""
- ],
- params=[cohort.id, cohort.id, cohort.id],
- )
+ insights_using_cohort = get_insights_using_cohort(cohort)
if insights_using_cohort.exists():
count = insights_using_cohort.count()
@@ -1053,24 +1099,11 @@ class CohortSerializer(serializers.ModelSerializer):
)
# Check if cohort is used as criteria in other cohorts
- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
- dependent_cohorts = (
- Cohort.objects.filter(
- team__project_id=cohort.team.project_id,
- deleted=False,
- )
- .exclude(id=cohort.id)
- .extra(
- where=[
- """jsonb_path_exists(filters, '$.** ? (@.type == "cohort" && @.value == %s)', '{"cohort_id": %s}'::jsonb)"""
- ],
- params=[cohort.id, cohort.id],
- )
- )
+ dependent_cohorts = get_cohorts_using_cohort(cohort)
if dependent_cohorts.exists():
count = dependent_cohorts.count()
- cohort_names = [c.name for c in dependent_cohorts[:5]]
+ cohort_names = [c.name or "Unnamed" for c in dependent_cohorts[:5]]
names_str = ", ".join(cohort_names)
if count > 5:
names_str = f"{names_str}, and {count - 5} more"
@@ -1147,6 +1180,82 @@ class CohortSerializer(serializers.ModelSerializer):
return representation
+def _truncate_used_in_queryset(qs: QuerySet) -> tuple[list[dict], int]:
+ """Return up to COHORT_USED_IN_PAGE_SIZE rows plus the total count.
+
+ Fetches one row past the cap so the common short-list case derives the total
+ from the page itself; the expensive predicate only runs a second time (via
+ ``count()``) when the cap is actually exceeded.
+ """
+ page = list(qs[: COHORT_USED_IN_PAGE_SIZE + 1])
+ if len(page) <= COHORT_USED_IN_PAGE_SIZE:
+ return page, len(page)
+ 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.
+
+ Used by deletion protection — only live flags should block cohort deletion.
+ """
+ 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)]
+
+
+def get_flags_using_cohort(cohort: Cohort) -> list[FeatureFlag]:
+ """Return all non-deleted feature flags (active or inactive) 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``.
+ """
+ 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)]
+
+
+def get_insights_using_cohort(cohort: Cohort) -> QuerySet[Insight]:
+ """Return insights that reference this cohort in their query filters or breakdown."""
+ return (
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
+ Insight.objects.filter(
+ team_id=cohort.team_id,
+ deleted=False,
+ )
+ .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)"""
+ ],
+ params=[cohort.id, cohort.id, cohort.id],
+ )
+ .order_by("id")
+ )
+
+
+def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:
+ """Return other cohorts that include this cohort as criteria."""
+ return (
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
+ Cohort.objects.filter(
+ team__project_id=cohort.team.project_id,
+ deleted=False,
+ )
+ .exclude(id=cohort.id)
+ .extra(
+ where=[
+ """jsonb_path_exists(filters, '$.** ? (@.type == "cohort" && @.value == %s)', '{"cohort_id": %s}'::jsonb)"""
+ ],
+ params=[cohort.id, cohort.id],
+ )
+ .order_by("id")
+ )
+
+
@extend_schema_view(
list=extend_schema(
parameters=[
@@ -1557,6 +1666,59 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
}
)
+ @extend_schema(responses=CohortUsedInResponseSerializer)
+ @action(methods=["GET"], detail=True, required_scopes=["cohort:read"])
+ def used_in(self, request: request.Request, **kwargs) -> Response:
+ cohort: Cohort = self.get_object()
+ # Hide references the caller has been denied at the object level, matching the
+ # 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)]
+ 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,
+ ).order_by("id")
+ flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name} for flag in flags_qs]
+
+ insights_qs = uac.filter_queryset_by_access_level(get_insights_using_cohort(cohort))
+ insights_page, insights_total = _truncate_used_in_queryset(
+ insights_qs.values("id", "short_id", "name", "derived_name")
+ )
+ insights_data = [
+ {
+ "id": insight["id"],
+ "short_id": insight["short_id"],
+ "name": insight.get("name") or insight.get("derived_name") or "Unnamed",
+ }
+ for insight in insights_page
+ ]
+
+ cohorts_qs = uac.filter_queryset_by_access_level(get_cohorts_using_cohort(cohort))
+ cohorts_page, cohorts_total = _truncate_used_in_queryset(cohorts_qs.values("id", "name"))
+ cohorts_data = [{"id": c["id"], "name": c["name"] or "Unnamed"} for c in cohorts_page]
+
+ 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),
+ },
+ }
+ )
+
def perform_create(self, serializer):
serializer.save()
instance = cast(Cohort, serializer.instance)
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 335ed7b628b5..91748b11e226 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -9,6 +9,7 @@ from posthog.test.base import (
_create_event,
_create_person,
flush_persons_and_events,
+ setup_test_organization_team_and_user,
)
from unittest import mock
from unittest.mock import ANY, MagicMock, patch
@@ -23,7 +24,7 @@ from rest_framework import status
from posthog.schema import PersonsOnEventsMode, PropertyOperator
-from posthog.api.cohort import CohortViewSet
+from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortViewSet
from posthog.clickhouse.client.execute import sync_execute
from posthog.models import Person, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -43,6 +44,7 @@ from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.exports.backend.api.test.test_exports import TestExportMixin
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
from ee.clickhouse.materialized_columns.analyze import materialize
@@ -5253,6 +5255,442 @@ [email protected],
self.assertIn("too much memory", response.json()["last_error_message"].lower())
+class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):
+ @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):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Target Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="My Flag",
+ key="my-flag",
+ created_by=self.user,
+ active=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ data = response.json()
+ self.assertEqual(len(data["feature_flags"]["results"]), 1)
+ self.assertEqual(data["feature_flags"]["total"], 1)
+ self.assertFalse(data["feature_flags"]["has_more"])
+ self.assertEqual(data["feature_flags"]["results"][0]["key"], "my-flag")
+ self.assertEqual(data["feature_flags"]["results"][0]["name"], "My Flag")
+ self.assertEqual(data["insights"], {"results": [], "total": 0, "has_more": False})
+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False})
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_returns_empty_when_not_referenced(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Lonely Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ data = response.json()
+ self.assertEqual(data["feature_flags"], {"results": [], "total": 0, "has_more": False})
+ self.assertEqual(data["insights"], {"results": [], "total": 0, "has_more": False})
+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False})
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_includes_inactive_flags(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}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="Inactive Flag",
+ key="inactive-flag",
+ created_by=self.user,
+ active=False,
+ )
+
+ 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"]["results"]
+ 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_dependent_cohorts(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Inner Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ inner_cohort_id = response.json()["id"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={
+ "name": "Outer Cohort",
+ "filters": {
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "OR",
+ "values": [{"type": "cohort", "key": "id", "value": inner_cohort_id}],
+ }
+ ],
+ }
+ },
+ },
+ )
+ outer_cohort_id = response.json()["id"]
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{inner_cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ data = response.json()
+ self.assertEqual(data["cohorts"]["total"], 1)
+ self.assertFalse(data["cohorts"]["has_more"])
+ self.assertEqual(len(data["cohorts"]["results"]), 1)
+ self.assertEqual(data["cohorts"]["results"][0]["id"], outer_cohort_id)
+ self.assertEqual(data["cohorts"]["results"][0]["name"], "Outer Cohort")
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_includes_insight_via_jsonb_path(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}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Insight Referencing Cohort",
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "properties": [{"type": "cohort", "key": "id", "value": cohort_id}],
+ },
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["insights"]["total"], 1)
+ self.assertEqual(len(data["insights"]["results"]), 1)
+ self.assertEqual(data["insights"]["results"][0]["id"], insight.id)
+ self.assertEqual(data["insights"]["results"][0]["name"], "Insight Referencing Cohort")
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_includes_insight_via_breakdown(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Breakdown Target Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Trends With Cohort Breakdown",
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "breakdownFilter": {"breakdown_type": "cohort", "breakdown": [cohort_id]},
+ },
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["insights"]["total"], 1)
+ self.assertEqual(len(data["insights"]["results"]), 1)
+ self.assertEqual(data["insights"]["results"][0]["id"], insight.id)
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_falls_back_to_derived_name_then_unnamed(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Naming Target", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+ cohort_query = {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "properties": [{"type": "cohort", "key": "id", "value": cohort_id}],
+ },
+ }
+
+ Insight.objects.create(team=self.team, name="Has Name", query=cohort_query)
+ Insight.objects.create(team=self.team, name="", derived_name="Falls Back", query=cohort_query)
+ Insight.objects.create(team=self.team, name="", derived_name="", query=cohort_query)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ names = sorted(r["name"] for r in response.json()["insights"]["results"])
+ self.assertEqual(names, ["Falls Back", "Has Name", "Unnamed"])
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_truncates_insights_with_has_more_signal(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Many Refs Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+ cohort_query = {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "properties": [{"type": "cohort", "key": "id", "value": cohort_id}],
+ },
+ }
+
+ for i in range(COHORT_USED_IN_PAGE_SIZE + 1):
+ Insight.objects.create(team=self.team, name=f"Insight {i}", query=cohort_query)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ block = response.json()["insights"]
+ self.assertEqual(len(block["results"]), COHORT_USED_IN_PAGE_SIZE)
+ self.assertEqual(block["total"], COHORT_USED_IN_PAGE_SIZE + 1)
+ self.assertTrue(block["has_more"])
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_truncates_cohorts_with_has_more_signal(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Inner Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ inner_cohort_id = response.json()["id"]
+ dependent_filters = {
+ "properties": {
+ "type": "OR",
+ "values": [{"type": "OR", "values": [{"type": "cohort", "key": "id", "value": inner_cohort_id}]}],
+ }
+ }
+
+ for i in range(COHORT_USED_IN_PAGE_SIZE + 1):
+ Cohort.objects.create(team=self.team, name=f"Dependent {i}", filters=dependent_filters)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{inner_cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ block = response.json()["cohorts"]
+ self.assertEqual(len(block["results"]), COHORT_USED_IN_PAGE_SIZE)
+ self.assertEqual(block["total"], COHORT_USED_IN_PAGE_SIZE + 1)
+ self.assertTrue(block["has_more"])
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_falls_back_to_unnamed_for_blank_cohort_name(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Inner Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ inner_cohort_id = response.json()["id"]
+
+ Cohort.objects.create(
+ team=self.team,
+ name="",
+ filters={
+ "properties": {
+ "type": "OR",
+ "values": [{"type": "OR", "values": [{"type": "cohort", "key": "id", "value": inner_cohort_id}]}],
+ }
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{inner_cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["cohorts"]["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["name"], "Unnamed")
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_excludes_insights_from_sibling_teams(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}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ other_team = Team.objects.create(organization=self.organization, project=self.team.project, name="Sibling Team")
+ Insight.objects.create(
+ team=other_team,
+ name="Sibling Insight",
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "properties": [{"type": "cohort", "key": "id", "value": cohort_id}],
+ },
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["insights"], {"results": [], "total": 0, "has_more": False})
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_excludes_references_from_other_projects(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}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ _, _, other_team, other_user, _ = setup_test_organization_team_and_user(
+ "Other Org", "other-token", "[email protected]", "password123"
+ )
+ FeatureFlag.objects.create(
+ team=other_team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="Other Project Flag",
+ key="other-project-flag",
+ created_by=other_user,
+ active=True,
+ )
+ Cohort.objects.create(
+ team=other_team,
+ name="Other Project Cohort",
+ filters={
+ "properties": {
+ "type": "OR",
+ "values": [{"type": "OR", "values": [{"type": "cohort", "key": "id", "value": cohort_id}]}],
+ }
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["feature_flags"], {"results": [], "total": 0, "has_more": False})
+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False})
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_truncates_flags_with_has_more_signal(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Many Flags Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ for i in range(COHORT_USED_IN_PAGE_SIZE + 1):
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name=f"Flag {i}",
+ key=f"flag-{i}",
+ created_by=self.user,
+ active=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ block = response.json()["feature_flags"]
+ self.assertEqual(len(block["results"]), COHORT_USED_IN_PAGE_SIZE)
+ self.assertEqual(block["total"], COHORT_USED_IN_PAGE_SIZE + 1)
+ self.assertTrue(block["has_more"])
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_deletion_protection_names_unnamed_dependent_cohorts(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Base Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ base_cohort_id = response.json()["id"]
+
+ Cohort.objects.create(
+ team=self.team,
+ name=None,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [{"type": "cohort", "key": "id", "value": base_cohort_id}],
+ }
+ },
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{base_cohort_id}",
+ 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): Unnamed",
+ response.json()["detail"],
+ )
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_used_in_excludes_soft_deleted_flags(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Cohort For Deleted Flag", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="Soft Deleted Flag",
+ key="deleted-flag",
+ created_by=self.user,
+ active=True,
+ deleted=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["feature_flags"], {"results": [], "total": 0, "has_more": False})
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_deletion_protection_still_excludes_inactive_flags(self, patch_calculate_cohort, patch_capture):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "Deletable Cohort", "groups": [{"properties": {"team_id": 5}}]},
+ )
+ cohort_id = response.json()["id"]
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},
+ name="Inactive Flag",
+ key="inactive-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())
+
+
class TestCalculateCohortCommand(APIBaseTest):
def test_calculate_cohort_command_success(self):
# Create a test cohort
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 2e462f738393..f685eed916bb 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -310,6 +310,70 @@ export interface PatchedRemovePersonRequestApi {
person_id?: string
}
+export interface CohortUsedInFlagApi {
+ /** Feature flag database ID */
+ id: number
+ /** Feature flag key (URL slug) */
+ key: string
+ /**
+ * Feature flag display name
+ * @nullable
+ */
+ name: string | null
+}
+
+export interface CohortUsedInFlagsBlockApi {
+ /** Feature flags referencing this cohort, capped at 100 results */
+ results: CohortUsedInFlagApi[]
+ /** Total number of feature flags referencing this cohort, before truncation */
+ total: number
+ /** True when more feature flags exist beyond the truncation cap */
+ has_more: boolean
+}
+
+export interface CohortUsedInInsightApi {
+ /** Insight database ID */
+ id: number
+ /** Insight short ID used for routing in the frontend */
+ short_id: string
+ /** Insight display name; falls back to derived name, then to 'Unnamed' when both are empty */
+ name: string
+}
+
+export interface CohortUsedInInsightsBlockApi {
+ /** Insights referencing this cohort, capped at 100 results */
+ results: CohortUsedInInsightApi[]
+ /** Total number of insights referencing this cohort, before truncation */
+ total: number
+ /** True when more insights exist beyond the truncation cap */
+ has_more: boolean
+}
+
+export interface CohortUsedInCohortApi {
+ /** Cohort database ID */
+ id: number
+ /** Cohort display name; falls back to 'Unnamed' when empty */
+ name: string
+}
+
+export interface CohortUsedInCohortsBlockApi {
+ /** Cohorts that include this cohort as a criterion, capped at 100 results */
+ results: CohortUsedInCohortApi[]
+ /** Total number of cohorts referencing this cohort, before truncation */
+ total: number
+ /** True when more cohorts exist beyond the truncation cap */
+ has_more: boolean
+}
+
+export interface CohortUsedInResponseApi {
+ /** Feature flags (active and inactive, excluding soft-deleted) that reference this cohort in their targeting conditions, with truncation metadata */
+ feature_flags: CohortUsedInFlagsBlockApi
+ /** Insights referencing this cohort with truncation metadata */
+ insights: CohortUsedInInsightsBlockApi
+ /** Other cohorts that include this cohort as a criterion, with truncation metadata */
+ cohorts: CohortUsedInCohortsBlockApi
+}
+
export type CohortsListParams = {
/**
* Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.
diff --git a/products/cohorts/frontend/generated/api.ts b/products/cohorts/frontend/generated/api.ts
index f25985e19bd0..5f0a32774d6a 100644
--- a/products/cohorts/frontend/generated/api.ts
+++ b/products/cohorts/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
CohortApi,
CohortPersonsResponseApi,
+ CohortUsedInResponseApi,
CohortsListParams,
CohortsPersonsRetrieveParams,
PaginatedCohortListApi,
@@ -231,6 +232,21 @@ export const cohortsRemovePersonFromStaticCohortPartialUpdate = async (
})
}
+export const getCohortsUsedInRetrieveUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/cohorts/${id}/used_in/`
+}
+
+export const cohortsUsedInRetrieve = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<CohortUsedInResponseApi> => {
+ return apiMutator<CohortUsedInResponseApi>(getCohortsUsedInRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCohortsAllActivityRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/cohorts/activity/`
}
diff --git a/products/cohorts/mcp/tools.yaml b/products/cohorts/mcp/tools.yaml
index 7674212aec04..8c69bf7f8bca 100644
--- a/products/cohorts/mcp/tools.yaml
+++ b/products/cohorts/mcp/tools.yaml
@@ -230,6 +230,9 @@ tools:
cohorts-update:
operation: cohorts_update
enabled: false
+ cohorts-used-in-retrieve:
+ operation: cohorts_used_in_retrieve
+ enabled: false
persons-cohorts-retrieve:
operation: persons_cohorts_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index de0983a311d8..7018e83a9633 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11359,6 +11359,70 @@ export namespace Schemas {
previous: string | null;
}
+ export interface CohortUsedInCohort {
+ /** Cohort database ID */
+ id: number;
+ /** Cohort display name; falls back to 'Unnamed' when empty */
+ name: string;
+ }
+
+ export interface CohortUsedInCohortsBlock {
+ /** Cohorts that include this cohort as a criterion, capped at 100 results */
+ results: CohortUsedInCohort[];
+ /** Total number of cohorts referencing this cohort, before truncation */
+ total: number;
+ /** True when more cohorts exist beyond the truncation cap */
+ has_more: boolean;
+ }
+
+ export interface CohortUsedInFlag {
+ /** Feature flag database ID */
+ id: number;
+ /** Feature flag key (URL slug) */
+ key: string;
+ /**
+ * Feature flag display name
+ * @nullable
+ */
+ name: string | null;
+ }
+
+ export interface CohortUsedInFlagsBlock {
+ /** Feature flags referencing this cohort, capped at 100 results */
+ results: CohortUsedInFlag[];
+ /** Total number of feature flags referencing this cohort, before truncation */
+ total: number;
+ /** True when more feature flags exist beyond the truncation cap */
+ has_more: boolean;
+ }
+
+ export interface CohortUsedInInsight {
+ /** Insight database ID */
+ id: number;
+ /** Insight short ID used for routing in the frontend */
+ short_id: string;
+ /** Insight display name; falls back to derived name, then to 'Unnamed' when both are empty */
+ name: string;
+ }
+
+ export interface CohortUsedInInsightsBlock {
+ /** Insights referencing this cohort, capped at 100 results */
+ results: CohortUsedInInsight[];
+ /** Total number of insights referencing this cohort, before truncation */
+ total: number;
+ /** True when more insights exist beyond the truncation cap */
+ has_more: boolean;
+ }
+
+ export interface CohortUsedInResponse {
+ /** Feature flags (active and inactive, excluding soft-deleted) that reference this cohort in their targeting conditions, with truncation metadata */
+ feature_flags: CohortUsedInFlagsBlock;
+ /** Insights referencing this cohort with truncation metadata */
+ insights: CohortUsedInInsightsBlock;
+ /** Other cohorts that include this cohort as a criterion, with truncation metadata */
+ cohorts: CohortUsedInCohortsBlock;
+ }
+
/**
* * `private` - Private (only visible to creator)
* * `shared` - Shared with team