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.

fix(cohorts): validate malformed behavioral filter properties (#72479)

Phil Haackd80593358bea
diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.py
index 58782017f11a..66d41e5f5ab1 100644
--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py
+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py
@@ -863,6 +863,33 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):
# Should group by person_id
self.assertIn("GROUP BY", query_str)
+ def test_behavioral_performed_event_multiple_times_alias_does_not_raise(self) -> None:
+ """Regression: `performed_event_multiple_times` (the realtime-cohort builder's alias for
+ `performed_event_multiple`) used to leave `Property.value` as the raw alias string, so
+ this dispatch's `prop.value == "performed_event_multiple"` check fell through to
+ `else: raise ValueError`."""
+ cohort = Cohort.objects.create(
+ team=self.team, name="Test Cohort", filters={"properties": {"type": "AND", "values": []}}
+ )
+ hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)
+
+ prop = Property(
+ key="$pageview",
+ type="behavioral",
+ value="performed_event_multiple_times",
+ event_type="events",
+ operator="gte",
+ operator_value=5,
+ time_value=30,
+ time_interval="day",
+ conditionHash="xyz789abc123",
+ )
+
+ query_ast = hogql_query._get_condition_for_property(prop)
+ query_str = prepare_and_print_ast(query_ast, hogql_query.hogql_context, "clickhouse", pretty=True)[0]
+
+ self.assertIn("precalculated_events", query_str)
+
def test_behavioral_performed_event_with_date_range(self) -> None:
"""performed_event with explicit_datetime + explicit_datetime_to bounds both ends of the window."""
cohort_filters = {
diff --git a/posthog/models/filters/mixins/property.py b/posthog/models/filters/mixins/property.py
index 6289516855a8..e22c846fbee0 100644
--- a/posthog/models/filters/mixins/property.py
+++ b/posthog/models/filters/mixins/property.py
@@ -1,12 +1,14 @@
import json
from typing import Any, Optional, Union, cast
+import posthoganalytics
from rest_framework.exceptions import ValidationError
from posthog.constants import PROPERTIES, PropertyOperatorType
+from posthog.exceptions_capture import capture_exception
from posthog.models.filters.mixins.base import BaseParamMixin
from posthog.models.filters.mixins.utils import cached_property, include_dict, include_query_tags
-from posthog.models.property import Property, PropertyGroup
+from posthog.models.property import Property, PropertyGroup, PropertyValidationError
class PropertyMixin(BaseParamMixin):
@@ -72,7 +74,30 @@ class PropertyMixin(BaseParamMixin):
try:
new_prop = Property(**prop_params)
_properties.append(new_prop)
- except:
+ except (PropertyValidationError, ValidationError, TypeError) as e:
+ # PropertyValidationError covers every failure Property.__init__ itself
+ # raises; ValidationError covers validate_group_type_index's own DRF
+ # error, which Property.__init__ leaves unwrapped so it still reaches
+ # direct callers as a 400; TypeError covers `Property(**prop_params)`
+ # failing to unpack prop_params as a mapping before __init__ even runs.
+ # Dropping an unparsable property changes validation behavior for every
+ # caller (e.g. cohort.properties.flat missing a behavioral leaf lets
+ # behavioral-cohort checks pass silently), so this must stay visible
+ # instead of failing silent. Report structure only — never the
+ # property's own value/event_filters — since those can carry real user
+ # data (e.g. an exact-match email filter). Code-variable capture would
+ # otherwise attach those same values from this frame's locals regardless
+ # of what we pass as additional_properties, so it's disabled for this call.
+ prop_dict = prop_params if isinstance(prop_params, dict) else {}
+ with posthoganalytics.new_context():
+ posthoganalytics.set_capture_exception_code_variables_context(False)
+ capture_exception(
+ e,
+ additional_properties={
+ "property_type": prop_dict.get("type"),
+ "property_fields": sorted(prop_dict.keys()) or None,
+ },
+ )
continue
return _properties
if not properties:
diff --git a/posthog/models/filters/mixins/test/test_property.py b/posthog/models/filters/mixins/test/test_property.py
index c0a0592bfab2..20f7b9e46cb9 100644
--- a/posthog/models/filters/mixins/test/test_property.py
+++ b/posthog/models/filters/mixins/test/test_property.py
@@ -1,11 +1,13 @@
import json
import pytest
+from unittest.mock import patch
+from posthoganalytics.contexts import get_capture_exception_code_variables_context
from rest_framework.exceptions import ValidationError
from posthog.models import Filter
-from posthog.models.property import Property, PropertyGroup
+from posthog.models.property import Property, PropertyGroup, PropertyValidationError
def test_property_group_multi_level_parsing():
@@ -230,3 +232,108 @@ def test_property_group_multi_level_json_parsing():
assert isinstance(filter.property_groups.values[1].values[0], Property)
assert filter.property_groups.values[1].values[0].key == "attr"
assert filter.property_groups.values[1].values[0].value == "val_2"
+
+
+ "invalid_property,expected_fields,expected_exception",
+ [
+ # Behavioral leaf missing its required event_type: fails Property.__init__'s own
+ # attr-presence checks (PropertyValidationError, raised directly).
+ pytest.param(
+ {"key": "$pageview", "type": "behavioral", "value": "performed_event"},
+ ["key", "type", "value"],
+ PropertyValidationError,
+ id="missing_event_type",
+ ),
+ # Behavioral leaf with a value that doesn't match any known BehavioralPropertyType
+ # (and has no alias): Property.__init__ used to KeyError here, which _parse_properties
+ # didn't catch, crashing the whole parse instead of dropping-and-reporting this leaf.
+ pytest.param(
+ {"key": "$pageview", "type": "behavioral", "value": "not_a_real_behavior", "event_type": "events"},
+ ["event_type", "key", "type", "value"],
+ PropertyValidationError,
+ id="unknown_behavioral_value",
+ ),
+ # "group" property with an out-of-range group_type_index: fails via
+ # validate_group_type_index, left as its native rest_framework ValidationError so
+ # callers that construct Property() directly during serializer validation still get
+ # a 400 for it.
+ pytest.param(
+ {"key": "industry", "value": "tech", "type": "group", "group_type_index": 99},
+ ["group_type_index", "key", "type", "value"],
+ ValidationError,
+ id="invalid_group_type_index",
+ ),
+ ],
+)
+def test_property_group_parsing_reports_and_skips_unparsable_property(
+ invalid_property, expected_fields, expected_exception
+):
+ # A property that fails to construct used to be dropped by a bare `except: continue`
+ # with no visibility at all. It must still be dropped (callers across the codebase
+ # rely on best-effort parsing of legacy/malformed data), but the failure must now be
+ # reported — regardless of which internal check inside Property.__init__ rejected it.
+ filter = Filter(
+ data={
+ "properties": {
+ "type": "AND",
+ "values": [{"key": "attr", "value": "val_1"}, invalid_property],
+ }
+ }
+ )
+
+ with patch("posthog.models.filters.mixins.property.capture_exception") as mock_capture_exception:
+ properties = filter.property_groups.values
+
+ assert len(properties) == 1
+ assert isinstance(properties[0], Property)
+ assert properties[0].key == "attr"
+
+ mock_capture_exception.assert_called_once()
+ args, kwargs = mock_capture_exception.call_args
+ assert isinstance(args[0], expected_exception)
+ assert kwargs["additional_properties"] == {
+ "property_type": invalid_property["type"],
+ "property_fields": expected_fields,
+ }
+
+
+def test_property_group_parsing_reports_non_mapping_property():
+ # Old-style flat-list path: a non-mapping element (e.g. a bare string) fails at
+ # `Property(**prop_params)` unpacking with TypeError, before __init__ even runs. The
+ # grouped-properties path can't reach this: a non-mapping element trips the "cannot
+ # contain both PropertyGroup and Property objects" check first.
+ filter = Filter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})
+
+ with patch("posthog.models.filters.mixins.property.capture_exception") as mock_capture_exception:
+ properties = filter.property_groups.values
+
+ assert len(properties) == 1
+ assert isinstance(properties[0], Property)
+ assert properties[0].key == "attr"
+
+ mock_capture_exception.assert_called_once()
+ args, kwargs = mock_capture_exception.call_args
+ assert isinstance(args[0], TypeError)
+ assert kwargs["additional_properties"] == {"property_type": None, "property_fields": None}
+
+
+def test_property_group_parsing_disables_code_variable_capture_for_reported_exception():
+ # capture_exception() forwards the exception object to PostHog's error-tracking SDK, which
+ # has code-variable capture enabled globally: it would otherwise attach this frame's locals
+ # -- including the malformed property's raw value/event_filters -- regardless of the
+ # deliberately structure-only additional_properties above. Must be disabled for this call.
+ observed_context_values = []
+
+ def fake_capture_exception(error, additional_properties=None):
+ observed_context_values.append(get_capture_exception_code_variables_context())
+
+ filter = Filter(data={"properties": [{"key": "attr", "value": "val_1"}, "not-a-mapping"]})
+
+ with patch(
+ "posthog.models.filters.mixins.property.capture_exception", side_effect=fake_capture_exception
+ ) as mock_capture_exception:
+ _ = filter.property_groups.values
+
+ mock_capture_exception.assert_called_once()
+ assert observed_context_values == [False]
diff --git a/posthog/models/property/property.py b/posthog/models/property/property.py
index 34e291e16d48..8b2977744d6c 100644
--- a/posthog/models/property/property.py
+++ b/posthog/models/property/property.py
@@ -128,10 +128,21 @@ VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES = {
# explicit_datetime_to is always optional — the existing `{explicit_datetime}` entry
# already accepts the both-set case since the validator uses "all required keys present".
{"explicit_datetime"},
+ # Realtime-compiled unbounded condition ("did this person ever do X"): the cohort
+ # backend compiles bytecode/conditionHash from event_type/event_filters regardless
+ # of whether a time bound is present, so a leaf carrying compiled bytecode but no
+ # time window is a deliberately unbounded condition, not a malformed one. A related
+ # (stricter, unconditional) requirement for these two fields lives in
+ # products/cohorts/backend/parity/eligibility.py::_classify_behavioral and its Rust
+ # source of truth rust/cohort-core/src/filters/leaf_classifier.rs — those answer a
+ # different question (is this leaf eligible for realtime precompute) and intentionally
+ # still require a time window there.
+ {"conditionHash", "bytecode"},
],
BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE: [
{"time_value", "time_interval"},
{"explicit_datetime"},
+ {"conditionHash", "bytecode"},
],
BehavioralPropertyType.PERFORMED_EVENT_FIRST_TIME: [
{"time_value", "time_interval"},
@@ -139,6 +150,18 @@ VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES = {
],
}
+# Behavioral `value`s that don't match BehavioralPropertyType's enum value but are
+# produced by cohort filter generators and are equivalent for validation purposes.
+# Keyed by the raw stored value string; resolves to the canonical type whose
+# VALIDATE_BEHAVIORAL_PROP_TYPES / VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES rules apply.
+# `Property.__init__` normalizes `self.value` to this canonical string once validation
+# passes, so downstream consumers that compare `prop.value` against the canonical
+# BehavioralPropertyType strings (e.g. HogQLCohortQuery._get_condition_for_property)
+# don't each need their own alias awareness.
+BEHAVIORAL_VALUE_ALIASES: dict[str, BehavioralPropertyType] = {
+ "performed_event_multiple_times": BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE,
+}
+
VALIDATE_BEHAVIORAL_PROP_TYPES = {
BehavioralPropertyType.PERFORMED_EVENT: [
"key",
@@ -198,6 +221,13 @@ VALIDATE_BEHAVIORAL_PROP_TYPES = {
}
+class PropertyValidationError(ValueError):
+ """Every failure to construct a valid Property from prop_params raises this (a
+ ValueError subclass, so existing `except ValueError` callers are unaffected) — one
+ owned type callers can catch, instead of having to discover each new internal raise
+ site (e.g. via validate_group_type_index) by reading Property.__init__'s source."""
+
+
class Property:
key: str
operator: Optional[OperatorType]
@@ -276,6 +306,11 @@ class Property:
self.key = key
self.operator = operator
self.type = type if type else "event"
+ # Left unwrapped (a DRF ValidationError, not PropertyValidationError): callers that
+ # construct Property() directly inside serializer validation (e.g. feature_flag.py's
+ # validate_filters) rely on DRF recognizing this exception type to turn it into a 400.
+ # _parse_properties, the one caller that needs report-and-skip for this, catches it
+ # explicitly alongside PropertyValidationError.
self.group_type_index = validate_group_type_index("group_type_index", group_type_index)
self.event_type = event_type
self.operator_value = operator_value
@@ -299,35 +334,48 @@ class Property:
elif self.type == "hogql":
pass # keep value as None
elif value is None:
- raise ValueError(f"Value must be set for property type {self.type} & operator {self.operator}")
+ raise PropertyValidationError(f"Value must be set for property type {self.type} & operator {self.operator}")
else:
self.value = value
if self.type not in VALIDATE_PROP_TYPES.keys():
- raise ValueError(f"Invalid property type: {self.type}")
+ raise PropertyValidationError(f"Invalid property type: {self.type}")
for attr in VALIDATE_PROP_TYPES[self.type]:
if getattr(self, attr, None) is None:
- raise ValueError(f"Missing required attr {attr} for property type {self.type} with key {self.key}")
+ raise PropertyValidationError(
+ f"Missing required attr {attr} for property type {self.type} with key {self.key}"
+ )
if self.type == "behavioral":
- for attr in VALIDATE_BEHAVIORAL_PROP_TYPES[cast(BehavioralPropertyType, self.value)]:
+ behavioral_value = BEHAVIORAL_VALUE_ALIASES.get(
+ cast(str, self.value), cast(BehavioralPropertyType, self.value)
+ )
+ required_attrs = VALIDATE_BEHAVIORAL_PROP_TYPES.get(behavioral_value)
+ if required_attrs is None:
+ raise PropertyValidationError(f"Invalid behavioral value: {self.value}")
+
+ for attr in required_attrs:
if getattr(self, attr, None) is None:
- raise ValueError(f"Missing required attr {attr} for property type {self.type}::{self.value}")
+ raise PropertyValidationError(
+ f"Missing required attr {attr} for property type {self.type}::{self.value}"
+ )
- if cast(BehavioralPropertyType, self.value) in VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES:
+ if behavioral_value in VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES:
matches_attr_list = False
- condition_list = VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES[cast(BehavioralPropertyType, self.value)]
+ condition_list = VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES[behavioral_value]
for attr_list in condition_list:
if all(getattr(self, attr, None) is not None for attr in attr_list):
matches_attr_list = True
break
if not matches_attr_list:
- raise ValueError(
+ raise PropertyValidationError(
f"Missing required parameters, atleast one of values ({'), ('.join([' & '.join(condition) for condition in condition_list])}) for property type {self.type}::{self.value}"
)
+ self.value = behavioral_value
+
def __repr__(self):
params_repr = ", ".join(f"{key}={repr(value)}" for key, value in self.to_dict().items())
return f"Property({params_repr})"
diff --git a/posthog/models/property/test/test_property_behavioral_validation.py b/posthog/models/property/test/test_property_behavioral_validation.py
index 73e70419289b..e429059bb79f 100644
--- a/posthog/models/property/test/test_property_behavioral_validation.py
+++ b/posthog/models/property/test/test_property_behavioral_validation.py
@@ -1,5 +1,7 @@
from posthog.test.base import BaseTest
+from parameterized import parameterized
+
from posthog.models.property import BehavioralPropertyType, Property
@@ -76,3 +78,72 @@ class TestBehavioralPropertyDateRangeValidation(BaseTest):
value=BehavioralPropertyType.PERFORMED_EVENT_FIRST_TIME,
explicit_datetime_to="-7d",
)
+
+
+class TestBehavioralPropertyValueAlias(BaseTest):
+ """Some cohort filter generators store "performed_event_multiple_times" instead of
+ BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE's canonical "performed_event_multiple".
+ The alias must resolve to that type's validation rules, not just skip validation."""
+
+ def _build(self, **overrides) -> Property:
+ defaults: dict = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event_multiple_times",
+ }
+ defaults.update(overrides)
+ return Property(**defaults)
+
+ def test_accepts_time_bound_like_canonical_type(self) -> None:
+ prop = self._build(operator_value=1, time_value=3650, time_interval="day")
+ self.assertEqual(prop.value, BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE)
+
+ def test_still_requires_operator_value(self) -> None:
+ # PERFORMED_EVENT_MULTIPLE's unconditional required attrs (VALIDATE_BEHAVIORAL_PROP_TYPES)
+ # must still apply through the alias, not just its conditional time-bound rules.
+ with self.assertRaises(ValueError):
+ self._build(time_value=3650, time_interval="day")
+
+
+class TestBehavioralPropertyBytecodeCondition(BaseTest):
+ """The realtime-cohort builder can express an unbounded "did this person ever do X"
+ condition purely via compiled bytecode/conditionHash, with no time_value/time_interval/
+ explicit_datetime set. That's a deliberately unbounded condition, not a malformed one."""
+
+ def _build(self, **overrides) -> Property:
+ defaults: dict = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": BehavioralPropertyType.PERFORMED_EVENT,
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ "conditionHash": "f9c616030a87e68f",
+ }
+ defaults.update(overrides)
+ return Property(**defaults)
+
+ @parameterized.expand(
+ [
+ ("performed_event", BehavioralPropertyType.PERFORMED_EVENT, {}),
+ (
+ "performed_event_multiple",
+ BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE,
+ {"operator_value": 1},
+ ),
+ ]
+ )
+ def test_accepts_bytecode_condition_with_no_time_bound(self, _name, value, extra_kwargs) -> None:
+ self._build(value=value, **extra_kwargs) # should not raise
+
+ @parameterized.expand(
+ [
+ ("no_conditions_at_all", {"bytecode": None, "conditionHash": None}),
+ # {conditionHash, bytecode} requires both, matching how the cohort backend
+ # always compiles them together — a partial pair isn't a valid compiled condition.
+ ("bytecode_without_condition_hash", {"conditionHash": None}),
+ ]
+ )
+ def test_rejects_incomplete_bytecode_condition(self, _name, overrides) -> None:
+ with self.assertRaises(ValueError):
+ self._build(**overrides)
diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.py
index 75b803de8f6d..5625a3c93021 100644
--- a/posthog/test/test_cohort_model.py
+++ b/posthog/test/test_cohort_model.py
@@ -329,6 +329,58 @@ class TestCohort(BaseTest):
},
)
+ @parameterized.expand(
+ [
+ (
+ # Regression: the realtime-cohort builder stores value="performed_event_multiple_times",
+ # not BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE's "performed_event_multiple".
+ # Property(**leaf) used to raise KeyError for this, silently dropping the leaf.
+ "multiple_times_suffixed_value",
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event_multiple_times",
+ "negation": False,
+ "operator": "gte",
+ "event_type": "events",
+ "time_value": 3650,
+ "time_interval": "day",
+ "operator_value": 1,
+ },
+ "performed_event_multiple",
+ ),
+ (
+ # Regression: an unbounded realtime-compiled condition ("did this person ever do X")
+ # carries bytecode/conditionHash/event_filters but no time_value/time_interval/
+ # explicit_datetime. Property(**leaf) used to raise ValueError ("Missing required
+ # parameters"), silently dropping the leaf.
+ "bytecode_only_unbounded_condition",
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ "negation": False,
+ "event_type": "events",
+ "conditionHash": "f9c616030a87e68f",
+ "event_filters": [
+ {"key": "$current_url", "type": "event", "value": "some-path", "operator": "icontains"}
+ ],
+ },
+ "performed_event",
+ ),
+ ]
+ )
+ def test_properties_flat_includes_realtime_style_behavioral_leaf(self, _name, behavioral_leaf, expected_value):
+ cohort = Cohort(
+ team=self.team,
+ filters={"properties": {"type": "AND", "values": [behavioral_leaf]}},
+ )
+
+ behavioral_props = [p for p in cohort.properties.flat if p.type == "behavioral"]
+ self.assertEqual(len(behavioral_props), 1)
+ self.assertEqual(behavioral_props[0].value, expected_value)
+
def test_insert_users_list_by_uuid(self):
# These are some fine uuids.
uuids = [
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index f9506f5d33c8..2cab11487f2a 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -295,19 +295,45 @@ def _is_realtime_cohort_flag_targeting_enabled(request) -> bool:
return False
-def _validate_behavioral_cohort_for_feature_flag(cohort: Cohort, *, allow_realtime_backfilled: bool = False) -> None:
+def _describe_behavioral_properties(behavioral_props: list[Property]) -> str | None:
+ """Human-readable summary of which condition(s) on a cohort are behavioral, so a
+ validation error can point at the specific thing to fix instead of a bare cohort name.
+ Returns None if no properties parsed into a description (caller falls back to generic wording)."""
+ seen: set[tuple[str, str]] = set()
+ descriptions = []
+ for prop in behavioral_props:
+ marker = (prop.key, str(prop.value))
+ if marker in seen:
+ continue
+ seen.add(marker)
+ descriptions.append(f"'{prop.key}' ({prop.value})")
+
+ if not descriptions:
+ return None
+ if len(descriptions) == 1:
+ return descriptions[0]
+ remaining = len(descriptions) - 1
+ return f"{descriptions[0]} and {remaining} other{'s' if remaining != 1 else ''}"
+
+
+def _validate_behavioral_cohort_for_feature_flag(
+ cohort: Cohort, behavioral_props: list[Property], *, allow_realtime_backfilled: bool = False
+) -> None:
"""
Raises a validation error unless the cohort is flag-compatible.
When allow_realtime_backfilled is True, realtime cohorts that have been backfilled
are permitted. Otherwise all behavioral cohorts are rejected.
"""
+ condition_description = _describe_behavioral_properties(behavioral_props)
+ condition_clause = f" on {condition_description}" if condition_description else ""
+
if allow_realtime_backfilled:
if cohort.is_flag_compatible:
return
if cohort.cohort_type != CohortType.REALTIME:
raise serializers.ValidationError(
- detail=f"Cohort '{cohort.name}' with filters on events cannot be used in feature flags.",
+ detail=f"Cohort '{cohort.name}' has an event-based condition{condition_clause} and cannot be used in feature flags.",
code=BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
)
raise serializers.ValidationError(
@@ -316,7 +342,7 @@ def _validate_behavioral_cohort_for_feature_flag(cohort: Cohort, *, allow_realti
)
raise serializers.ValidationError(
- detail=f"Cohort '{cohort.name}' with filters on events cannot be used in feature flags.",
+ detail=f"Cohort '{cohort.name}' has an event-based condition{condition_clause} and cannot be used in feature flags.",
code=BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
)
@@ -1446,9 +1472,21 @@ class FeatureFlagSerializer(
# filters are display-only and never evaluated, so skip them.
if cohort.is_static:
continue
- if any(cohort_prop.type == "behavioral" for cohort_prop in cohort.properties.flat):
+ behavioral_props = [
+ cohort_prop
+ for cohort_prop in cohort.properties.flat
+ if cohort_prop.type == "behavioral"
+ ]
+ # Gate on both signals: cohort.properties.flat parses each leaf into a
+ # Property() object, so a leaf shape the parser doesn't recognize would
+ # silently vanish from it and defeat this guard; _has_filter_type walks
+ # the raw filters JSON instead, so it can't miss an unparsable leaf. But
+ # _has_filter_type only reads `filters` — legacy cohorts that store their
+ # condition in the deprecated `groups` field instead (see Cohort.properties)
+ # would defeat *that* check, so behavioral_props still needs to cover them.
+ if cohort._has_filter_type("behavioral") or behavioral_props:
_validate_behavioral_cohort_for_feature_flag(
- cohort, allow_realtime_backfilled=self._allow_realtime_backfilled
+ cohort, behavioral_props, allow_realtime_backfilled=self._allow_realtime_backfilled
)
except Cohort.DoesNotExist:
raise serializers.ValidationError(
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index e9262d9ac665..7c54fca470d5 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -5438,7 +5438,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
{
"type": "validation_error",
"code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
+ "detail": "Cohort 'cohort2' has an event-based condition on '$pageview' (performed_event_first_time) and cannot be used in feature flags.",
"attr": "filters",
}.items(),
cohort_request.json().items(),
@@ -5478,7 +5478,145 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
{
"type": "validation_error",
"code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
+ "detail": "Cohort 'cohort2' has an event-based condition on '$pageview' (performed_event_first_time) and cannot be used in feature flags.",
+ "attr": "filters",
+ }.items(),
+ response.json().items(),
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "multiple_times_suffixed_value",
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event_multiple_times",
+ "negation": False,
+ "operator": "gte",
+ "event_type": "events",
+ "time_value": 3650,
+ "time_interval": "day",
+ "operator_value": 1,
+ },
+ "performed_event_multiple",
+ ),
+ (
+ "bytecode_only_unbounded_condition",
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ "negation": False,
+ "event_type": "events",
+ "conditionHash": "f9c616030a87e68f",
+ "event_filters": [
+ {"key": "$current_url", "type": "event", "value": "some-path", "operator": "icontains"}
+ ],
+ },
+ "performed_event",
+ ),
+ ]
+ )
+ def test_creating_feature_flag_with_realtime_style_behavioral_leaf_is_rejected(
+ self, _name, behavioral_leaf, expected_condition_value
+ ):
+ # Regression: both of these leaf shapes used to raise inside Property(**leaf) and
+ # get silently dropped by _parse_properties, so cohort.properties.flat came back
+ # with no behavioral property and this guard never fired — letting the flag save
+ # succeed even with realtime-cohort-flag-targeting off.
+ cohort = Cohort.objects.create(
+ team=self.team,
+ filters={"properties": {"type": "AND", "values": [behavioral_leaf]}},
+ name="realtime-behavioral-cohort",
+ )
+
+ response = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort.id}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": f"Cohort 'realtime-behavioral-cohort' has an event-based condition on '$pageview' ({expected_condition_value}) and cannot be used in feature flags.",
+ "attr": "filters",
+ }.items(),
+ response.json().items(),
+ )
+
+ def test_creating_feature_flag_with_unrecognized_behavioral_value_cohort_is_still_rejected(self) -> None:
+ # Regression: the guard used to decide whether to run at all by checking
+ # `cohort.properties.flat` for a behavioral property. A leaf with a value that
+ # Property.__init__ doesn't recognize fails to parse and is dropped from `.flat`
+ # (see test_property.py's unknown_behavioral_value case), so `.flat` alone would
+ # find nothing behavioral and skip the guard entirely -- reproducing the exact
+ # silent-bypass bug this PR fixes, just for a value it doesn't special-case.
+ # cohort._has_filter_type("behavioral") reads the raw filter JSON instead, so it
+ # still detects the leaf and the guard still fires, with a generic message since
+ # no behavioral property survived to describe.
+ cohort = Cohort.objects.create(
+ team=self.team,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "not_a_real_behavior",
+ "event_type": "events",
+ }
+ ],
+ }
+ },
+ name="unrecognized-behavioral-cohort",
+ )
+
+ response = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort.id}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'unrecognized-behavioral-cohort' has an event-based condition and cannot be used in feature flags.",
+ "attr": "filters",
+ }.items(),
+ response.json().items(),
+ )
+
+ def test_creating_feature_flag_with_legacy_groups_behavioral_cohort_is_rejected(self) -> None:
+ # Regression: cohort._has_filter_type("behavioral") only walks the `filters` JSON
+ # tree. Cohorts still using the deprecated `groups` field (no `filters` set) build
+ # their behavioral Property objects through a different path (Cohort.properties'
+ # groups-to-properties fallback), which _has_filter_type never sees. Gating solely
+ # on _has_filter_type would silently skip this guard for such a cohort -- reopening
+ # the exact bypass this PR fixes, just for the legacy storage format instead of an
+ # unparsable leaf shape.
+ cohort = Cohort.objects.create(
+ team=self.team,
+ groups=[{"event_id": "$pageview", "days": 30}],
+ name="legacy-groups-behavioral-cohort",
+ )
+
+ response = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort.id}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'legacy-groups-behavioral-cohort' has an event-based condition on '$pageview' (performed_event) and cannot be used in feature flags.",
"attr": "filters",
}.items(),
response.json().items(),
@@ -5603,7 +5741,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
{
"type": "validation_error",
"code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
+ "detail": "Cohort 'cohort-behavioural' has an event-based condition on '$pageview' (performed_event_first_time) and cannot be used in feature flags.",
"attr": "filters",
}.items(),
cohort_request.json().items(),
@@ -5619,7 +5757,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
{
"type": "validation_error",
"code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
+ "detail": "Cohort 'cohort-behavioural' has an event-based condition on '$pageview' (performed_event_first_time) and cannot be used in feature flags.",
"attr": "filters",
}.items(),
cohort_request.json().items(),
@@ -5649,7 +5787,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
False,
True,
status.HTTP_400_BAD_REQUEST,
- "filters on events",
+ "has an event-based condition",
),
(
"realtime_backfilled_flag_off",
@@ -5657,7 +5795,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
True,
False,
status.HTTP_400_BAD_REQUEST,
- "filters on events",
+ "has an event-based condition",
),
]
)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_utils.py b/products/feature_flags/backend/api/test/test_feature_flag_utils.py
index 08a07a66c7b6..bec2363b2a8a 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_utils.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_utils.py
@@ -1,7 +1,14 @@
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.property import Property
+
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.cohorts.backend.models.util import sort_cohorts_topologically
+from products.feature_flags.backend.api.feature_flag import _describe_behavioral_properties
class TestFeatureFlagUtils(APIBaseTest):
@@ -69,3 +76,35 @@ class TestFeatureFlagUtils(APIBaseTest):
seen_cohorts_cache: dict[int, CohortOrEmpty] = {}
topologically_sorted_cohort_ids = sort_cohorts_topologically(cohort_ids, seen_cohorts_cache)
self.assertEqual(topologically_sorted_cohort_ids, [])
+
+
+def _behavioral_prop(key: str) -> Property:
+ return Property(
+ key=key, type="behavioral", value="performed_event", event_type="events", time_value=30, time_interval="day"
+ )
+
+
+class TestDescribeBehavioralProperties(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no_properties", [], None),
+ ("single_property", [_behavioral_prop("$pageview")], "'$pageview' (performed_event)"),
+ (
+ "two_distinct_properties",
+ [_behavioral_prop("$pageview"), _behavioral_prop("$autocapture")],
+ "'$pageview' (performed_event) and 1 other",
+ ),
+ (
+ "three_distinct_properties",
+ [_behavioral_prop("$pageview"), _behavioral_prop("$autocapture"), _behavioral_prop("$identify")],
+ "'$pageview' (performed_event) and 2 others",
+ ),
+ (
+ "duplicate_properties_collapse_to_one",
+ [_behavioral_prop("$pageview"), _behavioral_prop("$pageview")],
+ "'$pageview' (performed_event)",
+ ),
+ ]
+ )
+ def test_describes_behavioral_properties(self, _name, behavioral_props, expected):
+ self.assertEqual(_describe_behavioral_properties(behavioral_props), expected)
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index d8f5bd77245f..20a79970c60f 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -1473,7 +1473,7 @@ class TestSurvey(APIBaseTest):
assert survey_with_targeting.json() == {
"type": "validation_error",
"code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort2' with filters on events cannot be used in surveys.",
+ "detail": "Cohort 'cohort2' has an event-based condition on '$pageview' (performed_event_first_time) and cannot be used in surveys.",
"attr": None,
}