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.

chore(flags): rm flag evaluation in django (#58078)

Nick Best14d73e966d6f
diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.py
index 4a32978eea90..6ad1376a5c10 100644
--- a/posthog/api/feature_flag.py
+++ b/posthog/api/feature_flag.py
@@ -73,7 +73,6 @@ from posthog.models.feature_flag import (
)
from posthog.models.feature_flag.flag_analytics import increment_request_count
from posthog.models.feature_flag.flag_status import FeatureFlagStatusChecker
-from posthog.models.feature_flag.flag_validation import check_flag_evaluation_query_is_ok
from posthog.models.feature_flag.local_evaluation import (
DATABASE_FOR_LOCAL_EVALUATION,
_get_flag_properties_from_filters,
@@ -98,6 +97,7 @@ from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, C
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.settings.feature_flags import LOCAL_EVAL_RATE_LIMITS, REMOTE_CONFIG_RATE_LIMITS
+from posthog.utils import is_valid_regex
from posthog.views import format_bytes
from products.dashboards.backend.api.dashboard import Dashboard
@@ -1051,8 +1051,23 @@ class FeatureFlagSerializer(
if value is not None and (isinstance(value, bool) or not isinstance(value, int)):
raise serializers.ValidationError(f"{path} must be an integer or null, got {type(value).__name__}")
+ def _validate_regex_pattern(value: Any, path: str, existing_patterns: set[str]) -> None:
+ if not isinstance(value, str):
+ return
+ if value not in existing_patterns and not is_valid_regex(value):
+ raise serializers.ValidationError(f"{path}: invalid regex pattern")
+
_validate_integer(flag_level_aggregation, "aggregation_group_type_index")
+ # Collect existing regex patterns so we don't reject unchanged patterns on
+ # PATCH — flags may contain regexes valid in fancy_regex/PG ARE but not Python re.
+ existing_patterns: set[str] = set()
+ if self.instance is not None:
+ for g in (self.instance.filters or {}).get("groups", []) or []:
+ for p in g.get("properties", []) or []:
+ if p.get("operator") in ("regex", "not_regex") and isinstance(p.get("value"), str):
+ existing_patterns.add(p["value"])
+
for group_index, group in enumerate(filters.get("groups", [])):
variant = group.get("variant")
if variant is not None and not isinstance(variant, str):
@@ -1072,6 +1087,13 @@ class FeatureFlagSerializer(
f"groups[{group_index}].properties[{prop_index}].group_type_index",
)
+ if prop.get("operator") in ("regex", "not_regex"):
+ _validate_regex_pattern(
+ prop.get("value"),
+ f"groups[{group_index}].properties[{prop_index}].value",
+ existing_patterns,
+ )
+
for var_index, variant in enumerate((filters.get("multivariate") or {}).get("variants", [])):
_validate_rollout_percentage(
variant.get("rollout_percentage"),
@@ -1462,30 +1484,6 @@ class FeatureFlagSerializer(
for dep_flag_key in flag_dependencies:
has_cycle(dep_flag_key, [current_flag_key])
- def check_flag_evaluation(self, data):
- # TODO: Once we move to no DB level evaluation, can get rid of this.
-
- temporary_flag = FeatureFlag(**data)
- team_id = self.context["team_id"]
- project_id = self.context["project_id"]
-
- # Skip validation for flags with flag dependencies since the evaluation
- # engine doesn't support flag dependencies yet
- filters = data.get("filters", {})
- flag_dependencies = self._extract_flag_dependencies(filters)
- if flag_dependencies:
- return # Skip validation for flag dependencies
-
- try:
- check_flag_evaluation_query_is_ok(
- temporary_flag,
- team_id,
- project_id,
- allow_realtime_backfilled=self._allow_realtime_backfilled,
- )
- except Exception:
- raise serializers.ValidationError("Can't evaluate flag - please check release conditions")
-
def _free_key_held_by_soft_deleted_flags(self, key: str, exclude_pk: int | None = None) -> None:
# The (team, key) unique constraint spans soft-deleted rows, so we must
# clear any tombstone holding `key`. Hard-delete first; if an FK blocks
@@ -1556,8 +1554,6 @@ class FeatureFlagSerializer(
analytics_dashboards = validated_data.pop("analytics_dashboards", None)
- self.check_flag_evaluation(validated_data)
-
with ImpersonatedContext(request):
instance: FeatureFlag = super().create(validated_data)
diff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.py
index 702879be62e3..d90511a87661 100644
--- a/posthog/api/test/test_feature_flag.py
+++ b/posthog/api/test/test_feature_flag.py
@@ -7152,112 +7152,232 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
response.json().items(),
)
- def test_cant_create_flag_with_data_that_fails_to_query(self):
- Person.objects.create(
- distinct_ids=["123"],
- team=self.team,
- properties={"email": "x y z"},
- )
- Person.objects.create(
- distinct_ids=["456"],
- team=self.team,
- properties={"email": "2.3.999"},
+ def test_cant_create_flag_with_invalid_regex(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
+ {
+ "name": "Beta feature",
+ "key": "beta-x",
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 65,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "[unclosed",
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
+ },
+ },
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")
- # Only snapshot flag evaluation queries
- with snapshot_postgres_queries_context(self, custom_query_matcher=lambda query: "posthog_person" in query):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags",
- {
- "name": "Beta feature",
- "key": "beta-x",
- "filters": {
- "groups": [
- {
- "rollout_percentage": 65,
- "properties": [
- {
- "key": "email",
- "type": "person",
- "value": "2.3.9{0-9}{1}",
- "operator": "regex",
- }
- ],
- }
- ]
- },
- },
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Can't evaluate flag - please check release conditions",
- "attr": None,
+ def test_cant_create_flag_with_invalid_not_regex(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
+ {
+ "name": "Beta feature",
+ "key": "beta-x",
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 65,
+ "properties": [
+ {
+ "key": "email",
+ "type": "group",
+ "group_type_index": 0,
+ "value": "(unclosed",
+ "operator": "not_regex",
+ }
+ ],
+ }
+ ],
},
- )
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")
- def test_cant_create_flag_with_group_data_that_fails_to_query(self):
- create_group_type_mapping_without_created_at(
+ def test_patch_flag_with_unchanged_python_incompatible_regex(self):
+ flag = FeatureFlag.objects.create(
team=self.team,
- project_id=self.team.project_id,
- group_type="organization",
- group_type_index=0,
+ created_by=self.user,
+ key="flag-with-lookbehind",
+ filters={
+ "groups": [
+ {
+ "rollout_percentage": 100,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "(?<!a{2,5})b",
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
+ },
)
- create_group_type_mapping_without_created_at(
- team=self.team,
- project_id=self.team.project_id,
- group_type="xyz",
- group_type_index=1,
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}",
+ {"active": False},
)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- for i in range(5):
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key=f"xyz:{i}",
- properties={"industry": f"{i}", "email": "2.3.4445"},
- )
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}",
+ {
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 50,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "(?<!a{2,5})b",
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- # Only snapshot flag evaluation queries
- with snapshot_postgres_queries_context(self, custom_query_matcher=lambda query: "posthog_group" in query):
- # Test group flag with invalid regex
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags",
- {
- "name": "Beta feature",
- "key": "beta-x",
- "filters": {
- "aggregation_group_type_index": 1,
- "groups": [
+ def test_patch_flag_rejects_new_invalid_regex(self):
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="flag-valid-regex",
+ filters={
+ "groups": [
+ {
+ "rollout_percentage": 100,
+ "properties": [
{
- "rollout_percentage": 65,
- "properties": [
- {
- "key": "email",
- "type": "group",
- "group_type_index": 1,
- "value": "2.3.9{0-9}{1 ef}",
- "operator": "regex",
- }
- ],
+ "key": "email",
+ "type": "person",
+ "value": "^valid$",
+ "operator": "regex",
}
],
- },
+ }
+ ]
+ },
+ )
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}",
+ {
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 100,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "[unclosed",
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")
+
+ def test_cant_create_flag_with_non_string_regex_value(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
+ {
+ "name": "Beta feature",
+ "key": "beta-x",
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 65,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": 123,
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
},
- )
+ },
+ )
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
+ self.assertEqual(response.json()["detail"], "Invalid value for operator regex: 123")
+
+ def test_can_create_flag_with_valid_regex(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
{
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Can't evaluate flag - please check release conditions",
- "attr": None,
+ "name": "Beta feature",
+ "key": "beta-x",
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 65,
+ "properties": [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "^[a-z]+@posthog\\.com$",
+ "operator": "regex",
+ }
+ ],
+ }
+ ]
+ },
},
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()
+ self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], "^[a-z]+@posthog\\.com$")
+
+ @parameterized.expand(
+ [
+ ("python_valid_pg_invalid_persons", "person", None, "2.3.9{0-9}{1}"),
+ ("python_valid_pg_invalid_groups", "group", 1, "2.3.9{0-9}{1 ef}"),
+ ]
+ )
+ def test_can_create_flag_with_postgres_incompatible_regex(self, _name, prop_type, group_type_index, pattern):
+ if prop_type == "group":
+ create_group_type_mapping_without_created_at(
+ team=self.team,
+ project_id=self.team.project_id,
+ group_type="xyz",
+ group_type_index=group_type_index,
+ )
+ prop = {"key": "email", "type": prop_type, "value": pattern, "operator": "regex"}
+ if group_type_index is not None:
+ prop["group_type_index"] = group_type_index
+ filters: dict = {"groups": [{"rollout_percentage": 65, "properties": [prop]}]}
+ if group_type_index is not None:
+ filters["aggregation_group_type_index"] = group_type_index
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
+ {"name": "Beta feature", "key": f"beta-{prop_type}", "filters": filters},
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()
+ self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], pattern)
def test_feature_flag_includes_cohort_names(self):
cohort = Cohort.objects.create(
diff --git a/posthog/models/feature_flag/flag_matching.py b/posthog/models/feature_flag/flag_matching.py
index dfa3a1831d7b..9298a03b8510 100644
--- a/posthog/models/feature_flag/flag_matching.py
+++ b/posthog/models/feature_flag/flag_matching.py
@@ -7,7 +7,6 @@ Exported symbols: FeatureFlagMatcher, FlagsMatcherCache, get_feature_flag_hash_k
All other flag evaluation uses the Rust flags service.
DO NOT add new callers — if you need flag evaluation, call FEATURE_FLAGS_SERVICE_URL/flags.
-For flag validation in the admin UI, use posthog/models/feature_flag/flag_validation.py.
"""
import hashlib
diff --git a/posthog/models/feature_flag/flag_validation.py b/posthog/models/feature_flag/flag_validation.py
deleted file mode 100644
index 78bf57c51983..000000000000
--- a/posthog/models/feature_flag/flag_validation.py
+++ /dev/null
@@ -1,199 +0,0 @@
-"""
-Flag validation utilities for feature flag creation/updates in the admin UI.
-
-These functions validate that feature flags can be evaluated without timing out
-by testing the underlying database queries.
-"""
-
-from typing import Optional, Union, cast
-
-from django.db.models import BooleanField, CharField, Expression, F, Func
-from django.db.models.expressions import ExpressionWrapper, RawSQL
-from django.db.models.query import QuerySet
-
-from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING
-from posthog.models.cohort import Cohort, CohortOrEmpty
-from posthog.models.filters import Filter
-from posthog.models.group import Group
-from posthog.models.person import Person
-from posthog.models.property.property import Property
-from posthog.person_db_router import PERSONS_DB_FOR_READ
-from posthog.queries.base import properties_to_Q, sanitize_property_key
-
-from .feature_flag import FeatureFlag
-
-READ_ONLY_DATABASE_FOR_PERSONS = PERSONS_DB_FOR_READ
-
-
-def key_and_field_for_property(property: Property) -> tuple[str, str]:
- """
- Generate database field names for property matching with math operators.
-
- Returns tuple of (annotation_key, field_path) for use in Django ORM queries.
- """
- column = "group_properties" if property.type == "group" else "properties"
- key = property.key
- sanitized_key = sanitize_property_key(key)
-
- return (
- f"{column}_{sanitized_key}_type",
- f"{column}__{key}",
- )
-
-
-def get_all_properties_with_math_operators(
- properties: list[Property], cohorts_cache: dict[int, CohortOrEmpty], project_id: int
-) -> list[tuple[str, str]]:
- """
- Recursively extract all properties that use math operators (gt, lt, gte, lte).
-
- These properties require special JSONB type annotations in the database query
- to ensure proper comparison semantics.
- """
- all_keys_and_fields = []
-
- for prop in properties:
- if prop.type == "cohort":
- cohort_id = int(cast(Union[str, int], prop.value))
- if cohorts_cache.get(cohort_id) is None:
- queried_cohort = (
- Cohort.objects.db_manager(DATABASE_FOR_FLAG_MATCHING)
- .filter(pk=cohort_id, team__project_id=project_id, deleted=False)
- .first()
- )
- cohorts_cache[cohort_id] = queried_cohort or ""
-
- cohort = cohorts_cache[cohort_id]
- if cohort:
- all_keys_and_fields.extend(
- get_all_properties_with_math_operators(cohort.properties.flat, cohorts_cache, project_id)
- )
- elif prop.operator in ["gt", "lt", "gte", "lte"] and prop.type in ("person", "group"):
- all_keys_and_fields.append(key_and_field_for_property(prop))
-
- return all_keys_and_fields
-
-
-def _get_property_type_annotations(properties_with_math_operators):
- """
- Generate Django ORM annotations for JSONB property type extraction.
-
- This allows the database to properly cast and compare JSONB values
- when using math operators like gt/lt.
- """
- return {
- prop_key: Func(F(prop_field), function="JSONB_TYPEOF", output_field=CharField())
- for prop_key, prop_field in properties_with_math_operators
- }
-
-
-def _exclude_realtime_backfilled_cohort_properties(
- properties: list[Property], project_id: int, *, allow_realtime_backfilled: bool = False
-) -> list[Property]:
- """
- When allow_realtime_backfilled is True, filters out cohort properties that reference
- realtime+backfilled cohorts from the property list. These cohorts are evaluated by the
- Rust flag service via cohort_membership table lookups and don't need Django ORM query
- validation.
-
- When False, returns the property list unchanged.
- """
- if not allow_realtime_backfilled:
- return properties
-
- result = []
- for prop in properties:
- if prop.type == "cohort":
- try:
- cohort = Cohort.objects.get(
- pk=int(cast(Union[str, int], prop.value)),
- team__project_id=project_id,
- deleted=False,
- )
- if cohort.is_flag_compatible:
- continue
- except (Cohort.DoesNotExist, ValueError):
- pass
- result.append(prop)
- return result
-
-
-def _base_query_for_aggregation(group_type_index: Optional[int], team_id: int) -> QuerySet:
- """Return the appropriate Person or Group queryset for a given aggregation type."""
- if group_type_index is None:
- return Person.objects.db_manager(READ_ONLY_DATABASE_FOR_PERSONS).filter( # nosemgrep: no-direct-persons-db-orm
- team_id=team_id
- ) # nosemgrep: no-direct-persons-db-orm
- return Group.objects.db_manager(READ_ONLY_DATABASE_FOR_PERSONS).filter( # nosemgrep: no-direct-persons-db-orm
- team_id=team_id, group_type_index=group_type_index
- )
-
-
-def check_flag_evaluation_query_is_ok(
- feature_flag: FeatureFlag, team_id: int, project_id: int, *, allow_realtime_backfilled: bool = False
-) -> None:
- """
- Validate that a feature flag's conditions can be evaluated without errors.
-
- This is a rough simulation of the actual query that will be run during flag evaluation.
- It catches database-level errors that aren't caught by syntax validation, such as:
- - Regex patterns valid in RE2 but not PostgreSQL
- - Property filters that cause query timeouts
- - Malformed property conditions
-
- Each condition is validated against the queryset matching its own aggregation type,
- which allows flags with mixed person and group conditions to be validated correctly.
-
- NOTE: This validation is primarily for the admin UI to prevent users from creating
- flags that will fail at evaluation time. Once all flag evaluation moves to the Rust
- service, this validation may need to be updated or removed.
-
- Args:
- feature_flag: The FeatureFlag instance to validate
- team_id: The team ID the flag belongs to
- project_id: The project ID the flag belongs to
-
- Raises:
- Any database errors that occur during query execution
- """
- # Group conditions by aggregation type so each set of conditions is validated
- # against the correct base queryset (Person for None, Group for a group_type_index).
- conditions_by_aggregation: dict[Optional[int], list[tuple[int, dict]]] = {}
- for index, condition in enumerate(feature_flag.conditions):
- aggregation = condition.get("aggregation_group_type_index")
- conditions_by_aggregation.setdefault(aggregation, []).append((index, condition))
-
- for aggregation, conditions in conditions_by_aggregation.items():
- base_query = _base_query_for_aggregation(aggregation, team_id)
- query_fields = []
-
- for index, condition in conditions:
- key = f"flag_0_condition_{index}"
- property_list = Filter(data=condition).property_groups.flat
- # When realtime cohort flag targeting is enabled, realtime cohorts that have been
- # backfilled are evaluated by the Rust service via cohort_membership lookups, not
- # Django ORM queries. Skip them here so validation doesn't fail trying to translate
- # behavioral filters into SQL.
- property_list = _exclude_realtime_backfilled_cohort_properties(
- property_list, project_id, allow_realtime_backfilled=allow_realtime_backfilled
- )
- expr = properties_to_Q(
- project_id,
- property_list,
- )
- properties_with_math_operators = get_all_properties_with_math_operators(property_list, {}, project_id)
- type_property_annotations = _get_property_type_annotations(properties_with_math_operators)
- base_query = base_query.annotate(
- **type_property_annotations,
- **{
- key: ExpressionWrapper(
- # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (literal "true", no user input)
- cast(Expression, expr if expr else RawSQL("true", [])),
- output_field=BooleanField(),
- ),
- },
- )
- query_fields.append(key)
-
- values = base_query.values(*query_fields)[:10]
- len(values) # Force query execution to surface any database errors
diff --git a/posthog/models/feature_flag/test/test_flag_validation.py b/posthog/models/feature_flag/test/test_flag_validation.py
deleted file mode 100644
index 20c870f320cf..000000000000
--- a/posthog/models/feature_flag/test/test_flag_validation.py
+++ /dev/null
@@ -1,113 +0,0 @@
-from datetime import datetime
-
-from posthog.test.base import APIBaseTest
-
-from parameterized import parameterized
-
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.cohort import CohortType
-from posthog.models.feature_flag.flag_validation import _exclude_realtime_backfilled_cohort_properties
-from posthog.models.property.property import Property
-
-BEHAVIORAL_FILTERS = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "behavioral",
- "key": "$pageview",
- "value": "performed_event",
- "event_type": "events",
- "time_value": 30,
- "time_interval": "day",
- }
- ],
- }
-}
-
-
-class TestExcludeRealtimeBackfilledCohortProperties(APIBaseTest):
- def _make_cohort_property(self, cohort_id: int) -> Property:
- return Property(type="cohort", key="id", value=cohort_id)
-
- def _make_person_property(self) -> Property:
- return Property(type="person", key="email", value="[email protected]")
-
- @parameterized.expand(
- [
- # (name, cohort_kwargs, allow_realtime_backfilled, expect_cohort_filtered)
- (
- "disabled_flag_keeps_all",
- {"cohort_type": CohortType.REALTIME, "last_backfill_person_properties_at": datetime.now()},
- False,
- False,
- ),
- (
- "enabled_realtime_backfilled_filtered",
- {"cohort_type": CohortType.REALTIME, "last_backfill_person_properties_at": datetime.now()},
- True,
- True,
- ),
- (
- "enabled_realtime_not_backfilled_kept",
- {"cohort_type": CohortType.REALTIME, "last_backfill_person_properties_at": None},
- True,
- False,
- ),
- (
- "enabled_non_realtime_kept",
- {},
- True,
- False,
- ),
- ]
- )
- def test_cohort_filtering(self, _name, cohort_kwargs, allow_realtime_backfilled, expect_cohort_filtered):
- cohort = Cohort.objects.create(
- team=self.team,
- name="test-cohort",
- filters=BEHAVIORAL_FILTERS,
- **cohort_kwargs,
- )
- person_prop = self._make_person_property()
- props = [self._make_cohort_property(cohort.pk), person_prop]
-
- result = _exclude_realtime_backfilled_cohort_properties(
- props, self.team.project.id, allow_realtime_backfilled=allow_realtime_backfilled
- )
-
- if expect_cohort_filtered:
- assert result == [person_prop]
- else:
- assert result == props
-
- def test_keeps_non_cohort_properties_untouched(self):
- person_prop = self._make_person_property()
- result = _exclude_realtime_backfilled_cohort_properties(
- [person_prop], self.team.project.id, allow_realtime_backfilled=True
- )
- assert result == [person_prop]
-
- def test_handles_nonexistent_cohort_gracefully(self):
- props = [self._make_cohort_property(99999)]
- result = _exclude_realtime_backfilled_cohort_properties(
- props, self.team.project.id, allow_realtime_backfilled=True
- )
- assert result == props
-
- def test_handles_deleted_cohort(self):
- cohort = Cohort.objects.create(
- team=self.team,
- name="deleted-cohort",
- filters=BEHAVIORAL_FILTERS,
- cohort_type=CohortType.REALTIME,
- last_backfill_person_properties_at=datetime.now(),
- deleted=True,
- )
- props = [self._make_cohort_property(cohort.pk)]
-
- result = _exclude_realtime_backfilled_cohort_properties(
- props, self.team.project.id, allow_realtime_backfilled=True
- )
- # Deleted cohorts aren't found by the query (deleted=False), so they're kept
- assert result == props
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 42388921c16c..182ae9f1fe3a 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -1206,6 +1206,32 @@ class TestExperimentService(APIBaseTest):
assert "global filter properties" in str(ctx.exception)
+ @parameterized.expand([("regex",), ("not_regex",)])
+ def test_update_experiment_allows_existing_invalid_regex_in_flag_filters(self, operator):
+ experiment = self._create_draft_experiment()
+ flag = experiment.feature_flag
+ flag.filters["groups"][0]["properties"] = [
+ {"key": "email", "value": "[unclosed", "operator": operator, "type": "person"}
+ ]
+ flag.save(update_fields=["filters"])
+
+ service = self._service()
+ service.update_experiment(
+ experiment,
+ {
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ],
+ },
+ },
+ )
+
+ flag.refresh_from_db()
+ assert flag.filters["groups"][0]["properties"][0]["value"] == "[unclosed"
+ assert flag.filters["groups"][0]["properties"][0]["operator"] == operator
+
def test_update_experiment_syncs_feature_flag_variants_for_draft(self):
experiment = self._create_draft_experiment()
service = self._service()
diff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.py
index e28cb85ac809..93e12455a776 100644
--- a/products/feature_flags/backend/test/test_max_tools.py
+++ b/products/feature_flags/backend/test/test_max_tools.py
@@ -1,5 +1,7 @@
from posthog.test.base import APIBaseTest
+from parameterized import parameterized
+
from posthog.schema import FeatureFlagGroupType, GroupPropertyFilter, PersonPropertyFilter, PropertyOperator
from posthog.models import FeatureFlag
@@ -427,6 +429,36 @@ class TestCreateFeatureFlagTool(APIBaseTest):
assert flag.filters["aggregation_group_type_index"] == 0
assert len(flag.filters["groups"][0]["properties"]) == 1
+ @parameterized.expand(
+ [
+ ("regex", PropertyOperator.REGEX),
+ ("not_regex", PropertyOperator.NOT_REGEX),
+ ]
+ )
+ async def test_create_flag_rejects_invalid_regex(self, _name, operator):
+ tool = self._create_tool()
+
+ schema = FeatureFlagCreationSchema(
+ key="bad-regex-flag",
+ name="Bad Regex Flag",
+ groups=[
+ FeatureFlagGroupType(
+ properties=[
+ PersonPropertyFilter(
+ key="email",
+ value="[unclosed",
+ operator=operator,
+ )
+ ],
+ rollout_percentage=None,
+ )
+ ],
+ )
+
+ result, artifact = await tool._arun_impl(feature_flag=schema)
+ assert "Failed to create feature flag" in result
+ assert "invalid regex pattern" in result
+
@staticmethod
async def _get_tag_names(flag: FeatureFlag) -> list[str]:
from posthog.models import TaggedItem
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 4a910c4e82c9..48f9caee793b 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -1780,6 +1780,36 @@ class TestSurvey(APIBaseTest):
assert updated_survey_deletes_targeting_flag.status_code == status.HTTP_200_OK
+ @parameterized.expand([("regex",), ("not_regex",)])
+ def test_survey_targeting_flag_rejects_invalid_regex(self, operator):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={
+ "name": "survey with bad regex",
+ "type": "popover",
+ "targeting_flag_filters": {
+ "groups": [
+ {
+ "variant": None,
+ "rollout_percentage": None,
+ "properties": [
+ {
+ "key": "email",
+ "value": "[unclosed",
+ "operator": operator,
+ "type": "person",
+ }
+ ],
+ }
+ ]
+ },
+ "conditions": {"url": "https://app.posthog.com/notebooks"},
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "invalid regex pattern" in response.json()["detail"]
+
def test_survey_targeting_flag_numeric_validation(self):
survey_with_targeting = self.client.post(
f"/api/projects/{self.team.id}/surveys/",