: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cohorts): show what blocks a cohort delete before confirming (#104035)
posthog[bot]227355fd751e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8409f6b07c5e..73b0209b7617 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13910,6 +13910,14 @@ snapshots:hash: v1.k794b7964.93a91a7c721456ea858c7daaca50b9e0e139a6cca3d4c5561766af6bdff0d446.iOwqrGTMXmqca1y1fXUHy1yrC6IAU1MG2Bp2QwUcMF0scenes-app-people-cohorts-blocking-workflows-modal--locked-from-details--light:hash: v1.k794b7964.a85e4e8e15e396a695ac820e7b5f12e090749678a37337d68f58c8ef2f3c84d1.mdB_yxx_jxgQdKnZ9yx0MqpZLGLVed12nt-qc_rElNs+ scenes-app-people-delete-cohort-dialog--blocked--dark:+ hash: v1.k794b7964.c207f2f246162cf80000cb96c0c0f06737241e7e12dee6130dd8dc2725ef0ce3.-UK9Q9-7WHMmUvLvgyX1h9LivGg52iquGoWPDQ0zciI+ scenes-app-people-delete-cohort-dialog--blocked--light:+ hash: v1.k794b7964.9e91d17bbcfb8bf7865a8df4d0869edbde76b4c5b51ad8f687ee420aee31cb10.D6nWe3lKUJ-W-J6gJMfdFAUrsqEETyaF9WlUVIjqAJs+ scenes-app-people-delete-cohort-dialog--nothing-uses-it--dark:+ hash: v1.k794b7964.1036b577e333ae40ff2ee8c0e2609ceec376629b7346bd75de99ecc961506f3e.DDcGYkamva7AsNLt4uq1aaDwe994LzINpnYXJn4yQkM+ scenes-app-people-delete-cohort-dialog--nothing-uses-it--light:+ hash: v1.k794b7964.428bcd8a708c88c2a7d7b1a818acb2519b725b4c2e7bac2645c017f07f9edff4.dJ49PgER13-hNZHFarklzAbYeGH9-1TQLUQiJc_xr_Escenes-app-people-groups--groups--dark:hash: v1.k794b7964.43aff64914fff6a42e75760dd43d3a6a389992009b996d68255cdf1edfaa4c08.J_2LUzPOjqGdvly-10vw0UsY8tOJAv6Jt76dYvjl7Gsscenes-app-people-groups--groups--light:diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex eeb2dd3950a1..ce6fa4355e04 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -14,7 +14,7 @@ import {IconTrash,IconWarning,} from '@posthog/icons'-import { LemonBanner, LemonDialog, LemonDivider, LemonSnack, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonDivider, LemonSnack, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'import { Button } from '@posthog/quill'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'@@ -36,6 +36,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { cn } from 'lib/utils/css-classes'+import { pluralize } from 'lib/utils/strings'import { StaticCohortMode, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'import { CohortCriteriaGroups } from 'scenes/cohorts/CohortFilters/CohortCriteriaGroups'import { COHORT_TYPE_OPTIONS } from 'scenes/cohorts/CohortFilters/constants'@@ -55,7 +56,7 @@ import {} from '~/layout/scenes/SceneLayout'import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'import { Query } from '~/queries/Query/Query'-import { ActivityScope, CohortType, InsightShortId, SidePanelTab } from '~/types'+import { ActivityScope, CohortType, SidePanelTab } from '~/types'import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'import { CohortRealtimeStatus } from 'products/cohorts/frontend/realtime/CohortRealtimeStatus'@@ -72,12 +73,15 @@ import { CohortBlockingWorkflowsModal } from './CohortBlockingWorkflowsModal'import { cohortCountWarningLogic } from './cohortCountWarningLogic'import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'import { CohortSceneMenuBar } from './CohortSceneMenuBar'+import { cohortUsedInSections } from './cohortUsedIn'+import { CohortUsedInList } from './CohortUsedInList'import {cohortBroadcastAudience,cohortBroadcastDisabledReason,createCohortDataNodeLogicKey,urlForCohortWorkflow,} from './cohortUtils'+import { openDeleteCohortDialog } from './DeleteCohortDialog'import { PersonSelectList } from './PersonSelectList'import { PersonDisplayNameType, RemovePersonFromCohortButton } from './RemovePersonFromCohortButton'@@ -95,45 +99,14 @@ interface UsedInSummaryProps {}function UsedInSummary({ usedIn, isExpanded, setIsExpanded }: UsedInSummaryProps): JSX.Element | null {- const sections = [- {- title: 'Feature flags',- noun: 'feature flag',- 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',- noun: 'insight',- 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',- noun: 'cohort',- 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)+ const sections = cohortUsedInSections(usedIn)if (sections.length === 0) {return null}- // `total` counts every use, while `results` stops at the API's truncation cap.- const counts = sections.map(({ block, noun }) => `${block.total} ${noun}${block.total === 1 ? '' : 's'}`)+ // `total` counts every use, while the section's items stop at the API's truncation cap.+ const counts = sections.map(({ total, noun }) => pluralize(total, noun))const summary = counts.length > 1 ? `${counts.slice(0, -1).join(', ')} and ${counts[counts.length - 1]}` : counts[0]return (@@ -150,22 +123,8 @@ function UsedInSummary({ usedIn, isExpanded, setIsExpanded }: UsedInSummaryPropsUsed in {summary}</LemonButton>{isExpanded && (- <div className="max-h-60 overflow-y-auto flex flex-col gap-y-2 pl-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">- {items.map(({ key, url, label }) => (- <li key={key}>- <Link to={url}>{label}</Link>- </li>- ))}- </ul>- </div>- ))}+ <div className="max-h-60 overflow-y-auto pl-2">+ <CohortUsedInList sections={sections} /></div>)}</div>@@ -392,20 +351,10 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {<ScenePanelActionsSection><ButtonPrimitiveonClick={() => {- LemonDialog.open({- title: 'Delete cohort?',- description: `Are you sure you want to delete "${cohort.name}"?`,- primaryButton: {- children: 'Delete',- status: 'danger',- onClick: () => deleteCohort(),- size: 'small',- },- secondaryButton: {- children: 'Cancel',- type: 'tertiary',- size: 'small',- },+ openDeleteCohortDialog({+ cohortId: cohort.id,+ cohortName: cohort.name,+ onConfirm: () => deleteCohort(),})}}variant="danger"diff --git a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsxindex 713608ac5aef..6758c7c44549 100644--- a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx+++ b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx@@ -2,7 +2,6 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { IconClock, IconCopy, IconLetter, IconRefresh, IconSend, IconTrash } from '@posthog/icons'-import { LemonDialog } from '@posthog/lemon-ui'import { SceneMenuBarAddToNotebook } from 'lib/components/Scenes/SceneMenuBarAddToNotebook'import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'@@ -15,6 +14,7 @@ import {cohortBroadcastDisabledReason,urlForCohortWorkflow,} from 'scenes/cohorts/cohortUtils'+import { openDeleteCohortDialog } from 'scenes/cohorts/DeleteCohortDialog'import { NotebookNodeType } from 'scenes/notebooks/types'import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'import { urls } from 'scenes/urls'@@ -142,20 +142,10 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element<SceneMenuBarItemvariant="destructive"onClick={() => {- LemonDialog.open({- title: 'Delete cohort?',- description: `Are you sure you want to delete "${cohort.name}"?`,- primaryButton: {- children: 'Delete',- status: 'danger',- onClick: () => deleteCohort(),- size: 'small',- },- secondaryButton: {- children: 'Cancel',- type: 'tertiary',- size: 'small',- },+ openDeleteCohortDialog({+ cohortId: cohort.id,+ cohortName: cohort.name,+ onConfirm: () => deleteCohort(),})}}data-attr={`${RESOURCE_TYPE}-menubar-delete`}diff --git a/frontend/src/scenes/cohorts/CohortUsedInList.tsx b/frontend/src/scenes/cohorts/CohortUsedInList.tsxnew file mode 100644index 000000000000..738c531b039b--- /dev/null+++ b/frontend/src/scenes/cohorts/CohortUsedInList.tsx@@ -0,0 +1,38 @@+import { Link } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import { CohortUsedInSection } from './cohortUsedIn'++function hiddenUsesNote(hidden: number, noun: string): string {+ return hidden === 1+ ? `You don't have access to 1 ${noun} that uses this cohort. Ask someone who can edit it to remove the cohort.`+ : `You don't have access to ${pluralize(hidden, noun)} that use this cohort. Ask someone who can edit them to remove the cohort.`+}++export function CohortUsedInList({ sections }: { sections: CohortUsedInSection[] }): JSX.Element {+ return (+ <div className="flex flex-col gap-y-2">+ {sections.map(({ title, noun, total, hidden = 0, items }) => (+ <div key={title}>+ <h5 className="text-xs font-semibold uppercase opacity-60 mb-0">+ {title}+ {total - hidden > items.length && (+ <span>{` (${items.length} of ${total - hidden} shown)`}</span>+ )}+ </h5>+ {items.length > 0 && (+ <ul className="list-disc pl-4 mb-0">+ {items.map(({ key, url, label }) => (+ <li key={key}>+ <Link to={url}>{label}</Link>+ </li>+ ))}+ </ul>+ )}+ {hidden > 0 && <p className="text-secondary mb-0">{hiddenUsesNote(hidden, noun)}</p>}+ </div>+ ))}+ </div>+ )+}diff --git a/frontend/src/scenes/cohorts/Cohorts.tsx b/frontend/src/scenes/cohorts/Cohorts.tsxindex 0a406c4e3b42..ece0707eb7b0 100644--- a/frontend/src/scenes/cohorts/Cohorts.tsx+++ b/frontend/src/scenes/cohorts/Cohorts.tsx@@ -3,7 +3,7 @@ import './Cohorts.scss'import { useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'-import { LemonBanner, LemonDialog, LemonInput, LemonSelect } from '@posthog/lemon-ui'+import { LemonBanner, LemonInput, LemonSelect } from '@posthog/lemon-ui'import { Button } from '@posthog/quill'import { MemberSelect } from 'lib/components/MemberSelect'@@ -22,6 +22,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'import { cohortsSceneLogic } from 'scenes/cohorts/cohortsSceneLogic'+import { openDeleteCohortDialog } from 'scenes/cohorts/DeleteCohortDialog'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -179,21 +180,11 @@ export function Cohorts(): JSX.Element {<LemonButtonstatus="danger"onClick={() => {- LemonDialog.open({- title: 'Delete cohort?',- description: `Are you sure you want to delete "${cohort.name}"?`,- primaryButton: {- children: 'Delete',- status: 'danger',- onClick: () =>- deleteCohort({ id: cohort.id, name: cohort.name, deleted: true }),- size: 'small',- },- secondaryButton: {- children: 'Cancel',- type: 'tertiary',- size: 'small',- },+ openDeleteCohortDialog({+ cohortId: cohort.id,+ cohortName: cohort.name,+ onConfirm: () =>+ deleteCohort({ id: cohort.id, name: cohort.name, deleted: true }),})}}fullWidthdiff --git a/frontend/src/scenes/cohorts/DeleteCohortDialog.stories.tsx b/frontend/src/scenes/cohorts/DeleteCohortDialog.stories.tsxnew file mode 100644index 000000000000..bf3a06500e8f--- /dev/null+++ b/frontend/src/scenes/cohorts/DeleteCohortDialog.stories.tsx@@ -0,0 +1,82 @@+import { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'++import { DeleteCohortDialog } from './DeleteCohortDialog'++const emptyBlock = { results: [], total: 0, hidden: 0, has_more: false }++const usedIn: CohortUsedInResponseApi = {+ feature_flags: {+ results: [+ { id: 1, key: 'new-checkout', name: 'New checkout', archived: false },+ { id: 2, key: 'paused-banner', name: 'Paused banner', archived: false },+ { id: 3, key: 'old-banner', name: 'Old banner', archived: true },+ ],+ total: 3,+ hidden: 0,+ has_more: false,+ },+ insights: {+ results: [{ id: 5, short_id: 'abc123', name: 'Weekly signups' }],+ total: 1,+ hidden: 0,+ has_more: false,+ },+ cohorts: emptyBlock,+ test_account_filters: {+ results: [{ id: 42, name: 'Staging' }],+ total: 1,+ has_more: false,+ },+ workflows: {+ results: [{ id: '0192a7f0-0000-7000-8000-000000000001', name: 'Welcome series', status: 'active' }],+ total: 2,+ hidden: 1,+ has_more: true,+ },+}++const meta: Meta<typeof DeleteCohortDialog> = {+ component: DeleteCohortDialog,+ title: 'Scenes-App/People/Delete cohort dialog',+ // In the app the dialog sits in a LemonModal, which is never narrower than 28rem. Rendering the+ // bare component lets it shrink to its text, so the snapshot would wrap at a width no user sees.+ decorators: [+ (Story) => (+ <div className="w-[28rem]">+ <Story />+ </div>+ ),+ ],+ args: {+ cohortId: 1,+ cohortName: 'Power users',+ onConfirm: () => {},+ closeDialog: () => {},+ },+}+export default meta++type Story = StoryObj<typeof DeleteCohortDialog>++export const Blocked: Story = {+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/:id/used_in/': usedIn } })],+}++export const NothingUsesIt: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/cohorts/:id/used_in/': {+ feature_flags: emptyBlock,+ insights: emptyBlock,+ cohorts: emptyBlock,+ test_account_filters: emptyBlock,+ },+ },+ }),+ ],+}diff --git a/frontend/src/scenes/cohorts/DeleteCohortDialog.tsx b/frontend/src/scenes/cohorts/DeleteCohortDialog.tsxnew file mode 100644index 000000000000..25a804287d3a--- /dev/null+++ b/frontend/src/scenes/cohorts/DeleteCohortDialog.tsx@@ -0,0 +1,95 @@+import { useValues } from 'kea'++import { LemonBanner, LemonDialog } from '@posthog/lemon-ui'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'++import { CohortType } from '~/types'++import { cohortDeleteDialogLogic } from './cohortDeleteDialogLogic'+import { CohortUsedInList } from './CohortUsedInList'++interface DeleteCohortDialogProps {+ cohortId: CohortType['id']+ cohortName?: string | null+ onConfirm: () => void+ closeDialog: () => void+}++export function DeleteCohortDialog({+ cohortId,+ cohortName,+ onConfirm,+ closeDialog,+}: DeleteCohortDialogProps): JSX.Element {+ const { blockers, blockersLoading } = useValues(cohortDeleteDialogLogic({ cohortId: Number(cohortId) }))+ const label = cohortName ? `"${cohortName}"` : 'this cohort'++ return (+ <div className="flex flex-col gap-y-2" data-attr="cohort-delete-dialog">+ {blockersLoading ? (+ <div className="flex items-center gap-x-2">+ <Spinner />+ <span>Checking what uses this cohort…</span>+ </div>+ ) : blockers?.length ? (+ <>+ <LemonBanner type="warning">+ You can't delete {label} while these still use it. Remove it from each of them, then delete the+ cohort.+ </LemonBanner>+ <div className="max-h-60 overflow-y-auto">+ <CohortUsedInList sections={blockers} />+ </div>+ </>+ ) : (+ <span>Are you sure you want to delete {label}?</span>+ )}+ <div className="flex justify-end gap-x-2 pt-2">+ <LemonButton type="tertiary" size="small" onClick={closeDialog}>+ Cancel+ </LemonButton>+ <LemonButton+ type="secondary"+ status="danger"+ size="small"+ disabledReason={+ blockersLoading+ ? 'Checking what uses this cohort'+ : blockers?.length+ ? 'Remove the cohort from everything listed above first'+ : undefined+ }+ onClick={() => {+ onConfirm()+ closeDialog()+ }}+ data-attr="cohort-delete-dialog-confirm"+ >+ Delete+ </LemonButton>+ </div>+ </div>+ )+}++export function openDeleteCohortDialog({+ cohortId,+ cohortName,+ onConfirm,+}: Omit<DeleteCohortDialogProps, 'closeDialog'>): void {+ LemonDialog.open({+ title: 'Delete cohort?',+ primaryButton: null,+ secondaryButton: null,+ content: (closeDialog) => (+ <DeleteCohortDialog+ cohortId={cohortId}+ cohortName={cohortName}+ onConfirm={onConfirm}+ closeDialog={closeDialog}+ />+ ),+ })+}diff --git a/frontend/src/scenes/cohorts/cohortDeleteDialogLogic.ts b/frontend/src/scenes/cohorts/cohortDeleteDialogLogic.tsnew file mode 100644index 000000000000..c7316558efd3--- /dev/null+++ b/frontend/src/scenes/cohorts/cohortDeleteDialogLogic.ts@@ -0,0 +1,84 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'+import { teamLogic } from 'scenes/teamLogic'++import { cohortsUsedInRetrieve } from 'products/cohorts/frontend/generated/api'++import { CohortUsedInSection, cohortUsedInSections } from './cohortUsedIn'++export interface CohortDeleteDialogLogicProps {+ cohortId: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortDeleteDialogLogicValues {+ currentProjectId: number | string // teamLogic+ blockers: CohortUsedInSection[] | null+ blockersLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortDeleteDialogLogicActions {+ loadBlockers: () => any+ loadBlockersFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBlockersSuccess: (+ blockers: CohortUsedInSection[],+ payload?: any+ ) => {+ blockers: CohortUsedInSection[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortDeleteDialogLogicMeta {+ key: number+}++export type cohortDeleteDialogLogicType = MakeLogicType<+ cohortDeleteDialogLogicValues,+ cohortDeleteDialogLogicActions,+ CohortDeleteDialogLogicProps,+ cohortDeleteDialogLogicMeta+>++export const cohortDeleteDialogLogic = kea<cohortDeleteDialogLogicType>([+ path(['scenes', 'cohorts', 'cohortDeleteDialogLogic']),+ props({} as CohortDeleteDialogLogicProps),+ key((props) => props.cohortId),+ connect(() => ({+ values: [teamLogic, ['currentProjectId']],+ })),+ loaders(({ props, values }) => ({+ blockers: [+ null as CohortUsedInSection[] | null,+ {+ loadBlockers: async () => {+ try {+ const usedIn = await cohortsUsedInRetrieve(String(values.currentProjectId), props.cohortId)+ return cohortUsedInSections(usedIn, { blockingOnly: true })+ } catch (error) {+ // A pre-check the user cannot see must not stand between them and a delete+ // the server may well accept, so treat a failure as "nothing known".+ if (!(error instanceof ApiError) || error.status !== 404) {+ posthog.captureException(error, { feature: 'cohort-delete-precheck' })+ }+ return []+ }+ },+ },+ ],+ })),+ afterMount(({ actions }) => {+ actions.loadBlockers()+ }),+])diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.tsindex da8fc3b05fd6..0b5c05f4fab6 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts@@ -56,12 +56,14 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({const mockUsedInResponse: CohortUsedInResponseApi = {feature_flags: {- results: [{ id: 7, key: 'my-flag', name: 'My Flag' }],+ results: [{ id: 7, key: 'my-flag', name: 'My Flag', archived: false }],total: 1,+ hidden: 0,has_more: false,},- insights: { results: [], total: 0, has_more: false },- cohorts: { results: [], total: 0, has_more: false },+ insights: { results: [], total: 0, hidden: 0, has_more: false },+ cohorts: { results: [], total: 0, hidden: 0, has_more: false },+ test_account_filters: { results: [], total: 0, has_more: false },workflows: { results: [], total: 0, hidden: 0, has_more: false },}diff --git a/frontend/src/scenes/cohorts/cohortUsedIn.test.ts b/frontend/src/scenes/cohorts/cohortUsedIn.test.tsnew file mode 100644index 000000000000..574e3afe3154--- /dev/null+++ b/frontend/src/scenes/cohorts/cohortUsedIn.test.ts@@ -0,0 +1,96 @@+import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'++import { cohortUsedInSections } from './cohortUsedIn'++const usedIn: CohortUsedInResponseApi = {+ feature_flags: {+ results: [+ { id: 1, key: 'live-flag', name: 'Live flag', archived: false },+ { id: 2, key: 'paused-flag', name: 'Paused flag', archived: false },+ { id: 3, key: 'archived-flag', name: 'Archived flag', archived: true },+ ],+ total: 3,+ hidden: 0,+ has_more: false,+ },+ insights: { results: [], total: 0, hidden: 0, has_more: false },+ cohorts: { results: [], total: 0, hidden: 0, has_more: false },+ test_account_filters: {+ results: [{ id: 42, name: 'Staging' }],+ total: 1,+ has_more: false,+ },+ workflows: { results: [], total: 0, hidden: 0, has_more: false },+}++describe('cohortUsedInSections', () => {+ it('reports every reference, and links each environment to its own settings', () => {+ const sections = cohortUsedInSections(usedIn)++ expect(sections.map(({ title, total }) => [title, total])).toEqual([+ ['Feature flags', 3],+ ['Filter out internal and test users', 1],+ ])+ expect(sections[1].items[0].url).toEqual(+ '/project/42/settings/environment-customization#internal-user-filtering'+ )+ })++ it('keeps only the references that block a delete', () => {+ const sections = cohortUsedInSections(usedIn, { blockingOnly: true })++ // An archived flag never blocks a delete, so listing it would send the user to fix nothing.+ expect(sections[0].items.map(({ label }) => label)).toEqual(['Live flag', 'Paused flag'])+ expect(sections[0].total).toEqual(2)+ })++ it.each([+ ['feature_flags', 'Feature flags'],+ ['insights', 'Insights'],+ ['cohorts', 'Cohorts'],+ ] as const)('counts %s the caller cannot view only as delete blockers', (block, title) => {+ const withHidden = {+ ...usedIn,+ [block]: { results: [], total: 0, hidden: 2, has_more: false },+ } as CohortUsedInResponseApi++ expect(cohortUsedInSections(withHidden, { blockingOnly: true }).find((s) => s.title === title)).toMatchObject({+ total: 2,+ hidden: 2,+ items: [],+ })+ expect(cohortUsedInSections(withHidden).map(({ title }) => title)).not.toContain(title)+ })++ it.each([+ [+ 'some of them are visible',+ { results: [{ id: 'wf-1', name: 'Onboarding', status: 'active' }], total: 3, hidden: 2, has_more: true },+ ['Onboarding'],+ ],+ ['none of them are visible', { results: [], total: 1, hidden: 1, has_more: true }, []],+ ])('lists relying workflows as delete blockers when %s', (_, workflows, labels) => {+ const withWorkflows: CohortUsedInResponseApi = { ...usedIn, workflows }+ const section = cohortUsedInSections(withWorkflows, { blockingOnly: true }).find(+ ({ title }) => title === 'Workflows'+ )++ expect(section).toMatchObject({ total: workflows.total, hidden: workflows.hidden })+ expect(section?.items.map(({ label }) => label)).toEqual(labels)+ expect(cohortUsedInSections(withWorkflows).map(({ title }) => title)).not.toContain('Workflows')+ })++ it('returns nothing for a cohort no-one references', () => {+ const empty = { results: [], total: 0, hidden: 0, has_more: false }++ expect(+ cohortUsedInSections({+ feature_flags: empty,+ insights: empty,+ cohorts: empty,+ test_account_filters: empty,+ workflows: empty,+ })+ ).toEqual([])+ })+})diff --git a/frontend/src/scenes/cohorts/cohortUsedIn.ts b/frontend/src/scenes/cohorts/cohortUsedIn.tsnew file mode 100644index 000000000000..1bb8421cf7d3--- /dev/null+++ b/frontend/src/scenes/cohorts/cohortUsedIn.ts@@ -0,0 +1,115 @@+import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'++import { InsightShortId } from '~/types'++import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'++export interface CohortUsedInItem {+ key: string+ url: string+ label: string+}++export interface CohortUsedInSection {+ title: string+ noun: string+ /** Every use, which can exceed the number of items when the API truncates the list. */+ total: number+ /** Uses the caller cannot view. They count toward the total but never appear in the items. */+ hidden?: number+ items: CohortUsedInItem[]+}++export interface CohortUsedInSectionsOptions {+ /** Keep only the references that make the server refuse a delete. */+ blockingOnly?: boolean+}++export function cohortUsedInSections(+ usedIn: CohortUsedInResponseApi,+ { blockingOnly = false }: CohortUsedInSectionsOptions = {}+): CohortUsedInSection[] {+ // Every flag that is not archived blocks a delete, enabled or not, so the blocking list drops the+ // archived ones and counts what is left instead of the server's total.+ const flags = blockingOnly+ ? usedIn.feature_flags.results.filter((flag) => !flag.archived)+ : usedIn.feature_flags.results+ // The editor lists what the caller can view. Only the blocking list counts hidden uses, because+ // they still stop a delete.+ const hiddenIn = (block: { hidden?: number }): number => (blockingOnly ? (block.hidden ?? 0) : 0)+ const hiddenFlags = hiddenIn(usedIn.feature_flags)+ const hiddenInsights = hiddenIn(usedIn.insights)+ const hiddenCohorts = hiddenIn(usedIn.cohorts)+ // During a rollout the frontend can reach a backend that predates these blocks.+ const environments = usedIn.test_account_filters?.results ?? []+ const workflows = usedIn.workflows ?? { results: [], total: 0, hidden: 0, has_more: false }++ const sections: CohortUsedInSection[] = [+ {+ title: 'Feature flags',+ noun: 'feature flag',+ total: (blockingOnly ? flags.length : usedIn.feature_flags.total) + hiddenFlags,+ hidden: hiddenFlags,+ items: flags.map((flag) => ({+ key: `flag-${flag.id}`,+ url: urls.featureFlag(flag.id),+ label: flag.name || flag.key,+ })),+ },+ {+ title: 'Insights',+ noun: 'insight',+ total: usedIn.insights.total + hiddenInsights,+ hidden: hiddenInsights,+ items: usedIn.insights.results.map((insight) => ({+ key: `insight-${insight.id}`,+ url: urls.insightView(insight.short_id as InsightShortId),+ label: insight.name,+ })),+ },+ {+ title: 'Cohorts',+ noun: 'cohort',+ total: usedIn.cohorts.total + hiddenCohorts,+ hidden: hiddenCohorts,+ items: usedIn.cohorts.results.map((cohort) => ({+ key: `cohort-${cohort.id}`,+ url: urls.cohort(cohort.id),+ label: cohort.name,+ })),+ },+ {+ title: 'Filter out internal and test users',+ noun: 'environment',+ total: usedIn.test_account_filters?.total ?? 0,+ items: environments.map((environment) => ({+ key: `environment-${environment.id}`,+ // The setting is per environment, so the link carries the environment it belongs to+ // rather than the one the user is looking at.+ url: addProjectIdIfMissing(+ urls.settings('environment-customization', 'internal-user-filtering'),+ environment.id+ ),+ label: environment.name,+ })),+ },+ ]+ // The editor shows workflows in its own link next to the cohort type, so only the blocking list includes them.+ // Every workflow in the block is active, and an active workflow blocks a delete.+ if (blockingOnly) {+ sections.push({+ title: 'Workflows',+ noun: 'workflow',+ total: workflows.total,+ hidden: workflows.hidden,+ items: workflows.results.map((workflow) => ({+ key: `workflow-${workflow.id}`,+ url: urls.workflow(workflow.id, 'workflow'),+ label: workflow.name || 'Untitled workflow',+ })),+ })+ }+ // A section whose uses are all hidden from the caller has no items, but it still blocks a delete.+ return sections.filter((section) => section.total > 0)+}diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 798a1fbc4b97..efeceedb6d12 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -7,7 +7,7 @@ import hashlibfrom collections import defaultdictfrom collections.abc import Iterable, Iterator, Sequencefrom copy import deepcopy-from typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast+from typing import Annotated, Any, ClassVar, Literal, NoReturn, Optional, Union, castfrom django.conf import settingsfrom django.db.models import OuterRef, Q, QuerySet, Subquery@@ -660,6 +660,14 @@ 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")+ archived = serializers.BooleanField(+ help_text="True when the flag is archived. Every flag that is not archived prevents the cohort from being deleted, enabled or not"+ )+++class CohortUsedInEnvironmentSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="Environment (team) database ID")+ name = serializers.CharField(help_text="Environment display name")class CohortUsedInInsightSerializer(serializers.Serializer):@@ -688,7 +696,10 @@ class CohortUsedInFlagsBlockSerializer(serializers.Serializer):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"+ help_text="Total number of feature flags referencing this cohort that the caller can view, before truncation"+ )+ hidden = serializers.IntegerField(+ help_text="Number of flags that are not archived and that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total")has_more = serializers.BooleanField(help_text="True when more feature flags exist beyond the truncation cap")@@ -697,7 +708,12 @@ 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")+ total = serializers.IntegerField(+ help_text="Total number of insights referencing this cohort that the caller can view, before truncation"+ )+ hidden = serializers.IntegerField(+ help_text="Number of insights referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total"+ )has_more = serializers.BooleanField(help_text="True when more insights exist beyond the truncation cap")@@ -706,10 +722,26 @@ class CohortUsedInCohortsBlockSerializer(serializers.Serializer):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")+ total = serializers.IntegerField(+ help_text="Total number of cohorts referencing this cohort that the caller can view, before truncation"+ )+ hidden = serializers.IntegerField(+ help_text="Number of cohorts referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total"+ )has_more = serializers.BooleanField(help_text="True when more cohorts exist beyond the truncation cap")+class CohortUsedInEnvironmentsBlockSerializer(serializers.Serializer):+ results = CohortUsedInEnvironmentSerializer(+ many=True,+ help_text=f"Environments that use this cohort in 'Filter out internal and test users', capped at {COHORT_USED_IN_PAGE_SIZE} results",+ )+ total = serializers.IntegerField(+ help_text="Total number of environments using this cohort in their test account filters, before truncation"+ )+ has_more = serializers.BooleanField(help_text="True when more environments exist beyond the truncation cap")++class CohortUsedInWorkflowsBlockSerializer(serializers.Serializer):results = CohortUsedInWorkflowSerializer(many=True,@@ -736,6 +768,9 @@ class CohortUsedInResponseSerializer(serializers.Serializer):cohorts = CohortUsedInCohortsBlockSerializer(help_text="Other cohorts that include this cohort as a criterion, with truncation metadata")+ test_account_filters = CohortUsedInEnvironmentsBlockSerializer(+ help_text="Environments across the project that use this cohort in 'Filter out internal and test users', with truncation metadata"+ )workflows = CohortUsedInWorkflowsBlockSerializer(help_text=("Active workflows that trigger on this cohort or branch on its membership. While any exist, the "@@ -1780,6 +1815,22 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializcode="behavioral_cohort_found",)+ def _reject_delete(self, cohort: Cohort, blocked_by: str, message: str, code: str | None = None) -> NoReturn:+ """Refuse a cohort deletion and record why, so the block is measurable.++ The rejection is a 400 the user never sees as an event otherwise, which left the+ frequency of this dead end unknown.+ """+ request = self.context["request"]+ report_user_action(+ request.user,+ "cohort deletion blocked",+ {"cohort_id": cohort.id, "blocked_by": blocked_by},+ team=cohort.team,+ request=request,+ )+ raise ValidationError(message, code=code)+def _user_access_control(self) -> Optional[UserAccessControl]:return getattr(self.context.get("view"), "user_access_control", None)@@ -1880,36 +1931,33 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ).exists()):message += " For a survey's targeting flag, change the survey's targeting or delete the survey instead."- raise ValidationError(message)+ self._reject_delete(cohort, "feature_flags", message)workflows_with_cohort = _workflows_relying_on_cohort(cohort)if workflows_with_cohort:names = _workflow_names_suffix(request, self._user_access_control(), cohort.team_id, workflows_with_cohort)- raise ValidationError(+ self._reject_delete(+ cohort,+ "workflows",f"This cohort is used in {len(workflows_with_cohort)} active workflow(s){names}. ""Please remove the cohort from these workflows before deleting it.",code=COHORT_USED_BY_WORKFLOWS_ERROR_CODE,)# Check if cohort is used in test_account_filters- teams_with_cohort = Team.objects.filter(- project_id=cohort.team.project_id,- test_account_filters__contains=[{"type": "cohort"}],- )- teams_using_cohort = []- for team in teams_with_cohort:- for filter_item in team.test_account_filters:- if filter_item.get("type") == "cohort" and filter_item.get("value") == cohort.id:- teams_using_cohort.append(team)- break+ teams_using_cohort = get_environments_using_cohort_in_test_account_filters(cohort)if teams_using_cohort:- team_names = [team.name for team in teams_using_cohort]- raise ValidationError(+ # The environment id is part of the name because environments in one project+ # often share a name, and the settings page only shows the current one.+ team_names = [f"{team.name} (environment {team.id})" for team in teams_using_cohort]+ self._reject_delete(+ cohort,+ "test_account_filters",f"This cohort is used in 'Filter out internal and test users' for {len(teams_using_cohort)} environment(s): {', '.join(team_names)}. "- "Please remove the cohort from these test account filters before deleting it."+ "Please remove the cohort from these test account filters before deleting it.",)# Check if cohort is used in insights@@ -1923,9 +1971,11 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializnames_str = ", ".join(insight_names)if count > 5:names_str = f"{names_str}, and {count - 5} more"- raise ValidationError(+ self._reject_delete(+ cohort,+ "insights",f"This cohort is used in {count} insight(s): {names_str}. "- "Please remove the cohort from these insights before deleting it."+ "Please remove the cohort from these insights before deleting it.",)# Check if cohort is used as criteria in other cohorts@@ -1937,9 +1987,11 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializnames_str = ", ".join(cohort_names)if count > 5:names_str = f"{names_str}, and {count - 5} more"- raise ValidationError(+ self._reject_delete(+ cohort,+ "cohorts",f"This cohort is used as criteria in {count} other cohort(s): {names_str}. "- "Please remove this cohort from those cohort definitions before deleting it."+ "Please remove this cohort from those cohort definitions before deleting it.",)relevant_team_ids = Team.objects.filter(project_id=cohort.team.project_id).values_list("id", flat=True)@@ -2015,6 +2067,14 @@ def _used_in_block(page: list[dict], total: int) -> dict[str, Any]:return {"results": page, "total": total, "has_more": total > len(page)}+def _hidden_reference_count(all_references: QuerySet, visible_references: QuerySet, visible_total: int) -> int:+ # filter_queryset_by_access_level returns the queryset it was given when it applies no filter,+ # so that case skips a second run of the reference predicate.+ if visible_references is all_references:+ return 0+ return max(all_references.count() - visible_total, 0)++def _workflows_block(request: Request, user_access_control: Optional[UserAccessControl], cohort: Cohort) -> dict[str, Any]:@@ -2182,6 +2242,26 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:)+def get_environments_using_cohort_in_test_account_filters(cohort: Cohort) -> list[Team]:+ """Return environments in the cohort's project whose test account filters reference it.++ The scan covers every environment in the project, not just the cohort's own, because+ test account filters are stored per environment and any one of them keeps the cohort alive.+ """+ candidate_teams = Team.objects.filter(+ project_id=cohort.team.project_id,+ test_account_filters__contains=[{"type": "cohort"}],+ ).order_by("id")+ return [+ team+ for team in candidate_teams+ if any(+ filter_item.get("type") == "cohort" and filter_item.get("value") == cohort.id+ for filter_item in team.test_account_filters+ )+ ]++@extend_schema(extensions={"x-product": "cohorts"})@extend_schema_view(list=extend_schema(@@ -2606,19 +2686,29 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi@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.+ # Hide references the caller has been denied at the object level. Org admins see every+ # reference, because they can open every object.uac = self.user_access_control- # Access-filter before the Python-side expansion so denied flags are never- # loaded or expanded.- flags_qs = uac.filter_queryset_by_access_level(- _flags_with_cohort_filters(cohort), include_all_if_admin=True- ).order_by("id")- flags = _filter_flags_referencing_cohort(flags_qs, cohort, stop_traversal_at_static=True)- flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name} for flag in flags]+ # Flags that are not archived sort first because they block a delete, and the page below+ # is truncated: a cohort behind more flags than the cap would otherwise report no blocker+ # while the deletion guard still refuses.+ all_flags_qs = _flags_with_cohort_filters(cohort)+ visible_flags_qs = uac.filter_queryset_by_access_level(all_flags_qs, include_all_if_admin=True)+ referencing_flags = _filter_flags_referencing_cohort(+ all_flags_qs.order_by("archived", "-active", "id"), cohort, stop_traversal_at_static=True+ )+ flags, hidden_flags = referencing_flags, 0+ if visible_flags_qs is not all_flags_qs:+ visible_flag_ids = set(+ visible_flags_qs.filter(id__in=[flag.id for flag in referencing_flags]).values_list("id", flat=True)+ )+ flags = [flag for flag in referencing_flags if flag.id in visible_flag_ids]+ hidden_flags = sum(1 for flag in referencing_flags if flag.id not in visible_flag_ids and not flag.archived)+ flags_data = [{"id": flag.id, "key": flag.key, "name": flag.name, "archived": flag.archived} for flag in flags]- insights_qs = uac.filter_queryset_by_access_level(get_insights_using_cohort(cohort))+ all_insights_qs = get_insights_using_cohort(cohort)+ insights_qs = uac.filter_queryset_by_access_level(all_insights_qs, include_all_if_admin=True)insights_page, insights_total = _truncate_used_in_queryset(insights_qs.values("id", "short_id", "name", "derived_name"))@@ -2631,15 +2721,34 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVifor insight in insights_page]- cohorts_qs = uac.filter_queryset_by_access_level(get_cohorts_using_cohort(cohort))+ all_cohorts_qs = get_cohorts_using_cohort(cohort)+ cohorts_qs = uac.filter_queryset_by_access_level(all_cohorts_qs, include_all_if_admin=True)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]+ # Not access-filtered, unlike the blocks above: this mirrors the deletion guard, which+ # scans every environment in the project. Hiding one would show a blocker-free list to a+ # user whose delete is still refused.+ environments = get_environments_using_cohort_in_test_account_filters(cohort)+ environments_data = [{"id": team.id, "name": team.name} for team in environments]+return Response({- "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),+ "feature_flags": {+ **_used_in_block(flags_data[:COHORT_USED_IN_PAGE_SIZE], len(flags_data)),+ "hidden": hidden_flags,+ },+ "insights": {+ **_used_in_block(insights_data, insights_total),+ "hidden": _hidden_reference_count(all_insights_qs, insights_qs, insights_total),+ },+ "cohorts": {+ **_used_in_block(cohorts_data, cohorts_total),+ "hidden": _hidden_reference_count(all_cohorts_qs, cohorts_qs, cohorts_total),+ },+ "test_account_filters": _used_in_block(+ environments_data[:COHORT_USED_IN_PAGE_SIZE], len(environments_data)+ ),"workflows": _workflows_block(request, uac, cohort),})diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex dbe3c1812a37..31daaa777349 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -6015,7 +6015,11 @@ [email protected],"This cohort is used in 'Filter out internal and test users' for 1 environment(s):",response.json()["detail"],)- self.assertIn(self.team.name, response.json()["detail"])+ self.assertIn(f"{self.team.name} (environment {self.team.id})", response.json()["detail"])+ self.assertIn(+ "cohort deletion blocked",+ [call.args[1] for call in patch_capture.call_args_list],+ )@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -6706,8 +6710,10 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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})+ self.assertFalse(data["feature_flags"]["results"][0]["archived"])+ self.assertEqual(data["insights"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["test_account_filters"], {"results": [], "total": 0, "has_more": False})@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -6722,33 +6728,78 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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})+ self.assertEqual(data["feature_flags"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["insights"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["test_account_filters"], {"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):+ def test_used_in_includes_inactive_and_archived_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"]+ filters = {"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]}FeatureFlag.objects.create(team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},+ filters=filters,name="Inactive Flag",key="inactive-flag",created_by=self.user,active=False,)+ FeatureFlag.objects.create(+ team=self.team,+ filters=filters,+ name="Archived Flag",+ key="archived-flag",+ created_by=self.user,+ active=False,+ archived=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)flags = response.json()["feature_flags"]["results"]- self.assertEqual(len(flags), 1)- self.assertEqual(flags[0]["key"], "inactive-flag")+ self.assertEqual(+ [(flag["key"], flag["archived"]) for flag in flags],+ [("inactive-flag", False), ("archived-flag", True)],+ )++ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_used_in_returns_environments_using_cohort_in_test_account_filters(+ 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_cohort = Cohort.objects.create(team=self.team, name="Other Cohort")++ self.team.test_account_filters = [{"key": "id", "value": cohort_id, "type": "cohort"}]+ self.team.save()+ sibling = Team.objects.create(organization=self.organization, project=self.team.project, name="Staging")+ sibling.test_account_filters = [{"key": "id", "value": cohort_id, "type": "cohort"}]+ sibling.save()+ unrelated = Team.objects.create(organization=self.organization, project=self.team.project, name="Unrelated")+ unrelated.test_account_filters = [{"key": "id", "value": other_cohort.pk, "type": "cohort"}]+ unrelated.save()++ 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()["test_account_filters"]+ self.assertEqual(block["total"], 2)+ self.assertFalse(block["has_more"])+ self.assertEqual(+ sorted(environment["id"] for environment in block["results"]), sorted([self.team.id, sibling.id])+ )+ self.assertIn("Staging", [environment["name"] for environment in block["results"]])@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -6769,7 +6820,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{source_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})+ self.assertEqual(response.json()["feature_flags"], {"results": [], "total": 0, "has_more": False, "hidden": 0})@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -7085,7 +7136,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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})+ self.assertEqual(response.json()["insights"], {"results": [], "total": 0, "has_more": False, "hidden": 0})@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -7121,8 +7172,8 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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})+ self.assertEqual(data["feature_flags"], {"results": [], "total": 0, "has_more": False, "hidden": 0})+ self.assertEqual(data["cohorts"], {"results": [], "total": 0, "has_more": False, "hidden": 0})@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")@@ -7150,6 +7201,43 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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_keeps_blocking_flags_when_truncating(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"]++ flag_filters = {"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]}+ for i in range(COHORT_USED_IN_PAGE_SIZE):+ FeatureFlag.objects.create(+ team=self.team,+ filters=flag_filters,+ name=f"Archived flag {i}",+ key=f"archived-flag-{i}",+ created_by=self.user,+ active=False,+ archived=True,+ )+ # Created last, so it has the highest id and only survives truncation if blocking flags sort first.+ FeatureFlag.objects.create(+ team=self.team,+ filters=flag_filters,+ name="Paused flag",+ key="paused-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)++ block = response.json()["feature_flags"]+ self.assertEqual(len(block["results"]), COHORT_USED_IN_PAGE_SIZE)+ self.assertEqual(block["results"][0]["key"], "paused-flag")+@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):@@ -7201,7 +7289,7 @@ class TestCohortUsedIn(ClickhouseTestMixin, APIBaseTest):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})+ self.assertEqual(response.json()["feature_flags"], {"results": [], "total": 0, "has_more": False, "hidden": 0})@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.pyindex 562adbb3dccd..1b4b3ad947fe 100644--- a/products/access_control/backend/tests/test_access_control.py+++ b/products/access_control/backend/tests/test_access_control.py@@ -2687,6 +2687,7 @@ class TestCohortUsedInAccessControl(BaseAccessControlTest):block = res.json()["feature_flags"]assert [flag["key"] for flag in block["results"]] == ["visible-flag"]assert block["total"] == 1+ assert block["hidden"] == 1assert block["has_more"] is Falsedef test_used_in_includes_restricted_flags_for_org_admins(self):@@ -2697,8 +2698,67 @@ class TestCohortUsedInAccessControl(BaseAccessControlTest):block = res.json()["feature_flags"]assert [flag["key"] for flag in block["results"]] == ["visible-flag", "hidden-flag"]assert block["total"] == 2+ assert block["hidden"] == 0assert block["has_more"] is False+ def _create_reference(self, resource: str, cohort: Cohort, created_by: User, archived: bool = False) -> int:+ reference = {"type": "cohort", "key": "id", "value": cohort.id}+ if resource == "insight":+ return Insight.objects.create(+ team=self.team,+ created_by=created_by,+ query={+ "kind": "DataTableNode",+ "source": {"kind": "EventsQuery", "select": ["*"], "properties": [reference]},+ },+ ).id+ if resource == "cohort":+ return Cohort.objects.create(+ team=self.team,+ created_by=created_by,+ name="Outer Cohort",+ filters={"properties": {"type": "OR", "values": [{"type": "OR", "values": [reference]}]}},+ ).id+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=created_by,+ key=f"flag-{uuid.uuid4().hex[:8]}",+ active=not archived,+ archived=archived,+ filters=self._cohort_flag_filters(cohort.id),+ ).id++ @parameterized.expand(+ [+ ("insight_member", "insight", "insights", OrganizationMembership.Level.MEMBER, False, 1, 1),+ ("insight_admin", "insight", "insights", OrganizationMembership.Level.ADMIN, False, 2, 0),+ ("cohort_member", "cohort", "cohorts", OrganizationMembership.Level.MEMBER, False, 1, 1),+ ("cohort_admin", "cohort", "cohorts", OrganizationMembership.Level.ADMIN, False, 2, 0),+ # An archived flag never blocks a delete, so it is not a hidden blocker.+ ("archived_flag_member", "feature_flag", "feature_flags", OrganizationMembership.Level.MEMBER, True, 1, 0),+ ]+ )+ def test_used_in_counts_hidden_references_that_block_a_delete(+ self,+ _name: str,+ resource: str,+ block_key: str,+ level: OrganizationMembership.Level,+ hidden_is_archived: bool,+ total: int,+ hidden: int,+ ):+ cohort = Cohort.objects.create(team=self.team, name="Target Cohort")+ self._create_reference(resource, cohort, created_by=self.user)+ hidden_id = self._create_reference(resource, cohort, created_by=self.other_user, archived=hidden_is_archived)+ AccessControl.objects.create(team=self.team, resource=resource, resource_id=str(hidden_id), access_level="none")+ self._org_membership(level)++ 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()[block_key]+ assert (len(block["results"]), block["total"], block["hidden"]) == (total, total, hidden)+class TestOrganizationMemberProjectAccess(BaseAccessControlTest):def setUp(self):diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex 1d0be7a7e6ce..ed19319832da 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -679,13 +679,17 @@ export interface CohortUsedInFlagApi {* @nullable*/name: string | null+ /** True when the flag is archived. Every flag that is not archived prevents the cohort from being deleted, enabled or not */+ archived: boolean}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 of feature flags referencing this cohort that the caller can view, before truncation */total: number+ /** Number of flags that are not archived and that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number/** True when more feature flags exist beyond the truncation cap */has_more: boolean}@@ -702,8 +706,10 @@ export interface CohortUsedInInsightApi {export interface CohortUsedInInsightsBlockApi {/** Insights referencing this cohort, capped at 100 results */results: CohortUsedInInsightApi[]- /** Total number of insights referencing this cohort, before truncation */+ /** Total number of insights referencing this cohort that the caller can view, before truncation */total: number+ /** Number of insights referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number/** True when more insights exist beyond the truncation cap */has_more: boolean}@@ -718,12 +724,30 @@ export interface CohortUsedInCohortApi {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 of cohorts referencing this cohort that the caller can view, before truncation */total: number+ /** Number of cohorts referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number/** True when more cohorts exist beyond the truncation cap */has_more: boolean}+export interface CohortUsedInEnvironmentApi {+ /** Environment (team) database ID */+ id: number+ /** Environment display name */+ name: string+}++export interface CohortUsedInEnvironmentsBlockApi {+ /** Environments that use this cohort in 'Filter out internal and test users', capped at 100 results */+ results: CohortUsedInEnvironmentApi[]+ /** Total number of environments using this cohort in their test account filters, before truncation */+ total: number+ /** True when more environments 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@@ -731,6 +755,8 @@ export interface CohortUsedInResponseApi {insights: CohortUsedInInsightsBlockApi/** Other cohorts that include this cohort as a criterion, with truncation metadata */cohorts: CohortUsedInCohortsBlockApi+ /** Environments across the project that use this cohort in 'Filter out internal and test users', with truncation metadata */+ test_account_filters: CohortUsedInEnvironmentsBlockApi/** Active workflows that trigger on this cohort or branch on its membership. While any exist, the cohort cannot be deleted or edited in a way that stops it updating in real time. */workflows: CohortUsedInWorkflowsBlockApi}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3537d6d0d6c4..af121e4b4ce5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24145,12 +24145,30 @@ export namespace Schemas {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 of cohorts referencing this cohort that the caller can view, before truncation */total: number;+ /** Number of cohorts referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number;/** True when more cohorts exist beyond the truncation cap */has_more: boolean;}+ export interface CohortUsedInEnvironment {+ /** Environment (team) database ID */+ id: number;+ /** Environment display name */+ name: string;+ }++ export interface CohortUsedInEnvironmentsBlock {+ /** Environments that use this cohort in 'Filter out internal and test users', capped at 100 results */+ results: CohortUsedInEnvironment[];+ /** Total number of environments using this cohort in their test account filters, before truncation */+ total: number;+ /** True when more environments exist beyond the truncation cap */+ has_more: boolean;+ }+export interface CohortUsedInFlag {/** Feature flag database ID */id: number;@@ -24161,13 +24179,17 @@ export namespace Schemas {* @nullable*/name: string | null;+ /** True when the flag is archived. Every flag that is not archived prevents the cohort from being deleted, enabled or not */+ archived: boolean;}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 of feature flags referencing this cohort that the caller can view, before truncation */total: number;+ /** Number of flags that are not archived and that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number;/** True when more feature flags exist beyond the truncation cap */has_more: boolean;}@@ -24184,8 +24206,10 @@ export namespace Schemas {export interface CohortUsedInInsightsBlock {/** Insights referencing this cohort, capped at 100 results */results: CohortUsedInInsight[];- /** Total number of insights referencing this cohort, before truncation */+ /** Total number of insights referencing this cohort that the caller can view, before truncation */total: number;+ /** Number of insights referencing this cohort that the caller cannot view. They prevent the cohort from being deleted but never appear in results or total */+ hidden: number;/** True when more insights exist beyond the truncation cap */has_more: boolean;}@@ -24217,6 +24241,8 @@ export namespace Schemas {insights: CohortUsedInInsightsBlock;/** Other cohorts that include this cohort as a criterion, with truncation metadata */cohorts: CohortUsedInCohortsBlock;+ /** Environments across the project that use this cohort in 'Filter out internal and test users', with truncation metadata */+ test_account_filters: CohortUsedInEnvironmentsBlock;/** Active workflows that trigger on this cohort or branch on its membership. While any exist, the cohort cannot be deleted or edited in a way that stops it updating in real time. */workflows: CohortUsedInWorkflowsBlock;}