: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
feat(workflows): lock cohorts that active workflows rely on (#117007)
Harley Alexandere23ba9ec74e7
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 8a34e5ecb358..ef5c283bbcd3 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -3,6 +3,7 @@ import jsonimport timeimport uuidimport hashlib+from collections import defaultdictfrom collections.abc import Iterable, Iterator, Sequencefrom copy import deepcopyfrom typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast@@ -80,12 +81,14 @@ from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS, Profrom posthog.models.property.relative_date import determine_parsed_date_for_property_matchingfrom posthog.models.team.team import DEPRECATED_ATTRS, Teamfrom posthog.models.utils import UUIDT+from posthog.permissions import get_authenticator_scopesfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.renderers import SafeJSONRendererfrom posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_eventfrom posthog.utils import format_query_params_absolute_url, str_to_bool+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.cdp.backend.filters import build_behavioral_event_exprfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import (@@ -96,7 +99,10 @@ from products.cohorts.backend.models.cohort import (CohortType,Group,)-from products.cohorts.backend.models.dependencies import get_flag_excluded_behavioral_cohort_ids+from products.cohorts.backend.models.dependencies import (+ extract_cohort_dependencies,+ get_flag_excluded_behavioral_cohort_ids,+)from products.cohorts.backend.models.util import (CohortErrorCode,cohort_filters_have_values,@@ -122,6 +128,53 @@ from products.feature_flags.backend.models.team_feature_flags_config import ()from products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabledfrom products.product_analytics.backend.facade.models import Insight+from products.workflows.backend.facade.api import (+ filter_hog_flow_references_by_access_level,+ get_active_workflows_using_realtime_cohort,+)+from products.workflows.backend.facade.contracts import CohortDependentWorkflow, HogFlowReference+++def _workflows_relying_on_cohort(cohort: Cohort) -> list[CohortDependentWorkflow]:+ # A cohort that includes this one as a criterion reads its membership, so a workflow on that cohort+ # also relies on this one. Load the project's cohort references in one query and walk them in memory.+ dependents: defaultdict[int, set[int]] = defaultdict(set)+ for other in Cohort.objects.filter(team__project_id=cohort.team.project_id, deleted=False).only(+ "id", "filters", "groups", "deleted"+ ):+ for dependency_id in extract_cohort_dependencies(other):+ dependents[dependency_id].add(other.id)+ cohort_ids = {cohort.id}+ pending = [cohort.id]+ while pending:+ for dependent_id in dependents[pending.pop()] - cohort_ids:+ cohort_ids.add(dependent_id)+ pending.append(dependent_id)+ return get_active_workflows_using_realtime_cohort(team_id=cohort.team_id, cohort_ids=cohort_ids)+++def _workflow_names_suffix(+ 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.+ 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 ""+ 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", []+ )+ 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 "")class CohortPersonsResponseSerializer(serializers.Serializer):@@ -1495,6 +1548,9 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializcode="behavioral_cohort_found",)+ def _user_access_control(self) -> Optional[UserAccessControl]:+ return getattr(self.context.get("view"), "user_access_control", None)+def update(self, cohort: Cohort, validated_data: dict, *args: Any, **kwargs: Any) -> Cohort: # type: ignorerequest = self.context["request"]existing_has_criteria = cohort_filters_have_values(cohort.filters)@@ -1506,6 +1562,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializif create_in_folder is not None:cohort._create_in_folder = create_in_folder or None+ was_realtime = cohort.cohort_type == CohortType.REALTIME and not cohort.is_static+cohort.name = validated_data.get("name", cohort.name)cohort.description = validated_data.get("description", cohort.description)cohort.groups = validated_data.get("groups", cohort.groups)@@ -1530,6 +1588,20 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializelse:cohort.filters = filters+ # A cohort that stops being realtime stops emitting membership changes, so its workflows would+ # never trigger and their branches would read frozen membership, with no error anywhere.+ if was_realtime and (cohort.is_static or cohort.cohort_type != CohortType.REALTIME):+ workflows_relying_on_realtime = _workflows_relying_on_cohort(cohort)+ if workflows_relying_on_realtime:+ names = _workflow_names_suffix(+ request, self._user_access_control(), cohort.team_id, workflows_relying_on_realtime+ )+ 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."+ )+deleted_state = cast(bool | None, validated_data.get("deleted"))incoming_has_criteria = cohort_filters_have_values(validated_data.get("filters"))@@ -1549,6 +1621,16 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ"Please remove the cohort from these feature flags before deleting it.")+ 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(+ f"This cohort is used in {len(workflows_with_cohort)} active workflow(s){names}. "+ "Please remove the cohort from these workflows before deleting it."+ )+# Check if cohort is used in test_account_filtersteams_with_cohort = Team.objects.filter(project_id=cohort.team.project_id,diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 8d2f32cb4589..51ae5c39e102 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -28,6 +28,7 @@ from posthog.schema import PersonsOnEventsMode, PropertyOperatorfrom posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortFiltersfrom posthog.clickhouse.client.execute import sync_execute+from posthog.constants import AvailableFeaturefrom posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.async_deletion.async_deletion import AsyncDeletion@@ -46,6 +47,7 @@ from posthog.tasks.calculate_cohort import (from posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.persons import create_person+from products.access_control.backend.models.access_control import AccessControlfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillTriggerfrom products.cohorts.backend.models.cohort import DEFAULT_COHORT_INSERT_BATCH_SIZE, Cohort, CohortType@@ -56,6 +58,7 @@ from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfigfrom products.product_analytics.backend.facade.models import Insight+from products.workflows.backend.facade.testing import create_workflow_for_testfrom ee.clickhouse.materialized_columns.analyze import materialize@@ -7045,6 +7048,146 @@ class TestCohortTypeIntegration(APIBaseTest):self.assertEqual(cohort.cohort_type, CohortType.BEHAVIORAL) # Should remain unchangedself.assertEqual(response.data["cohort_type"], CohortType.BEHAVIORAL)+ def _create_realtime_cohort(self) -> int:+ filters = {+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ }+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/", {"name": "Realtime", "filters": filters}, format="json"+ )+ assert response.status_code == 201, response.data+ assert response.data["cohort_type"] == CohortType.REALTIME+ return response.data["id"]++ def _create_workflow_using_cohort(self, cohort_id: int, usage: str, status: str) -> str:+ if usage == "trigger":+ action = {"id": "trigger_node", "type": "trigger", "config": {"type": "cohort", "cohort_id": cohort_id}}+ else:+ filter_type = "precalculated-cohort" if usage == "branch_precalculated" else "cohort"+ condition = {"filters": {"properties": [{"key": "id", "type": filter_type, "value": cohort_id}]}}+ action = {"id": "branch", "type": "conditional_branch", "config": {"conditions": [condition]}}+ return create_workflow_for_test(+ team_id=self.team.id, name=f"Workflow {usage}", status=status, actions=[action]+ ).id++ @parameterized.expand(+ [+ ("active_trigger", "trigger", "active", 400),+ ("active_branch", "branch", "active", 400),+ ("active_branch_precalculated", "branch_precalculated", "active", 400),+ ("draft_trigger", "trigger", "draft", 200),+ ]+ )+ def test_delete_cohort_is_blocked_by_active_workflows_using_it(self, _name, usage, workflow_status, expected):+ cohort_id = self._create_realtime_cohort()+ self._create_workflow_using_cohort(cohort_id, usage, workflow_status)++ response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", {"deleted": True})++ assert response.status_code == expected, response.json()+ if expected == 400:+ assert f"used in 1 active workflow(s): Workflow {usage}" in response.json()["detail"]++ @parameterized.expand(+ [+ ("without_workflow_read", ["cohort:write"], False),+ ("with_workflow_read", ["cohort:write", "hog_flow:read"], True),+ ]+ )+ def test_blocked_delete_names_workflows_only_for_workflow_readers(self, _name, scopes, names_shown):+ cohort_id = self._create_realtime_cohort()+ self._create_workflow_using_cohort(cohort_id, "trigger", "active")+ key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}", {"deleted": True}, HTTP_AUTHORIZATION=f"Bearer {key}"+ )++ assert response.status_code == 400, response.json()+ assert "used in 1 active workflow(s)" in response.json()["detail"]+ assert ("Workflow trigger" in response.json()["detail"]) == names_shown++ def test_blocked_delete_hides_names_of_workflows_the_member_cannot_view(self):+ 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")+ self._create_workflow_using_cohort(cohort_id, "branch", "active")+ AccessControl.objects.create(+ team=self.team,+ resource="hog_flow",+ resource_id=hidden_id,+ access_level="none",+ organization_member=self.organization_membership,+ )++ response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", {"deleted": True})++ assert response.status_code == 400, response.json()+ assert "used in 2 active workflow(s): Workflow branch and 1 more." in response.json()["detail"]+ assert "Workflow trigger" not in response.json()["detail"]++ 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")+ filters = {+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ },+ "filterTestAccounts": True,+ }++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}", {"filters": filters}, format="json"+ )++ assert response.status_code == 400, response.json()+ assert "stops the cohort updating in real time" in response.json()["detail"]+ 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):+ included_id = self._create_realtime_cohort()+ including_id = included_id+ for name in ("Includes realtime", "Includes that one"):+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {+ "name": name,+ "filters": {+ "properties": {+ "type": "AND",+ "values": [{"type": "cohort", "key": "id", "value": including_id}],+ }+ },+ },+ format="json",+ )+ assert response.status_code == 201, response.json()+ assert response.json()["cohort_type"] == CohortType.REALTIME+ including_id = response.json()["id"]+ self._create_workflow_using_cohort(including_id, "trigger", "active")+ filters = {+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ },+ "filterTestAccounts": True,+ }++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{included_id}", {"filters": filters}, format="json"+ )++ assert response.status_code == 400, response.json()+ assert "1 active workflow(s) rely on that: Workflow trigger." in response.json()["detail"]+def test_cohort_type_not_set_when_not_provided(self):"""cohort_type should remain None when not provided"""diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex fe64acad1927..85a9966a7f3e 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -1,4 +1,4 @@-from collections.abc import Iterable+from collections.abc import Collection, Iterablefrom typing import Anyfrom uuid import UUID@@ -9,6 +9,7 @@ from posthog.ingress.contracts import WebhookDeliveryfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.workflows.backend.facade.contracts import (+ CohortDependentWorkflow,EmailDomainDnsRecord,EmailDomainVerification,RecentWorkflow,@@ -223,6 +224,20 @@ def get_active_workflows_using_integration(*, team_id: int, integration_id: int)]+def get_active_workflows_using_realtime_cohort(+ *, team_id: int, cohort_ids: Collection[int]+) -> list[CohortDependentWorkflow]:+ # Deferred to keep the cdp filter compiler, and the HogQL schema it loads, off the django.setup() path.+ from products.workflows.backend.services.cohort_usage import ( # noqa: PLC0415+ get_active_hog_flows_using_realtime_cohort,+ )++ return [+ CohortDependentWorkflow(id=str(flow.id), name=flow.name or "", status=flow.status)+ for flow in get_active_hog_flows_using_realtime_cohort(team_id=team_id, cohort_ids=cohort_ids)+ ]++def recompute_email_sending_tier(team_id: int) -> TierDecision | None:# Deferred to keep the ClickHouse metrics client off the facade import path.from products.workflows.backend.services.email_sending_tier import ( # noqa: PLC0415diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 75d5abe69e10..638add89a373 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -28,6 +28,13 @@ class WorkflowSummary:status: str+@frozen+class CohortDependentWorkflow:+ id: str+ name: str+ status: str++@frozenclass RecentWorkflow:id: strdiff --git a/products/workflows/backend/services/cohort_usage.py b/products/workflows/backend/services/cohort_usage.pynew file mode 100644index 000000000000..32f90bd97182--- /dev/null+++ b/products/workflows/backend/services/cohort_usage.py@@ -0,0 +1,31 @@+from collections.abc import Collection, Iterator+from typing import Any++from products.cdp.backend.presentation.hog_functions import filter_cohort_ids+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+++def _action_uses_realtime_cohort(action: Any, cohort_ids: set[int]) -> bool:+ if not isinstance(action, dict):+ return False+ config = action.get("config") or {}+ if action.get("type") == "trigger":+ return config.get("type") == "cohort" and config.get("cohort_id") in cohort_ids+ if action.get("type") == "conditional_branch":+ return any(+ not cohort_ids.isdisjoint(filter_cohort_ids(condition.get("filters")))+ for condition in config.get("conditions") or []+ if isinstance(condition, dict)+ )+ return False+++def get_active_hog_flows_using_realtime_cohort(team_id: int, cohort_ids: Collection[int]) -> Iterator[HogFlow]:+ """Active workflows in the environment that read the realtime membership of any of these cohorts, as a+ 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")+ for flow in flows.iterator():+ if any(_action_uses_realtime_cohort(action, ids) for action in (flow.actions or [])):+ yield flow