Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(cohorts): cache behavioral cohort exclusion for flag list (#65602)

Gustavo H. Strassburger67d953b1c2b0
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 3b73f90ffd29..463e9e25ff2e 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -3,7 +3,6 @@ import json
import time
import uuid
import hashlib
-from collections import defaultdict
from collections.abc import Iterator
from typing import Annotated, Any, Literal, Optional, Union, cast
@@ -78,6 +77,7 @@ from products.cohorts.backend.models.cohort import (
CohortOrEmpty,
CohortType,
)
+from products.cohorts.backend.models.dependencies import get_flag_excluded_behavioral_cohort_ids
from products.cohorts.backend.models.util import (
CohortErrorCode,
cohort_filters_have_values,
@@ -1379,16 +1379,11 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
from products.feature_flags.backend.api.feature_flag import _is_realtime_cohort_flag_targeting_enabled
allow_realtime_backfilled = _is_realtime_cohort_flag_targeting_enabled(self.request)
- # Lists every column read by _find_behavioral_cohorts (is_static, filters)
- # and Cohort.is_flag_compatible (cohort_type, last_backfill_person_properties_at);
- # dropping one triggers a per-cohort deferred query (an N+1 that only bites a
- # team with thousands of cohorts). Deferring the rest keeps the graph scan cheap.
- graph_source = queryset.only(
- "id", "is_static", "filters", "cohort_type", "last_backfill_person_properties_at"
- )
- all_cohorts = {cohort.id: cohort for cohort in graph_source.all()}
- behavioral_cohort_ids = self._find_behavioral_cohorts(
- all_cohorts, allow_realtime_backfilled=allow_realtime_backfilled
+ # The flag's cohort typeahead hits this endpoint on every keystroke, so the
+ # behavioral set is computed once per team and cached (invalidated on cohort
+ # writes); see get_flag_excluded_behavioral_cohort_ids.
+ behavioral_cohort_ids = get_flag_excluded_behavioral_cohort_ids(
+ self.team_id, allow_realtime_backfilled=allow_realtime_backfilled
)
queryset = queryset.exclude(id__in=behavioral_cohort_ids)
@@ -1420,86 +1415,6 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
.order_by("-created_at")
)
- def _find_behavioral_cohorts(
- self, all_cohorts: dict[int, Cohort], *, allow_realtime_backfilled: bool = False
- ) -> set[int]:
- """Find cohorts that are behavioral, or reference (transitively) a behavioral cohort.
-
- A cohort is affected if it's a behavioral seed, or references one through the
- dependency graph. We walk the *reverse* graph once from the seeds (O(V+E)) —
- every node that can reach a seed via forward edges is affected.
-
- When allow_realtime_backfilled is True, realtime cohorts that have been backfilled
- are not seeds: they can be evaluated via the cohort_membership table during flag
- evaluation. (They can still be pulled in if they reference another seed.)
- """
- graph, behavioral_cohorts = self._build_cohort_dependency_graph(all_cohorts)
-
- flag_compatible: set[int] = set()
- if allow_realtime_backfilled:
- flag_compatible = {
- cid for cid in behavioral_cohorts if (cohort := all_cohorts.get(cid)) and cohort.is_flag_compatible
- }
- seeds = behavioral_cohorts - flag_compatible
-
- # Reverse adjacency: target -> sources that reference it.
- reverse: dict[int, set[int]] = defaultdict(set)
- for source_id, targets in graph.items():
- for target_id in targets:
- reverse[target_id].add(source_id)
-
- affected = set(seeds)
- stack = list(seeds)
- while stack:
- node = stack.pop()
- for source_id in reverse.get(node, ()):
- if source_id not in affected:
- affected.add(source_id)
- stack.append(source_id)
-
- return affected
-
- def _build_cohort_dependency_graph(self, all_cohorts: dict[int, Cohort]) -> tuple[dict[int, set[int]], set[int]]:
- """
- Builds a directed graph of cohort dependencies and identifies behavioral cohorts.
- Returns (adjacency_list, behavioral_cohort_ids).
- """
- graph = defaultdict(set)
- behavioral_cohorts = set()
-
- def check_property_values(values: Any, source_id: int) -> None:
- """Process property values to build graph edges and identify behavioral cohorts."""
- if not isinstance(values, list):
- return
-
- for value in values:
- if not isinstance(value, dict):
- continue
-
- if value.get("type") == "behavioral":
- behavioral_cohorts.add(source_id)
- elif value.get("type") == "cohort":
- try:
- target_id = int(value.get("value", "0"))
- if target_id in all_cohorts:
- graph[source_id].add(target_id)
- except ValueError:
- continue
- elif value.get("type") in ("AND", "OR") and value.get("values"):
- check_property_values(value["values"], source_id)
-
- for cohort_id, cohort in all_cohorts.items():
- # Static cohorts have pre-computed membership and don't re-evaluate
- # their filters, so they're always safe to use regardless of filter type.
- if cohort.is_static:
- continue
- if cohort.filters:
- properties = cohort.filters.get("properties", {})
- if isinstance(properties, dict):
- check_property_values(properties.get("values", []), cohort_id)
-
- return graph, behavioral_cohorts
-
@extend_schema(
parameters=[
OpenApiParameter(
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 59b5afab0ada..70df9d1d84ab 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -24,7 +24,7 @@ from rest_framework import status
from posthog.schema import PersonsOnEventsMode, PropertyOperator
-from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortViewSet
+from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE
from posthog.clickhouse.client.execute import sync_execute
from posthog.models import Person, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -43,6 +43,7 @@ from posthog.test.persons import create_person
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.dependencies import find_behavioral_cohorts
from products.exports.backend.api.test.test_exports import TestExportMixin
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
@@ -1806,13 +1807,11 @@ [email protected],
make(7, refs=(1, 5)),
]
}
- viewset = CohortViewSet()
-
# Without the realtime exemption, every behavioral cohort and its referrers are excluded.
- self.assertEqual(viewset._find_behavioral_cohorts(cohorts), {1, 2, 3, 5, 6, 7})
+ self.assertEqual(find_behavioral_cohorts(cohorts), {1, 2, 3, 5, 6, 7})
# With it, 5 is flag-compatible (not a seed) and 6 only referenced 5, so both stay.
# 7 still reaches real seed 1, so it remains excluded.
- self.assertEqual(viewset._find_behavioral_cohorts(cohorts, allow_realtime_backfilled=True), {1, 2, 3, 7})
+ self.assertEqual(find_behavioral_cohorts(cohorts, allow_realtime_backfilled=True), {1, 2, 3, 7})
@patch("posthog.api.cohort.report_user_action")
def test_basic_list_omits_heavy_fields(self, patch_capture):
diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.py
index 5a8194c0ed5b..c135263ff212 100644
--- a/products/cohorts/backend/models/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -1,5 +1,10 @@
+from collections import defaultdict
+from typing import Any
+
from django.core.cache import cache
from django.db import transaction
+from django.db.models import Q, TextField
+from django.db.models.functions import Cast
from django.db.models.signals import post_delete, post_save, pre_save
from django.dispatch import receiver
@@ -35,6 +40,141 @@ def _cohort_dependents_key(cohort_id: int) -> str:
return f"cohort:dependents:{cohort_id}"
+# Set of behavioral (flag-incompatible) cohort ids per team, hidden from the feature-flag
+# property picker. Cached because the flag's cohort typeahead hits the cohorts list endpoint
+# on every keystroke, and recomputing the dependency graph there means loading every cohort
+# for the team into memory. The TTL is a backstop; the cache is invalidated whenever a cohort
+# in the team changes (see cohort_changed / cohort_deleted). It is keyed on
+# allow_realtime_backfilled because that toggles which realtime cohorts count as seeds.
+BEHAVIORAL_COHORT_IDS_CACHE_TIMEOUT = 60 * 60 # 1 hour
+
+
+def _behavioral_cohort_ids_key(team_id: int, allow_realtime_backfilled: bool) -> str:
+ return f"cohort:flag_excluded_behavioral_ids:{team_id}:{int(allow_realtime_backfilled)}"
+
+
+def _build_cohort_dependency_graph(all_cohorts: dict[int, Cohort]) -> tuple[dict[int, set[int]], set[int]]:
+ """Build a directed graph of cohort dependencies and identify behavioral cohorts.
+
+ Returns (adjacency_list, behavioral_cohort_ids). Static cohorts are skipped: they have
+ pre-computed membership and don't re-evaluate their filters, so they're always safe to
+ use regardless of filter type.
+ """
+ graph: dict[int, set[int]] = defaultdict(set)
+ behavioral_cohorts: set[int] = set()
+
+ def check_property_values(values: Any, source_id: int) -> None:
+ if not isinstance(values, list):
+ return
+
+ for value in values:
+ if not isinstance(value, dict):
+ continue
+
+ if value.get("type") == "behavioral":
+ behavioral_cohorts.add(source_id)
+ elif value.get("type") == "cohort":
+ try:
+ target_id = int(value.get("value", "0"))
+ except ValueError:
+ continue
+ if target_id in all_cohorts:
+ graph[source_id].add(target_id)
+ elif value.get("type") in ("AND", "OR") and value.get("values"):
+ check_property_values(value["values"], source_id)
+
+ for cohort_id, cohort in all_cohorts.items():
+ if cohort.is_static:
+ continue
+ if cohort.filters:
+ properties = cohort.filters.get("properties", {})
+ if isinstance(properties, dict):
+ check_property_values(properties.get("values", []), cohort_id)
+
+ return graph, behavioral_cohorts
+
+
+def find_behavioral_cohorts(all_cohorts: dict[int, Cohort], *, allow_realtime_backfilled: bool = False) -> set[int]:
+ """Find cohorts that are behavioral, or reference (transitively) a behavioral cohort.
+
+ A cohort is affected if it's a behavioral seed, or references one through the dependency
+ graph. We walk the *reverse* graph once from the seeds (O(V+E)) — every node that can
+ reach a seed via forward edges is affected.
+
+ When allow_realtime_backfilled is True, realtime cohorts that have been backfilled are
+ not seeds: they can be evaluated via the cohort_membership table during flag evaluation.
+ (They can still be pulled in if they reference another seed.)
+ """
+ graph, behavioral_cohorts = _build_cohort_dependency_graph(all_cohorts)
+
+ flag_compatible: set[int] = set()
+ if allow_realtime_backfilled:
+ flag_compatible = {
+ cid for cid in behavioral_cohorts if (cohort := all_cohorts.get(cid)) and cohort.is_flag_compatible
+ }
+ seeds = behavioral_cohorts - flag_compatible
+
+ # Reverse adjacency: target -> sources that reference it.
+ reverse: dict[int, set[int]] = defaultdict(set)
+ for source_id, targets in graph.items():
+ for target_id in targets:
+ reverse[target_id].add(source_id)
+
+ affected = set(seeds)
+ stack = list(seeds)
+ while stack:
+ node = stack.pop()
+ for source_id in reverse.get(node, ()):
+ if source_id not in affected:
+ affected.add(source_id)
+ stack.append(source_id)
+
+ return affected
+
+
+def _compute_flag_excluded_behavioral_cohort_ids(team_id: int, *, allow_realtime_backfilled: bool) -> set[int]:
+ # Only non-static cohorts whose filters reference a behavioral node or another cohort can
+ # be a seed or reach one; the rest are leaves that never get excluded. Filtering them out
+ # in SQL keeps the in-memory graph — and the JSON we parse — small. The bare-word match
+ # can't produce false negatives: a behavioral or cohort node always serializes the literal
+ # "behavioral"/"cohort" substring. A false positive (e.g. a person-property value of
+ # "cohort") only loads an extra leaf, which the graph walk then ignores.
+ graph_source = (
+ Cohort.objects.filter(team_id=team_id, deleted=False, is_static=False)
+ .annotate(_filters_text=Cast("filters", output_field=TextField()))
+ .filter(Q(_filters_text__icontains="behavioral") | Q(_filters_text__icontains="cohort"))
+ .only("id", "is_static", "filters", "cohort_type", "last_backfill_person_properties_at")
+ )
+ all_cohorts = {cohort.id: cohort for cohort in graph_source}
+ return find_behavioral_cohorts(all_cohorts, allow_realtime_backfilled=allow_realtime_backfilled)
+
+
+def get_flag_excluded_behavioral_cohort_ids(team_id: int, *, allow_realtime_backfilled: bool | None) -> set[int]:
+ """Behavioral (flag-incompatible) cohort ids for a team, cached across requests."""
+ # feature_enabled can return None when the flag can't be evaluated; normalize so the
+ # cache key is stable and the compute path sees a real bool.
+ allow_realtime_backfilled = bool(allow_realtime_backfilled)
+ cache_key = _behavioral_cohort_ids_key(team_id, allow_realtime_backfilled)
+ cached = cache.get(cache_key)
+ if cached is not None: # empty list is a valid cached result, not a miss
+ return set(cached)
+
+ behavioral_cohort_ids = _compute_flag_excluded_behavioral_cohort_ids(
+ team_id, allow_realtime_backfilled=allow_realtime_backfilled
+ )
+ cache.set(cache_key, list(behavioral_cohort_ids), timeout=BEHAVIORAL_COHORT_IDS_CACHE_TIMEOUT)
+ return behavioral_cohort_ids
+
+
+def _invalidate_team_behavioral_cohort_cache(team_id: int) -> None:
+ cache.delete_many(
+ [
+ _behavioral_cohort_ids_key(team_id, allow_realtime_backfilled=True),
+ _behavioral_cohort_ids_key(team_id, allow_realtime_backfilled=False),
+ ]
+ )
+
+
def extract_cohort_dependencies(cohort: Cohort) -> set[int]:
"""
Extract cohort dependencies from the given cohort.
@@ -339,6 +479,7 @@ def cohort_changed(sender, instance, **kwargs):
return
transaction.on_commit(lambda: _on_cohort_changed(instance))
+ transaction.on_commit(lambda: _invalidate_team_behavioral_cohort_cache(instance.team_id))
@receiver(post_save, sender=Cohort)
@@ -400,6 +541,7 @@ def cohort_deleted(sender, instance, **kwargs):
Clear and rebuild dependency caches when cohort is deleted.
"""
transaction.on_commit(lambda: _on_cohort_changed(instance, always_invalidate=True))
+ transaction.on_commit(lambda: _invalidate_team_behavioral_cohort_cache(instance.team_id))
@receiver(post_delete, sender=Team)
@@ -413,5 +555,6 @@ def clear_team_cohort_dependency_cache(sender, instance: Team, **kwargs):
for cohort_id in team_cohorts:
cache.delete(_cohort_dependencies_key(cohort_id))
cache.delete(_cohort_dependents_key(cohort_id))
+ _invalidate_team_behavioral_cohort_cache(instance.pk)
transaction.on_commit(clear_cache)
diff --git a/products/cohorts/backend/models/test/test_dependencies.py b/products/cohorts/backend/models/test/test_dependencies.py
index 2ce585ccce3e..51d30f769ba2 100644
--- a/products/cohorts/backend/models/test/test_dependencies.py
+++ b/products/cohorts/backend/models/test/test_dependencies.py
@@ -12,6 +12,7 @@ from products.cohorts.backend.models.dependencies import (
COHORT_BACKFILL_DEBOUNCE_SECONDS,
COHORT_DEPENDENCY_CACHE_COUNTER,
DEPENDENCY_CACHE_TIMEOUT,
+ _behavioral_cohort_ids_key,
_extract_person_property_filters,
_has_person_property_filters,
_person_property_filters_changed,
@@ -19,6 +20,7 @@ from products.cohorts.backend.models.dependencies import (
extract_cohort_dependencies,
get_cohort_dependencies,
get_cohort_dependents,
+ get_flag_excluded_behavioral_cohort_ids,
warm_team_cohort_dependency_cache,
)
@@ -1242,3 +1244,171 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):
result = _person_property_filters_changed(cohort)
self.assertFalse(result)
+
+
+class TestFlagExcludedBehavioralCohortIds(BaseTest):
+ BEHAVIORAL_FILTERS = {
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ }
+ ],
+ }
+ }
+
+ def _person_filters(self) -> dict:
+ return {"properties": {"type": "OR", "values": [{"type": "person", "key": "email", "value": "[email protected]"}]}}
+
+ def _ref_filters(self, cohort_id: int) -> dict:
+ return {"properties": {"type": "OR", "values": [{"type": "cohort", "key": "id", "value": str(cohort_id)}]}}
+
+ def _nested_behavioral_filters(self) -> dict:
+ # Behavioral node buried inside an inner AND group, so detection has to recurse
+ # rather than read the top-level value list.
+ return {
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {"type": "person", "key": "email", "value": "[email protected]"},
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ },
+ ],
+ }
+ ],
+ }
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ @fixture(autouse=True)
+ def mock_transaction(self):
+ with mock.patch("django.db.transaction.on_commit", side_effect=lambda func: func()):
+ yield
+
+ def test_excludes_behavioral_and_transitive_referrers_but_not_leaves(self) -> None:
+ behavioral = Cohort.objects.create(team=self.team, name="behavioral", filters=self.BEHAVIORAL_FILTERS)
+ referrer = Cohort.objects.create(team=self.team, name="referrer", filters=self._ref_filters(behavioral.id))
+ leaf = Cohort.objects.create(team=self.team, name="leaf", filters=self._person_filters())
+
+ excluded = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)
+
+ self.assertEqual(excluded, {behavioral.id, referrer.id})
+ self.assertNotIn(leaf.id, excluded)
+
+ def test_static_cohort_with_behavioral_filters_not_excluded(self) -> None:
+ static_behavioral = Cohort.objects.create(
+ team=self.team, name="static", is_static=True, filters=self.BEHAVIORAL_FILTERS
+ )
+
+ excluded = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)
+
+ self.assertNotIn(static_behavioral.id, excluded)
+
+ def test_result_is_cached(self) -> None:
+ behavioral = Cohort.objects.create(team=self.team, name="behavioral", filters=self.BEHAVIORAL_FILTERS)
+ cache_key = _behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=False)
+ self.assertIsNone(cache.get(cache_key))
+
+ get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)
+
+ self.assertEqual(set(cache.get(cache_key)), {behavioral.id})
+
+ def test_none_allow_realtime_backfilled_is_normalized(self) -> None:
+ Cohort.objects.create(team=self.team, name="behavioral", filters=self.BEHAVIORAL_FILTERS)
+
+ # feature_enabled can return None; it must be treated as False without erroring.
+ excluded = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=None)
+
+ self.assertEqual(
+ set(cache.get(_behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=False))), excluded
+ )
+
+ def test_cache_invalidated_when_cohort_changes(self) -> None:
+ cache_key_false = _behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=False)
+ cache_key_true = _behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=True)
+ leaf = Cohort.objects.create(team=self.team, name="leaf", filters=self._person_filters())
+
+ self.assertEqual(get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False), set())
+ self.assertEqual(get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=True), set())
+ self.assertIsNotNone(cache.get(cache_key_false))
+ self.assertIsNotNone(cache.get(cache_key_true))
+
+ # Turning the cohort behavioral must invalidate both cache key variants.
+ leaf.filters = self.BEHAVIORAL_FILTERS
+ leaf.save()
+
+ self.assertIsNone(cache.get(cache_key_false))
+ self.assertIsNone(cache.get(cache_key_true))
+ self.assertEqual(
+ get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False), {leaf.id}
+ )
+
+ def test_backfilled_realtime_cohort_excluded_without_flag_included_with_it(self) -> None:
+ from django.utils import timezone
+
+ # A realtime cohort that has been backfilled (is_flag_compatible=True) should NOT be
+ # excluded when allow_realtime_backfilled=True, but must still be excluded when False.
+ realtime_behavioral = Cohort.objects.create(
+ team=self.team,
+ name="realtime_behavioral",
+ cohort_type=CohortType.REALTIME,
+ filters=self.BEHAVIORAL_FILTERS,
+ last_backfill_person_properties_at=timezone.now(),
+ )
+
+ excluded_without = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)
+ excluded_with = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=True)
+
+ self.assertIn(realtime_behavioral.id, excluded_without)
+ self.assertNotIn(realtime_behavioral.id, excluded_with)
+
+ def test_detects_behavioral_nested_in_group_and_two_hop_referrers(self) -> None:
+ # Behavioral node nested inside an inner AND group exercises the check_property_values recursion.
+ behavioral = Cohort.objects.create(
+ team=self.team, name="nested_behavioral", filters=self._nested_behavioral_filters()
+ )
+ # Two-hop chain hop2 -> hop1 -> behavioral exercises the reverse-walk traversal, not a single edge.
+ hop1 = Cohort.objects.create(team=self.team, name="hop1", filters=self._ref_filters(behavioral.id))
+ hop2 = Cohort.objects.create(team=self.team, name="hop2", filters=self._ref_filters(hop1.id))
+
+ excluded = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)
+
+ self.assertEqual(excluded, {behavioral.id, hop1.id, hop2.id})
+
+ def test_cache_invalidated_when_cohort_deleted(self) -> None:
+ cache_key_false = _behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=False)
+ cache_key_true = _behavioral_cohort_ids_key(self.team.id, allow_realtime_backfilled=True)
+ behavioral = Cohort.objects.create(team=self.team, name="behavioral", filters=self.BEHAVIORAL_FILTERS)
+
+ self.assertEqual(
+ get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False), {behavioral.id}
+ )
+ self.assertEqual(
+ get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=True), {behavioral.id}
+ )
+ self.assertIsNotNone(cache.get(cache_key_false))
+ self.assertIsNotNone(cache.get(cache_key_true))
+
+ # Deleting the cohort must invalidate both cache key variants.
+ behavioral.delete()
+
+ self.assertIsNone(cache.get(cache_key_false))
+ self.assertIsNone(cache.get(cache_key_true))
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 973beaf986de..680824115f1d 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -334,7 +334,7 @@ class HogFlowActionSerializer(serializers.Serializer):
# behavior the way it's intended; the UI hides behavioral cohorts from the audience picker. Mirror
# that for API/MCP callers. Static cohorts are exempt regardless of how they were built — their
# membership is frozen and precalculated — matching the audience-picker exemption in
- # _build_cohort_dependency_graph in posthog/api/cohort.py.
+ # _build_cohort_dependency_graph in products/cohorts/backend/models/dependencies.py.
if not isinstance(properties, list):
return
cohort_ids = [