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): list the workflows that block a cohort delete or edit (#117708)

Harley Alexander8dd9028e2058
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fc29aadaa0c6..c9c647388a40 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13414,6 +13414,18 @@ snapshots:
hash: v1.k794b7964.730f63a37031a8670713c04b565dee44eb0daf7ca1739d3ec65fb46cf1fb6022.P67NSd6TYkZMOWMhgH7gK0ia88hUc1NU3u0rPO5Gn08
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-with-all-selected--light:
hash: v1.k794b7964.c8a802919fbe8b57ddd3484e0736960c6e7aef3e5236f3518ad5d78b5de0741f.qL7rlejiasuC6pwlUE5inv_GZ1tjujnDGsZQk48MiHI
+ scenes-app-people-cohorts-blocking-workflows-modal--delete-blocked--dark:
+ hash: v1.k794b7964.ef919a6aca9609d0783731ec8bc26d8d09efaf8b1c2474d7ccb02bb6fac50aa6.qIa0KtoTlo_FBuI5D_yGUKkRZllRs4Y6MIDRn-rtV-g
+ scenes-app-people-cohorts-blocking-workflows-modal--delete-blocked--light:
+ hash: v1.k794b7964.6f6ceb5effdae404b9f66569db456095c2af833f861b93af32578c499d028f27.mz4x5kPGdheXrB1x9LMwRyL-jWlMZ74IBbKy8vHI3zY
+ scenes-app-people-cohorts-blocking-workflows-modal--edit-blocked--dark:
+ hash: v1.k794b7964.4ab673c6606d909b34c56b8bfb177364d5eb7fa35d02061cd9f833f12c63cdaf.wkc81U4GRFFxj8xah2nNomuMtXvizMXjF5bSZbNDlkk
+ scenes-app-people-cohorts-blocking-workflows-modal--edit-blocked--light:
+ hash: v1.k794b7964.a20b5934f62fbbd3cefc8844040941854f8c07d7baab13cde28e99c51a77776b.fXVAOpjznHOqNSNNaHMHG0HiD5IGiDrBeEODg2cTtoc
+ scenes-app-people-cohorts-blocking-workflows-modal--locked-from-details--dark:
+ hash: v1.k794b7964.a8256a9ab17c87980c37f839c64524986fc4faa877c0ed181ff243b881c4b8bf.nYbKjn1dpL-ZVnM4yrFPXO90qg8a2LgFPB5Fg7G9Qcg
+ scenes-app-people-cohorts-blocking-workflows-modal--locked-from-details--light:
+ hash: v1.k794b7964.9819971802de11467c344f7a264ee683d097adcf9365dbf0ddf7247a3ff52f72.uf3FzWXYyPG0c_v1sj4Tzz3essREBnh8ZvXL0Hh3WLs
scenes-app-people-groups--groups--dark:
hash: v1.k794b7964.43aff64914fff6a42e75760dd43d3a6a389992009b996d68255cdf1edfaa4c08.J_2LUzPOjqGdvly-10vw0UsY8tOJAv6Jt76dYvjl7Gs
scenes-app-people-groups--groups--light:
diff --git a/frontend/src/mocks/jest.ts b/frontend/src/mocks/jest.ts
index 4c088f6f9485..f16f7d1ab347 100644
--- a/frontend/src/mocks/jest.ts
+++ b/frontend/src/mocks/jest.ts
@@ -24,6 +24,7 @@ const jestOnlyDefaultHandlers = mocksToHandlers({
feature_flags: { results: [], total: 0, has_more: false },
insights: { results: [], total: 0, has_more: false },
cohorts: { results: [], total: 0, has_more: false },
+ workflows: { results: [], total: 0, hidden: 0, has_more: false },
},
},
})
diff --git a/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.stories.tsx b/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.stories.tsx
new file mode 100644
index 000000000000..7c3527f69362
--- /dev/null
+++ b/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.stories.tsx
@@ -0,0 +1,88 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
+import { useEffect } from 'react'
+
+import { CohortBlockingWorkflowsModal } from './CohortBlockingWorkflowsModal'
+import { CohortBlockingWorkflows, cohortBlockingWorkflowsModalLogic } from './cohortBlockingWorkflowsModalLogic'
+
+const meta: Meta = {
+ title: 'Scenes-App/People/Cohorts/Blocking Workflows Modal',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-07-04',
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+function OpenModal({ blocking }: { blocking: CohortBlockingWorkflows }): JSX.Element {
+ const { openBlockingWorkflowsModal } = useActions(cohortBlockingWorkflowsModalLogic)
+ useEffect(() => {
+ openBlockingWorkflowsModal(blocking)
+ }, [blocking, openBlockingWorkflowsModal])
+ return <CohortBlockingWorkflowsModal />
+}
+
+export const DeleteBlocked: Story = {
+ render: () => (
+ <OpenModal
+ blocking={{
+ action: 'delete',
+ workflows: {
+ results: [
+ { id: '0190a1b2-0000-0000-0000-000000000001', name: 'Welcome series', status: 'active' },
+ {
+ id: '0190a1b2-0000-0000-0000-000000000002',
+ name: 'Win back churned users',
+ status: 'active',
+ },
+ ],
+ total: 3,
+ hidden: 1,
+ has_more: true,
+ },
+ }}
+ />
+ ),
+}
+
+export const EditBlocked: Story = {
+ render: () => (
+ <OpenModal
+ blocking={{
+ action: 'edit',
+ workflows: {
+ results: [{ id: '0190a1b2-0000-0000-0000-000000000001', name: 'Welcome series', status: 'active' }],
+ total: 1,
+ hidden: 0,
+ has_more: false,
+ },
+ }}
+ />
+ ),
+}
+
+export const LockedFromDetails: Story = {
+ render: () => (
+ <OpenModal
+ blocking={{
+ action: 'view',
+ workflows: {
+ results: [
+ { id: '0190a1b2-0000-0000-0000-000000000001', name: 'Welcome series', status: 'active' },
+ {
+ id: '0190a1b2-0000-0000-0000-000000000002',
+ name: 'Win back churned users',
+ status: 'active',
+ },
+ ],
+ total: 2,
+ hidden: 0,
+ has_more: false,
+ },
+ }}
+ />
+ ),
+}
diff --git a/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.tsx b/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.tsx
new file mode 100644
index 000000000000..cc4b13c8a9cf
--- /dev/null
+++ b/frontend/src/scenes/cohorts/CohortBlockingWorkflowsModal.tsx
@@ -0,0 +1,64 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal, Link } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { CohortBlockedAction, cohortBlockingWorkflowsModalLogic } from './cohortBlockingWorkflowsModalLogic'
+
+const BLOCKING_COPY: Record<CohortBlockedAction, string> = {
+ delete: 'These workflows trigger on this cohort or branch on it. Remove the cohort from each workflow, or disable the workflow, then delete the cohort.',
+ edit: 'This change would stop the cohort updating in real time, and these workflows need real-time updates. Remove the cohort from each workflow, or disable the workflow, then save your change.',
+ view: "These workflows trigger on this cohort or branch on it, so the cohort is locked. You can't delete it or make a change that stops real-time updates. Remove the cohort from each workflow, or disable the workflow, to unlock it.",
+}
+
+export function CohortBlockingWorkflowsModal(): JSX.Element {
+ const { blocking } = useValues(cohortBlockingWorkflowsModalLogic)
+ const { closeBlockingWorkflowsModal } = useActions(cohortBlockingWorkflowsModalLogic)
+ const hiddenCount = blocking?.workflows.hidden ?? 0
+ // The API caps the list it returns, so some workflows the person can view may not be listed.
+ const unlistedCount = blocking ? blocking.workflows.total - hiddenCount - blocking.workflows.results.length : 0
+
+ return (
+ <LemonModal
+ isOpen={!!blocking}
+ onClose={closeBlockingWorkflowsModal}
+ title="This cohort is used by active workflows"
+ width={480}
+ footer={
+ <LemonButton type="secondary" onClick={closeBlockingWorkflowsModal}>
+ Close
+ </LemonButton>
+ }
+ >
+ {blocking && (
+ <div className="flex flex-col gap-y-3" data-attr="cohort-blocking-workflows">
+ <p className="mb-0">{BLOCKING_COPY[blocking.action]}</p>
+ {blocking.workflows.results.length > 0 && (
+ <ul className="list-disc pl-4 mb-0">
+ {blocking.workflows.results.map((workflow) => (
+ <li key={workflow.id}>
+ <Link
+ to={urls.workflow(workflow.id, 'workflow')}
+ onClick={closeBlockingWorkflowsModal}
+ data-attr="cohort-blocking-workflow-link"
+ >
+ {workflow.name || 'Untitled workflow'}
+ </Link>
+ </li>
+ ))}
+ {unlistedCount > 0 && <li className="text-secondary">and {unlistedCount} more</li>}
+ </ul>
+ )}
+ {hiddenCount > 0 && (
+ <p className="mb-0 text-secondary">
+ {hiddenCount === 1
+ ? "1 more workflow uses this cohort, but you don't have access to it. Ask someone who can edit it to remove the cohort."
+ : `${hiddenCount} more workflows use this cohort, but you don't have access to them. Ask someone who can edit them to remove the cohort.`}
+ </p>
+ )}
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
index 7403914d75e2..e8d67dd55810 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
@@ -665,6 +665,7 @@ describe('cohortEditLogic', () => {
has_more: true,
},
cohorts: { results: [], total: 0, has_more: false },
+ workflows: { results: [], total: 0, hidden: 0, has_more: false },
},
},
}
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index a1cc3554dba4..99d884421af5 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -66,6 +66,7 @@ import { messageAudienceOpenLogic } from 'products/workflows/frontend/MessageAud
import { AddPersonToCohortModal } from './AddPersonToCohortModal'
import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
+import { CohortBlockingWorkflowsModal } from './CohortBlockingWorkflowsModal'
import { cohortCountWarningLogic } from './cohortCountWarningLogic'
import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'
import { CohortSceneMenuBar } from './CohortSceneMenuBar'
@@ -221,6 +222,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
setStaticCohortMode,
setActiveTab,
setUsedInExpanded,
+ openBlockingWorkflowsModal,
submitCohort,
} = useActions(logic)
const modalLogic = addPersonToCohortModalLogic(logicProps)
@@ -290,6 +292,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
<BindLogic logic={cohortEditLogic} props={logicProps}>
<div className="cohort">
<AddPersonToCohortModal id={id} />
+ <CohortBlockingWorkflowsModal />
<CohortSceneMenuBar id={id} />
<ScenePanel>
@@ -526,6 +529,24 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
<Tooltip title="Create a new cohort to use a different type of cohort.">
<IconInfo className="text-secondary text-base" />
</Tooltip>
+ {usedIn && usedIn.workflows.total > 0 && (
+ <>
+ <span className="text-secondary">·</span>
+ <Link
+ className="text-sm"
+ onClick={() =>
+ openBlockingWorkflowsModal({
+ action: 'view',
+ workflows: usedIn.workflows,
+ })
+ }
+ data-attr="cohort-used-in-workflows"
+ >
+ Used in {usedIn.workflows.total}{' '}
+ {usedIn.workflows.total === 1 ? 'workflow' : 'workflows'}
+ </Link>
+ </>
+ )}
</div>
)}
diff --git a/frontend/src/scenes/cohorts/cohortBlockingWorkflows.ts b/frontend/src/scenes/cohorts/cohortBlockingWorkflows.ts
new file mode 100644
index 000000000000..4fc0122aa6bb
--- /dev/null
+++ b/frontend/src/scenes/cohorts/cohortBlockingWorkflows.ts
@@ -0,0 +1,30 @@
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api-error'
+
+import { cohortsBlockingWorkflowsRetrieve } from 'products/cohorts/frontend/generated/api'
+import type { CohortUsedInWorkflowsBlockApi } from 'products/cohorts/frontend/generated/api.schemas'
+
+// pinned: error code the cohort API returns when workflows block a change, see posthog/api/cohort.py
+export const COHORT_USED_BY_WORKFLOWS_ERROR_CODE = 'cohort_used_by_workflows'
+
+/**
+ * The active workflows that block deleting this cohort or editing it so it stops updating in real
+ * time, or null when nothing blocks it. A failed check returns null, because the API still refuses
+ * the change and the caller then shows the API error.
+ */
+export async function loadBlockingWorkflows(
+ projectId: number | string,
+ cohortId: number
+): Promise<CohortUsedInWorkflowsBlockApi | null> {
+ try {
+ const workflows = await cohortsBlockingWorkflowsRetrieve(String(projectId), cohortId)
+ return workflows.total ? workflows : null
+ } catch (error) {
+ // A 404 means the endpoint is not deployed yet, which is expected during a deploy.
+ if (!(error instanceof ApiError) || error.status !== 404) {
+ posthog.captureException(error, { feature: 'cohort-blocking-workflows' })
+ }
+ return null
+ }
+}
diff --git a/frontend/src/scenes/cohorts/cohortBlockingWorkflowsModalLogic.ts b/frontend/src/scenes/cohorts/cohortBlockingWorkflowsModalLogic.ts
new file mode 100644
index 000000000000..2120789c586a
--- /dev/null
+++ b/frontend/src/scenes/cohorts/cohortBlockingWorkflowsModalLogic.ts
@@ -0,0 +1,62 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import posthog from 'posthog-js'
+
+import type { CohortUsedInWorkflowsBlockApi } from 'products/cohorts/frontend/generated/api.schemas'
+
+// `view` opens the modal from the cohort's details, before anything is blocked.
+export type CohortBlockedAction = 'delete' | 'edit' | 'view'
+
+export interface CohortBlockingWorkflows {
+ action: CohortBlockedAction
+ workflows: CohortUsedInWorkflowsBlockApi
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface cohortBlockingWorkflowsModalLogicValues {
+ blocking: CohortBlockingWorkflows | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface cohortBlockingWorkflowsModalLogicActions {
+ closeBlockingWorkflowsModal: () => {
+ value: true
+ }
+ openBlockingWorkflowsModal: (blocking: CohortBlockingWorkflows) => {
+ blocking: CohortBlockingWorkflows
+ }
+}
+
+export type cohortBlockingWorkflowsModalLogicType = MakeLogicType<
+ cohortBlockingWorkflowsModalLogicValues,
+ cohortBlockingWorkflowsModalLogicActions
+>
+
+export const cohortBlockingWorkflowsModalLogic = kea<cohortBlockingWorkflowsModalLogicType>([
+ path(['scenes', 'cohorts', 'cohortBlockingWorkflowsModalLogic']),
+ actions({
+ openBlockingWorkflowsModal: (blocking: CohortBlockingWorkflows) => ({ blocking }),
+ closeBlockingWorkflowsModal: true,
+ }),
+ reducers({
+ blocking: [
+ null as CohortBlockingWorkflows | null,
+ {
+ openBlockingWorkflowsModal: (_, { blocking }) => blocking,
+ closeBlockingWorkflowsModal: () => null,
+ },
+ ],
+ }),
+ listeners({
+ openBlockingWorkflowsModal: ({ blocking }) => {
+ if (blocking.action === 'view') {
+ return
+ }
+ // pinned: analytics event name, renaming breaks dashboards
+ posthog.capture('cohort change blocked by workflows', {
+ action: blocking.action,
+ workflow_count: blocking.workflows.total,
+ hidden_workflow_count: blocking.workflows.hidden,
+ })
+ },
+ }),
+])
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 8261fda3d76a..8b1325be34ed 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -8,6 +8,7 @@ import { v4 as uuidv4 } from 'uuid'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { cohortBlockingWorkflowsModalLogic } from 'scenes/cohorts/cohortBlockingWorkflowsModalLogic'
import { CohortLogicProps, REALTIME_POLL_INTERVAL_MS, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { CRITERIA_VALIDATIONS, NEW_CRITERIA, ROWS } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
@@ -58,6 +59,7 @@ const mockUsedInResponse: CohortUsedInResponseApi = {
},
insights: { results: [], total: 0, has_more: false },
cohorts: { results: [], total: 0, has_more: false },
+ workflows: { results: [], total: 0, hidden: 0, has_more: false },
}
describe('cohortEditLogic', () => {
@@ -113,6 +115,15 @@ describe('cohortEditLogic', () => {
expect(logic.values.usedIn).toEqual(mockUsedInResponse)
})
+ it('treats a used-in response without a workflows block as no workflows', async () => {
+ const { workflows: _, ...olderResponse } = mockUsedInResponse
+ useMocks({ get: { '/api/projects/:team_id/cohorts/:id/used_in/': olderResponse } })
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
+
+ expect(logic.values.usedIn).toEqual(mockUsedInResponse)
+ })
+
it('swallows used-in 404s without reporting them', async () => {
useMocks({
get: {
@@ -411,6 +422,115 @@ describe('cohortEditLogic', () => {
)
})
+ describe('workflows that rely on the cohort', () => {
+ const blockingWorkflows = {
+ results: [{ id: 'flow-1', name: 'Welcome series', status: 'active' }],
+ total: 2,
+ hidden: 1,
+ has_more: true,
+ }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/used_in/': {
+ ...mockUsedInResponse,
+ workflows: blockingWorkflows,
+ },
+ '/api/projects/:team_id/cohorts/:id/blocking_workflows/': blockingWorkflows,
+ },
+ patch: {
+ '/api/projects/:team_id/cohorts/:id/': () => [
+ 400,
+ { type: 'validation_error', code: 'cohort_used_by_workflows', detail: 'Blocked', attr: null },
+ ],
+ },
+ })
+ })
+
+ it('lists the blocking workflows instead of deleting the cohort', async () => {
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic).toMatchValues({
+ usedIn: expect.objectContaining({ workflows: blockingWorkflows }),
+ })
+
+ await expectLogic(logic, () => logic.actions.deleteCohort())
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions([cohortsModel.actionTypes.deleteCohort])
+ expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual({
+ action: 'delete',
+ workflows: blockingWorkflows,
+ })
+ })
+
+ it('deletes on the next attempt once the blocking workflows are gone', async () => {
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic).toMatchValues({
+ usedIn: expect.objectContaining({ workflows: blockingWorkflows }),
+ })
+ useMocks({ get: { '/api/projects/:team_id/cohorts/:id/used_in/': mockUsedInResponse } })
+
+ await expectLogic(logic, () => logic.actions.deleteCohort()).toDispatchActions([
+ 'deleteCohort',
+ 'loadUsedIn',
+ 'loadUsedInSuccess',
+ ])
+ await expectLogic(logic, () => logic.actions.deleteCohort()).toDispatchActions([
+ cohortsModel.actionTypes.deleteCohort,
+ ])
+ })
+
+ it('does nothing after the blocked save workflow check when the editor has closed', async () => {
+ let releaseLookup: () => void = () => {}
+ const lookupHeld = new Promise<void>((resolve) => {
+ releaseLookup = resolve
+ })
+ let lookupStarted: () => void = () => {}
+ const started = new Promise<void>((resolve) => {
+ lookupStarted = resolve
+ })
+ let lookupAnswered: () => void = () => {}
+ const answered = new Promise<void>((resolve) => {
+ lookupAnswered = resolve
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/blocking_workflows/': async () => {
+ lookupStarted()
+ await lookupHeld
+ lookupAnswered()
+ return [200, blockingWorkflows]
+ },
+ },
+ })
+ await initCohortLogic({ id: 1 })
+ // The cohorts list keeps the modal logic mounted after the editor closes.
+ cohortBlockingWorkflowsModalLogic.mount()
+ const deleteSpy = jest.spyOn(cohortsModel.actions, 'deleteCohort')
+
+ logic.actions.saveCohort()
+ await started
+ logic.unmount()
+ releaseLookup()
+ await answered
+ await expectLogic(cohortsModel).toFinishAllListeners()
+
+ expect(deleteSpy).not.toHaveBeenCalled()
+ expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual(null)
+ })
+
+ it('lists the blocking workflows when the API refuses an edit that stops realtime updates', async () => {
+ await initCohortLogic({ id: 1 })
+
+ await expectLogic(logic, () => logic.actions.saveCohort()).toFinishAllListeners()
+ expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual({
+ action: 'edit',
+ workflows: blockingWorkflows,
+ })
+ expect(lemonToast.error).not.toHaveBeenCalledWith('Blocked')
+ })
+ })
+
describe('form validation', () => {
it('save with valid cohort', async () => {
await initCohortLogic({ id: 1 })
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 9d8212622f3e..72c7df93e428 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -31,6 +31,8 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { objectsEqual } from 'lib/utils/objects'
import { isOperatorDate } from 'lib/utils/operators'
+import { COHORT_USED_BY_WORKFLOWS_ERROR_CODE, loadBlockingWorkflows } from 'scenes/cohorts/cohortBlockingWorkflows'
+import { cohortBlockingWorkflowsModalLogic } from 'scenes/cohorts/cohortBlockingWorkflowsModalLogic'
import { NEW_COHORT, NEW_CRITERIA, NEW_CRITERIA_GROUP } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import {
@@ -156,6 +158,11 @@ export interface cohortEditLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cohortEditLogicActions {
+ openBlockingWorkflowsModal: (
+ blocking: import('scenes/cohorts/cohortBlockingWorkflowsModalLogic').CohortBlockingWorkflows
+ ) => {
+ blocking: import('scenes/cohorts/cohortBlockingWorkflowsModalLogic').CohortBlockingWorkflows
+ } // cohortBlockingWorkflowsModalLogic
reportExperimentExposureCohortEdited: (
existingCohort: CohortType,
newCohort: CohortType
@@ -548,7 +555,12 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
path(['scenes', 'cohorts', 'cohortLogicEdit']),
connect(() => ({
values: [teamLogic, ['currentProjectId']],
- actions: [eventUsageLogic, ['reportExperimentExposureCohortEdited']],
+ actions: [
+ eventUsageLogic,
+ ['reportExperimentExposureCohortEdited'],
+ cohortBlockingWorkflowsModalLogic,
+ ['openBlockingWorkflowsModal'],
+ ],
logic: [cohortsModel],
})),
@@ -985,6 +997,18 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
})
}
+ if (error.code === COHORT_USED_BY_WORKFLOWS_ERROR_CODE && typeof cohort.id === 'number') {
+ const workflows = await loadBlockingWorkflows(values.currentProjectId, cohort.id)
+ breakpoint()
+ if (workflows) {
+ actions.openBlockingWorkflowsModal({
+ action: 'edit',
+ workflows,
+ })
+ return values.cohort
+ }
+ }
+
lemonToast.error(error.detail || 'Failed to save cohort')
return values.cohort
}
@@ -1099,7 +1123,12 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
return null
}
try {
- return await cohortsUsedInRetrieve(String(values.currentProjectId), Number(id))
+ const usedIn = await cohortsUsedInRetrieve(String(values.currentProjectId), Number(id))
+ // A backend from before the workflows block returns no `workflows` key during a deploy.
+ return {
+ ...usedIn,
+ workflows: usedIn.workflows ?? { results: [], total: 0, hidden: 0, has_more: false },
+ }
} catch (error) {
// A 404 just means the endpoint isn't deployed yet (deploy skew) or the
// cohort is gone; neither is worth reporting.
@@ -1152,6 +1181,14 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
}
},
deleteCohort: () => {
+ // The editor already loaded what uses the cohort, so blocking workflows show without another request.
+ const workflows = values.usedIn?.workflows
+ if (workflows?.total) {
+ actions.openBlockingWorkflowsModal({ action: 'delete', workflows })
+ // Workflows can change in another tab, so refresh what the next delete attempt checks.
+ actions.loadUsedIn()
+ return
+ }
cohortsModel.actions.deleteCohort({ id: values.cohort.id, name: values.cohort.name })
},
removePersonFromCohort: async ({ personId }) => {
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 3526399ede80..840c5ba4c8be 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -154,28 +154,44 @@ def _workflows_relying_on_cohort(cohort: Cohort) -> list[CohortDependentWorkflow
return get_active_workflows_using_realtime_cohort(team_id=cohort.team_id, cohort_ids=cohort_ids)
-def _workflow_names_suffix(
+def _visible_workflows(
request: Request,
user_access_control: Optional[UserAccessControl],
team_id: int,
workflows: list[CohortDependentWorkflow],
-) -> str:
- # The caller sees the names of the workflows it can view. The count covers every workflow.
+) -> list[CohortDependentWorkflow]:
+ # The caller sees the workflows it can view. Callers count every workflow.
scopes = get_authenticator_scopes(request.successful_authenticator)
if user_access_control is None or (
scopes is not None and not {"*", "hog_flow:read", "hog_flow:write"} & set(scopes)
):
- return ""
+ return []
references = [
HogFlowReference(id=workflow.id, name=workflow.name, status=workflow.status) for workflow in workflows
]
- visible = filter_hog_flow_references_by_access_level(team_id, {"blocking": references}, user_access_control).get(
- "blocking", []
- )
+ visible_ids = {
+ reference.id
+ for reference in filter_hog_flow_references_by_access_level(
+ team_id, {"blocking": references}, user_access_control
+ ).get("blocking", [])
+ }
+ return [workflow for workflow in workflows if workflow.id in visible_ids]
+
+
+def _workflow_names_suffix(
+ request: Request,
+ user_access_control: Optional[UserAccessControl],
+ team_id: int,
+ workflows: list[CohortDependentWorkflow],
+) -> str:
+ visible = _visible_workflows(request, user_access_control, team_id, workflows)
if not visible:
return ""
hidden = len(workflows) - len(visible)
- return f": {', '.join(reference.name for reference in visible)}" + (f" and {hidden} more" if hidden else "")
+ return f": {', '.join(workflow.name for workflow in visible)}" + (f" and {hidden} more" if hidden else "")
+
+
+COHORT_USED_BY_WORKFLOWS_ERROR_CODE = "cohort_used_by_workflows"
class CohortPersonsResponseSerializer(serializers.Serializer):
@@ -592,6 +608,14 @@ class CohortUsedInCohortSerializer(serializers.Serializer):
name = serializers.CharField(help_text="Cohort display name; falls back to 'Unnamed' when empty")
+class CohortUsedInWorkflowSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Workflow ID (UUID)")
+ name = serializers.CharField(allow_blank=True, help_text="Workflow display name")
+ status = serializers.CharField(
+ help_text="Workflow status. Always 'active', because only active workflows rely on the cohort"
+ )
+
+
class CohortUsedInFlagsBlockSerializer(serializers.Serializer):
results = CohortUsedInFlagSerializer(
many=True, help_text=f"Feature flags referencing this cohort, capped at {COHORT_USED_IN_PAGE_SIZE} results"
@@ -619,6 +643,22 @@ class CohortUsedInCohortsBlockSerializer(serializers.Serializer):
has_more = serializers.BooleanField(help_text="True when more cohorts exist beyond the truncation cap")
+class CohortUsedInWorkflowsBlockSerializer(serializers.Serializer):
+ results = CohortUsedInWorkflowSerializer(
+ many=True,
+ help_text=(
+ f"Active workflows relying on this cohort that the caller can view, capped at {COHORT_USED_IN_PAGE_SIZE} results"
+ ),
+ )
+ total = serializers.IntegerField(
+ help_text="Total number of active workflows relying on this cohort, including ones the caller cannot view"
+ )
+ hidden = serializers.IntegerField(
+ help_text="Number of relying workflows the caller cannot view. They count toward total but are never listed"
+ )
+ has_more = serializers.BooleanField(help_text="True when some relying workflows are not listed in results")
+
+
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",
@@ -629,6 +669,12 @@ class CohortUsedInResponseSerializer(serializers.Serializer):
cohorts = CohortUsedInCohortsBlockSerializer(
help_text="Other cohorts that include this cohort as a criterion, with truncation metadata"
)
+ workflows = CohortUsedInWorkflowsBlockSerializer(
+ help_text=(
+ "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."
+ )
+ )
class CohortCalculationHistorySerializer(serializers.ModelSerializer):
@@ -1669,7 +1715,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
raise ValidationError(
f"This change stops the cohort updating in real time, and {len(workflows_relying_on_realtime)} "
f"active workflow(s) rely on that{names}. "
- "Please remove the cohort from these workflows before making this change."
+ "Please remove the cohort from these workflows before making this change.",
+ code=COHORT_USED_BY_WORKFLOWS_ERROR_CODE,
)
deleted_state = cast(bool | None, validated_data.get("deleted"))
@@ -1698,7 +1745,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
)
raise ValidationError(
f"This cohort is used in {len(workflows_with_cohort)} active workflow(s){names}. "
- "Please remove the cohort from these workflows before deleting it."
+ "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
@@ -1823,6 +1871,18 @@ def _used_in_block(page: list[dict], total: int) -> dict[str, Any]:
return {"results": page, "total": total, "has_more": total > len(page)}
+def _workflows_block(
+ request: Request, user_access_control: Optional[UserAccessControl], cohort: Cohort
+) -> dict[str, Any]:
+ workflows = _workflows_relying_on_cohort(cohort)
+ visible = _visible_workflows(request, user_access_control, cohort.team_id, workflows)
+ page = [
+ {"id": workflow.id, "name": workflow.name, "status": workflow.status}
+ for workflow in visible[:COHORT_USED_IN_PAGE_SIZE]
+ ]
+ return {**_used_in_block(page, len(workflows)), "hidden": len(workflows) - len(visible)}
+
+
def _truncate_used_in_queryset(qs: QuerySet) -> tuple[list[dict], int]:
"""Return up to COHORT_USED_IN_PAGE_SIZE rows plus the total count.
@@ -2400,9 +2460,19 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
"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),
+ "workflows": _workflows_block(request, uac, cohort),
}
)
+ @extend_schema(
+ description="Active workflows that block deleting this cohort or editing it so it stops updating in real time.",
+ responses=CohortUsedInWorkflowsBlockSerializer,
+ )
+ @action(methods=["GET"], detail=True, required_scopes=["cohort:read"])
+ def blocking_workflows(self, request: request.Request, **kwargs) -> Response:
+ cohort: Cohort = self.get_object()
+ return Response(_workflows_block(request, self.user_access_control, cohort))
+
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 8b2f6952d86e..968092d0a81f 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -7269,6 +7269,7 @@ class TestCohortTypeIntegration(APIBaseTest):
assert response.status_code == expected, response.json()
if expected == 400:
assert f"used in 1 active workflow(s): Workflow {usage}" in response.json()["detail"]
+ assert response.json()["code"] == "cohort_used_by_workflows"
@parameterized.expand(
[
@@ -7312,6 +7313,39 @@ class TestCohortTypeIntegration(APIBaseTest):
assert "used in 2 active workflow(s): Workflow branch and 1 more." in response.json()["detail"]
assert "Workflow trigger" not in response.json()["detail"]
+ @parameterized.expand([("used_in", "workflows"), ("blocking_workflows", None)])
+ def test_lists_viewable_workflows_relying_on_the_cohort(self, path, key):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ cohort_id = self._create_realtime_cohort()
+ hidden_id = self._create_workflow_using_cohort(cohort_id, "trigger", "active")
+ visible_ids = {
+ self._create_workflow_using_cohort(cohort_id, "branch", "active"),
+ self._create_workflow_using_cohort(cohort_id, "branch_precalculated", "active"),
+ }
+ self._create_workflow_using_cohort(cohort_id, "branch", "draft")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="hog_flow",
+ resource_id=hidden_id,
+ access_level="none",
+ organization_member=self.organization_membership,
+ )
+
+ with patch("posthog.api.cohort.COHORT_USED_IN_PAGE_SIZE", 1):
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/{path}/")
+
+ assert response.status_code == 200, response.json()
+ workflows = response.json()[key] if key else response.json()
+ assert [workflow["id"] for workflow in workflows["results"]] in [[visible_id] for visible_id in visible_ids]
+ assert {key: workflows[key] for key in ("total", "hidden", "has_more")} == {
+ "total": 3,
+ "hidden": 1,
+ "has_more": True,
+ }
+
def test_edit_that_stops_realtime_is_blocked_by_active_workflows_using_it(self):
cohort_id = self._create_realtime_cohort()
self._create_workflow_using_cohort(cohort_id, "trigger", "active")
@@ -7329,6 +7363,7 @@ class TestCohortTypeIntegration(APIBaseTest):
assert response.status_code == 400, response.json()
assert "stops the cohort updating in real time" in response.json()["detail"]
+ assert response.json()["code"] == "cohort_used_by_workflows"
assert Cohort.objects.get(id=cohort_id).cohort_type == CohortType.REALTIME
def test_edit_that_stops_realtime_is_blocked_by_workflows_on_a_cohort_that_includes_it(self):
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 3b26f21523d7..24c1709edd0a 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -525,6 +525,26 @@ export interface PatchedAddPersonsToStaticCohortRequestApi {
person_ids?: string[]
}
+export interface CohortUsedInWorkflowApi {
+ /** Workflow ID (UUID) */
+ id: string
+ /** Workflow display name */
+ name: string
+ /** Workflow status. Always 'active', because only active workflows rely on the cohort */
+ status: string
+}
+
+export interface CohortUsedInWorkflowsBlockApi {
+ /** Active workflows relying on this cohort that the caller can view, capped at 100 results */
+ results: CohortUsedInWorkflowApi[]
+ /** Total number of active workflows relying on this cohort, including ones the caller cannot view */
+ total: number
+ /** Number of relying workflows the caller cannot view. They count toward total but are never listed */
+ hidden: number
+ /** True when some relying workflows are not listed in results */
+ has_more: boolean
+}
+
/**
* The actor's properties.
*/
@@ -644,6 +664,8 @@ export interface CohortUsedInResponseApi {
insights: CohortUsedInInsightsBlockApi
/** Other cohorts that include this cohort as a criterion, with truncation metadata */
cohorts: CohortUsedInCohortsBlockApi
+ /** 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
}
export type CohortsStaffListParams = {
diff --git a/products/cohorts/frontend/generated/api.ts b/products/cohorts/frontend/generated/api.ts
index 463600471208..8d6179d054f2 100644
--- a/products/cohorts/frontend/generated/api.ts
+++ b/products/cohorts/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
CohortApi,
CohortPersonsResponseApi,
CohortUsedInResponseApi,
+ CohortUsedInWorkflowsBlockApi,
CohortsListParams,
CohortsPersonsRetrieveParams,
CohortsStaffListParams,
@@ -263,6 +264,24 @@ export const cohortsAddPersonsToStaticCohortPartialUpdate = async (
})
}
+export const getCohortsBlockingWorkflowsRetrieveUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/cohorts/${id}/blocking_workflows/`
+}
+
+/**
+ * Active workflows that block deleting this cohort or editing it so it stops updating in real time.
+ */
+export const cohortsBlockingWorkflowsRetrieve = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<CohortUsedInWorkflowsBlockApi> => {
+ return apiMutator<CohortUsedInWorkflowsBlockApi>(getCohortsBlockingWorkflowsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCohortsCalculationHistoryRetrieveUrl = (projectId: string, id: number) => {
return `/api/projects/${projectId}/cohorts/${id}/calculation_history/`
}
diff --git a/products/workflows/backend/services/cohort_usage.py b/products/workflows/backend/services/cohort_usage.py
index 32f90bd97182..c3ef7b73ee77 100644
--- a/products/workflows/backend/services/cohort_usage.py
+++ b/products/workflows/backend/services/cohort_usage.py
@@ -1,6 +1,9 @@
from collections.abc import Collection, Iterator
from typing import Any
+from django.db.models import TextField
+from django.db.models.functions import Cast
+
from products.cdp.backend.presentation.hog_functions import filter_cohort_ids
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
@@ -25,7 +28,13 @@ def get_active_hog_flows_using_realtime_cohort(team_id: int, cohort_ids: Collect
cohort trigger or in a conditional branch."""
# Only the fields the check reads, streamed: full rows carry encrypted inputs and the whole graph.
ids = set(cohort_ids)
- flows = HogFlow.objects.filter(team_id=team_id, status=HogFlow.State.ACTIVE).only("id", "name", "status", "actions")
+ # Postgres skips workflows whose actions never mention a cohort, so only those graphs reach Python.
+ flows = (
+ HogFlow.objects.filter(team_id=team_id, status=HogFlow.State.ACTIVE)
+ .alias(actions_text=Cast("actions", output_field=TextField()))
+ .filter(actions_text__contains="cohort")
+ .only("id", "name", "status", "actions")
+ )
for flow in flows.iterator():
if any(_action_uses_realtime_cohort(action, ids) for action in (flow.actions or [])):
yield flow
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6d8b30e2d3cf..fa5597dfd4a2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23921,6 +23921,26 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface CohortUsedInWorkflow {
+ /** Workflow ID (UUID) */
+ id: string;
+ /** Workflow display name */
+ name: string;
+ /** Workflow status. Always 'active', because only active workflows rely on the cohort */
+ status: string;
+ }
+
+ export interface CohortUsedInWorkflowsBlock {
+ /** Active workflows relying on this cohort that the caller can view, capped at 100 results */
+ results: CohortUsedInWorkflow[];
+ /** Total number of active workflows relying on this cohort, including ones the caller cannot view */
+ total: number;
+ /** Number of relying workflows the caller cannot view. They count toward total but are never listed */
+ hidden: number;
+ /** True when some relying workflows are not listed in results */
+ 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;
@@ -23928,6 +23948,8 @@ export namespace Schemas {
insights: CohortUsedInInsightsBlock;
/** Other cohorts that include this cohort as a criterion, with truncation metadata */
cohorts: CohortUsedInCohortsBlock;
+ /** 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;
}
/**