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): remove django local_evaluation endpoint (#62229)

Patricio2ef14b3eed1c
diff --git a/docs/internal/feature-flags/billing.md b/docs/internal/feature-flags/billing.md
index 904b313c8689..373ea6ae4dfc 100644
--- a/docs/internal/feature-flags/billing.md
+++ b/docs/internal/feature-flags/billing.md
@@ -82,7 +82,7 @@ The billable flag key check is implemented as a shared predicate (`is_billable_f
### Quota enforcement
-Both Django's `/api/feature_flag/local_evaluation` and Rust's `/flags/definitions` endpoints enforce billing quotas. When a team exceeds their feature flag request quota, either endpoint returns **HTTP 402** with a JSON body:
+Rust's `/flags/definitions` endpoint enforces billing quotas. When a team exceeds their feature flag request quota, the endpoint returns **HTTP 402** with a JSON body:
```json
{
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.md
index c147b5f75815..50a2fcea12f0 100644
--- a/docs/internal/feature-flags/django-api-endpoints.md
+++ b/docs/internal/feature-flags/django-api-endpoints.md
@@ -1,8 +1,8 @@
# Django API endpoints
-Django serves the admin/management API for feature flags: CRUD operations, local SDK evaluation, analytics, and organization-level operations. Runtime flag evaluation (`/flags`, `/decide`) is routed directly to the [Rust service](rust-service-overview.md) by Contour/Envoy at the Kubernetes infrastructure level -- these requests never reach Django. Django does make internal service-to-service HTTP calls to the Rust service for actions like `my_flags` and `evaluation_reasons`.
+Django serves the admin/management API for feature flags: CRUD operations, analytics, and organization-level operations. Runtime flag evaluation (`/flags`, `/decide`) is routed directly to the [Rust service](rust-service-overview.md) by Contour/Envoy at the Kubernetes infrastructure level -- these requests never reach Django. Django does make internal service-to-service HTTP calls to the Rust service for actions like `my_flags` and `evaluation_reasons`.
-The `/api/feature_flag/local_evaluation` endpoint was historically served by a dedicated Django deployment (`posthog-local-evaluation`). As of April 2026, all local evaluation traffic is served by the Rust definitions fleet at `/flags/definitions` (see [Rust service overview](rust-service-overview.md)). The Django endpoint and deployment are deprecated and pending removal.
+The `/api/feature_flag/local_evaluation` endpoint was historically served by a dedicated Django deployment (`posthog-local-evaluation`). All local evaluation traffic is now served by the Rust definitions fleet at `/flags/definitions` (see [Rust service overview](rust-service-overview.md)). The Django endpoint and deployment have been removed.
## Architecture overview
@@ -54,7 +54,6 @@ Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked
| Method | URL | Description |
| ------ | ------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `GET` | `.../feature_flags/my_flags/` | All flags with values for the current user (proxied to Rust service) |
-| `GET` | `.../feature_flags/local_evaluation/` | Flag definitions for local SDK evaluation (ETag support) |
| `GET` | `.../feature_flags/evaluation_reasons/` | Evaluate flags for a `distinct_id` with match reasons (proxied to Rust service) |
| `POST` | `.../feature_flags/user_blast_radius/` | Estimate how many users a condition affects |
| `POST` | `.../feature_flags/{pk}/create_static_cohort_for_flag/` | Create a static cohort from matched users |
@@ -71,12 +70,6 @@ Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked
## Key actions in detail
-### `local_evaluation`
-
-Returns flag definitions for SDKs that evaluate flags locally (server-side SDKs). Response includes flags (via `MinimalFeatureFlagSerializer`), `group_type_mapping`, and optionally cohort definitions. Supports ETag-based caching. Uses HyperCache with Redis -> S3 -> PostgreSQL fallback.
-
-Requires `ProjectSecretAPIKeyAuthentication`. Rate limited at 600/minute (overridable per team via `LOCAL_EVAL_RATE_LIMITS`). Checks billing quotas via `list_limited_team_attributes`.
-
### `my_flags` and `evaluation_reasons`
Both actions **proxy to the Rust flags service** via `get_flags_from_service()` in `posthog/api/services/flags_service.py`. The Rust service URL defaults to `http://localhost:3001` (configured via `FEATURE_FLAGS_SERVICE_URL` in `posthog/settings/data_stores.py`).
diff --git a/docs/internal/feature-flags/rate-limiting.md b/docs/internal/feature-flags/rate-limiting.md
index a9078b297242..23a6457b1c95 100644
--- a/docs/internal/feature-flags/rate-limiting.md
+++ b/docs/internal/feature-flags/rate-limiting.md
@@ -77,7 +77,6 @@ A background task runs every 60 seconds (`RATE_LIMITER_CLEANUP_INTERVAL_SECS`) t
| `FLAGS_TOKEN_RATE_LIMIT_OVERRIDES` | (empty) | Per-token rate limit overrides as JSON (max 100) |
| `RATE_LIMITER_CLEANUP_INTERVAL_SECS` | `60` | Stale entry cleanup interval |
| `FLAG_DEFINITIONS_DEFAULT_RATE_PER_MINUTE` | `600` | Default rate for `/flags/definitions` |
-| `LOCAL_EVAL_RATE_LIMITS` | (empty) | Per-team overrides for `/flags/definitions` as JSON |
## Key files
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index 21ea2957bc1a..2d7a36beca58 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -140,7 +140,7 @@ Authenticated via:
- Team secret API token (`Authorization: Bearer phs_...`), or
- Personal API key with `feature_flag:read` scope
-Current implementation returns flag definitions with cohort data from HyperCache, with PostgreSQL fallback on cache miss. Supports ETag-based conditional requests (`If-None-Match` header) to avoid re-transferring unchanged definitions. Rate limited per team (default 600/minute, per-team overrides via `LOCAL_EVAL_RATE_LIMITS`).
+Current implementation returns flag definitions with cohort data from HyperCache, with PostgreSQL fallback on cache miss. Supports ETag-based conditional requests (`If-None-Match` header) to avoid re-transferring unchanged definitions. Rate limited per team (default 600/minute).
Billing quota enforcement matches Django's `/api/feature_flag/local_evaluation` behavior:
diff --git a/posthog/api/test/test_classify_auth_method.py b/posthog/api/test/test_classify_auth_method.py
deleted file mode 100644
index 7127a5f672f4..000000000000
--- a/posthog/api/test/test_classify_auth_method.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from django.test import TestCase
-
-from parameterized import parameterized
-
-from posthog.auth import (
- JwtAuthentication,
- OAuthAccessTokenAuthentication,
- PersonalAPIKeyAuthentication,
- ProjectSecretAPIKeyAuthentication,
- SessionAuthentication,
-)
-
-from products.feature_flags.backend.api.feature_flag import _classify_auth_method
-
-
-class TestClassifyAuthMethod(TestCase):
- @parameterized.expand(
- [
- (ProjectSecretAPIKeyAuthentication(), "secret_api_key"),
- (PersonalAPIKeyAuthentication(), "personal_api_key"),
- (OAuthAccessTokenAuthentication(), "oauth"),
- (JwtAuthentication(), "jwt"),
- (SessionAuthentication(), "session"),
- (None, "other"),
- ("unexpected_type", "other"),
- ]
- )
- def test_returns_expected_label(self, authenticator, expected):
- self.assertEqual(_classify_auth_method(authenticator), expected)
diff --git a/posthog/api/test/test_local_evaluation.py b/posthog/api/test/test_local_evaluation.py
deleted file mode 100644
index 4079b584e2e3..000000000000
--- a/posthog/api/test/test_local_evaluation.py
+++ /dev/null
@@ -1,517 +0,0 @@
-from posthog.test.base import APIBaseTest
-
-from rest_framework import status
-
-from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.surveys.backend.models import Survey
-
-
-class TestFeatureFlagDependencyTransformation(APIBaseTest):
- """Test flag dependency transformation in local_evaluation endpoint."""
-
- def setUp(self):
- super().setUp()
- # Clean up existing flags to avoid interference
- FeatureFlag.objects.all().delete()
-
- def _find_flag(self, flags: list[dict], key: str) -> dict:
- """Helper method to find a flag by key in the flags list."""
- return next(flag for flag in flags if flag["key"] == key)
-
- def test_flag_dependency_transformation_complex_chain(self):
- """Test dependency transformation with complex dependency chains."""
- # Create a flag dependency chain: C -> B -> A
- # Create flag A
- flag_a = FeatureFlag.objects.create(
- team=self.team,
- key="flag-a",
- name="Flag A",
- filters={
- "groups": [
- {
- "properties": [
- {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Create flag B that depends on flag A
- flag_b = FeatureFlag.objects.create(
- team=self.team,
- key="flag-b",
- name="Flag B",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Create flag C that depends on flag B
- FeatureFlag.objects.create(
- team=self.team,
- key="flag-c",
- name="Flag C",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- flag_c_data = self._find_flag(flags, "flag-c")
-
- properties = flag_c_data["filters"]["groups"][0]["properties"]
- flag_property = next(prop for prop in properties if prop["type"] == "flag")
-
- # ID should be converted to key
- self.assertEqual(flag_property["key"], "flag-b")
-
- # Full dependency chain should be included (topologically sorted)
- self.assertIn("dependency_chain", flag_property)
- self.assertEqual(flag_property["dependency_chain"], ["flag-a", "flag-b"])
-
- flag_b_data = self._find_flag(flags, "flag-b")
- properties_b = flag_b_data["filters"]["groups"][0]["properties"]
- flag_property_b = next(prop for prop in properties_b if prop["type"] == "flag")
- self.assertEqual(flag_property_b["dependency_chain"], ["flag-a"])
-
- def test_flag_dependency_transformation_circular_dependency(self):
- """Test handling of circular dependencies."""
- # Create flag A
- flag_a = FeatureFlag.objects.create(
- team=self.team,
- key="flag-a",
- name="Flag A",
- filters={
- "groups": [
- {
- "properties": [
- {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Create flag B that depends on flag A
- flag_b = FeatureFlag.objects.create(
- team=self.team,
- key="flag-b",
- name="Flag B",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Update flag A to depend on flag B (creating a cycle)
- flag_a.filters = {
- "groups": [
- {
- "properties": [
- {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- }
- flag_a.save()
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
-
- self.assertIn("flags", data)
- self.assertEqual(len(data["flags"]), 2)
-
- flag_a_data = self._find_flag(data["flags"], "flag-a")
- flag_b_data = self._find_flag(data["flags"], "flag-b")
-
- # Check flag A's dependency chain is empty
- properties_a = flag_a_data["filters"]["groups"][0]["properties"]
- flag_properties_a = [prop for prop in properties_a if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties_a), 1)
- self.assertEqual(flag_properties_a[0]["dependency_chain"], [])
-
- # Check flag B's dependency chain is empty
- properties_b = flag_b_data["filters"]["groups"][0]["properties"]
- flag_properties_b = [prop for prop in properties_b if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties_b), 1)
- self.assertEqual(flag_properties_b[0]["dependency_chain"], [])
-
- def test_flag_dependency_transformation_multiple_dependencies(self):
- """Test transformation with multiple flag dependencies and transitive dependencies."""
- # Create base flags
- flag_a = FeatureFlag.objects.create(
- team=self.team,
- key="flag-a",
- name="Flag A",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- flag_b = FeatureFlag.objects.create(
- team=self.team,
- key="flag-b",
- name="Flag B",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- # Create flag C that depends on both A and B
- flag_c = FeatureFlag.objects.create(
- team=self.team,
- key="flag-c",
- name="Flag C",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
- {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
- {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Create flag D that depends on flag C (testing transitive dependencies)
- FeatureFlag.objects.create(
- team=self.team,
- key="flag-d",
- name="Flag D",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_c.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
- {"key": "country", "type": "person", "value": "US", "operator": "exact"},
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- flag_c_data = self._find_flag(flags, "flag-c")
-
- properties = flag_c_data["filters"]["groups"][0]["properties"]
- flag_properties = [prop for prop in properties if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties), 2)
-
- flag_keys = {prop["key"] for prop in flag_properties}
- self.assertEqual(flag_keys, {"flag-a", "flag-b"})
-
- for prop in flag_properties:
- self.assertIn("dependency_chain", prop)
- if prop["key"] == "flag-a":
- self.assertEqual(prop["dependency_chain"], ["flag-a"])
- elif prop["key"] == "flag-b":
- self.assertEqual(prop["dependency_chain"], ["flag-b"])
-
- flag_d_data = self._find_flag(flags, "flag-d")
-
- properties_d = flag_d_data["filters"]["groups"][0]["properties"]
- flag_properties_d = [prop for prop in properties_d if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties_d), 1)
- self.assertEqual(flag_properties_d[0]["key"], "flag-c")
-
- self.assertEqual(flag_properties_d[0]["dependency_chain"], ["flag-a", "flag-b", "flag-c"])
-
- def test_flag_dependency_transformation_self_dependency(self):
- """Test transformation handles self-dependency gracefully."""
- # Create a flag that depends on itself
- FeatureFlag.objects.create(
- team=self.team,
- key="self-flag",
- name="Self Flag",
- filters={
- "groups": [
- {
- "properties": [
- # This flag references itself - should be detected as self-dependency
- {"key": "self-flag", "type": "flag", "value": True, "operator": "flag_evaluates_to"},
- {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- self_flag_data = self._find_flag(flags, "self-flag")
-
- properties = self_flag_data["filters"]["groups"][0]["properties"]
- flag_properties = [prop for prop in properties if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties), 1)
- self.assertEqual(flag_properties[0]["key"], "self-flag")
-
- self.assertEqual(flag_properties[0]["dependency_chain"], [])
-
- def test_flag_dependency_transformation_self_referencing_circular_dependency(self):
- """Test flagA -> flagB -> flagB scenario where flagB references itself."""
- # Create flag B that references itself
- flag_b = FeatureFlag.objects.create(
- team=self.team,
- key="flag-b",
- name="Flag B",
- filters={
- "groups": [
- {
- "properties": [
- {"key": "flag-b", "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Create flag A that depends on flag B (which has self-dependency)
- FeatureFlag.objects.create(
- team=self.team,
- key="flag-a",
- name="Flag A",
- filters={
- "groups": [
- {
- "properties": [
- {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- flag_a_data = self._find_flag(flags, "flag-a")
- flag_b_data = self._find_flag(flags, "flag-b")
-
- # Flag B should have empty dependency chain due to self-reference
- properties_b = flag_b_data["filters"]["groups"][0]["properties"]
- flag_properties_b = [prop for prop in properties_b if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties_b), 1)
- self.assertEqual(flag_properties_b[0]["key"], "flag-b")
- self.assertEqual(flag_properties_b[0]["dependency_chain"], [])
-
- # Flag A should have empty dependency chain because it depends on flag B which can't be evaluated
- properties_a = flag_a_data["filters"]["groups"][0]["properties"]
- flag_properties_a = [prop for prop in properties_a if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties_a), 1)
- self.assertEqual(flag_properties_a[0]["key"], "flag-b")
- self.assertEqual(flag_properties_a[0]["dependency_chain"], [])
-
- def test_flag_dependency_transformation_missing_dependency(self):
- """Test that missing flag dependencies result in empty dependency chain."""
- # Create flag A that references a non-existent flag by ID
- non_existent_flag_id = "999999" # ID that doesn't exist
-
- FeatureFlag.objects.create(
- team=self.team,
- key="flag-a",
- name="Flag A",
- filters={
- "groups": [
- {
- "properties": [
- {
- "key": non_existent_flag_id,
- "type": "flag",
- "value": True,
- "operator": "flag_evaluates_to",
- },
- {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- flag_a_data = self._find_flag(flags, "flag-a")
-
- properties = flag_a_data["filters"]["groups"][0]["properties"]
- flag_properties = [prop for prop in properties if prop["type"] == "flag"]
- self.assertEqual(len(flag_properties), 1)
-
- # The key should remain as the original ID since it can't be resolved
- self.assertEqual(flag_properties[0]["key"], non_existent_flag_id)
-
- # Dependency chain should be empty because the referenced flag doesn't exist
- self.assertEqual(flag_properties[0]["dependency_chain"], [])
-
- def test_flag_dependency_transformation_shared_dependencies(self):
- """Test that shared dependencies are handled correctly and efficiently."""
- # Create a base flag that will be shared by multiple other flags
- shared_flag = FeatureFlag.objects.create(
- team=self.team,
- key="shared-dependency",
- name="Shared Dependency",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- # Create multiple flags that all depend on the same shared flag
- dependent_flags = []
- for i in range(5): # Create 5 flags that depend on the shared flag
- flag = FeatureFlag.objects.create(
- team=self.team,
- key=f"dependent-flag-{i}",
- name=f"Dependent Flag {i}",
- filters={
- "groups": [
- {
- "properties": [
- {
- "key": str(shared_flag.id),
- "type": "flag",
- "value": True,
- "operator": "flag_evaluates_to",
- }
- ],
- "rollout_percentage": 100,
- }
- ]
- },
- )
- dependent_flags.append(flag)
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- flags = data["flags"]
-
- # Verify that all dependent flags have the correct dependency chain
- for i, _flag in enumerate(dependent_flags):
- flag_data = self._find_flag(flags, f"dependent-flag-{i}")
- properties = flag_data["filters"]["groups"][0]["properties"]
- flag_properties = [prop for prop in properties if prop["type"] == "flag"]
-
- self.assertEqual(len(flag_properties), 1)
- self.assertEqual(flag_properties[0]["key"], "shared-dependency")
- self.assertEqual(flag_properties[0]["dependency_chain"], ["shared-dependency"])
-
- # This test demonstrates that:
- # 1. The shared dependency chain is built once and reused
- # 2. All flags referencing the same dependency get the same chain
- # 3. The optimization correctly handles multiple flags with shared dependencies
-
-
-class TestSurveyFlagExclusionAPI(APIBaseTest):
- """Integration tests for survey flag exclusion from local_evaluation endpoint (GitHub issue #43631)."""
-
- def setUp(self):
- super().setUp()
- FeatureFlag.objects.all().delete()
-
- def test_survey_flags_excluded_from_local_evaluation_endpoint(self):
- """Survey-linked flags should be excluded from the local_evaluation API response."""
- regular_flag = FeatureFlag.objects.create(
- team=self.team,
- key="regular-flag",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
-
- targeting_flag = FeatureFlag.objects.create(
- team=self.team,
- key="survey-targeting-flag",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
- internal_targeting_flag = FeatureFlag.objects.create(
- team=self.team,
- key="survey-internal-targeting-flag",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
- response_sampling_flag = FeatureFlag.objects.create(
- team=self.team,
- key="survey-response-sampling-flag",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
-
- Survey.objects.create(
- team=self.team,
- name="Test Survey",
- type="popover",
- targeting_flag=targeting_flag,
- internal_targeting_flag=internal_targeting_flag,
- internal_response_sampling_flag=response_sampling_flag,
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- data = response.json()
- flag_keys = [f["key"] for f in data["flags"]]
-
- self.assertIn(regular_flag.key, flag_keys)
- self.assertNotIn(targeting_flag.key, flag_keys)
- self.assertNotIn(internal_targeting_flag.key, flag_keys)
- self.assertNotIn(response_sampling_flag.key, flag_keys)
-
- def test_linked_flag_included_in_local_evaluation_endpoint(self):
- """User-created linked_flag should NOT be excluded from the local_evaluation API response."""
- user_linked_flag = FeatureFlag.objects.create(
- team=self.team,
- key="user-linked-flag",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
-
- Survey.objects.create(
- team=self.team,
- name="Test Survey",
- type="popover",
- linked_flag=user_linked_flag,
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- data = response.json()
- flag_keys = [f["key"] for f in data["flags"]]
-
- self.assertIn(user_linked_flag.key, flag_keys)
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 5e38e5f4964a..0bb46f2ae93b 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -600,33 +600,24 @@ class TestPersonalAPIKeysWithScopeAPIAuthentication(PersonalAPIKeysBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json()["detail"] == "API key missing required scope 'feature_flag:write'"
- def test_allows_legacy_feature_flag_local_evaluation_with_personal_api_key(self):
- response = self._do_request(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
-
+ def test_allows_action_with_required_scopes(self):
+ response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/my_flags")
assert response.status_code == status.HTTP_200_OK
- response_data = response.json()
- assert "flags" in response_data
- assert "group_type_mapping" in response_data
- assert "cohorts" in response_data
- def test_legacy_feature_flag_evaluation_with_no_current_team(self):
+ def test_feature_flag_list_with_no_current_team(self):
+ # LegacyFeatureFlagViewSet resolves the project from the token when the user
+ # has no current_team (param_derived_from_user_current_team), so the list route
+ # must still work in that case.
original_team = self.user.current_team
-
try:
self.user.current_team = None
self.user.save()
-
- # Use team token to provide team context when user.current_team is None
- response = self._do_request(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
+ response = self._do_request(f"/api/feature_flag/?token={self.team.api_token}")
assert response.status_code == status.HTTP_200_OK
finally:
self.user.current_team = original_team
self.user.save()
- def test_allows_action_with_required_scopes(self):
- response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
- assert response.status_code == status.HTTP_200_OK
-
def test_allows_custom_error_tracking_read_action(self):
self.key.scopes = ["error_tracking:read"]
self.key.save()
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.py
index 6c6f10c0a7b2..783264ae969e 100644
--- a/posthog/settings/feature_flags.py
+++ b/posthog/settings/feature_flags.py
@@ -19,12 +19,6 @@ PERSISTED_FEATURE_FLAGS = get_list(os.getenv("PERSISTED_FEATURE_FLAGS", ""))
# so a key is always present.
FLAGS_SECRET_KEYS: list[str] = get_list(os.getenv("FLAGS_SECRET_KEYS", "")) or [SECRET_KEY]
-# Per-team local evaluation rate limits, e.g. {"123": "1200/minute", "456": "2400/hour"}
-LOCAL_EVAL_RATE_LIMITS: dict[int, str] = {}
-with suppress(Exception):
- as_json = json.loads(os.getenv("LOCAL_EVAL_RATE_LIMITS", "{}"))
- LOCAL_EVAL_RATE_LIMITS = {int(k): str(v) for k, v in as_json.items()}
-
# Per-team remote config rate limits, e.g. {"123": "1200/minute", "456": "2400/hour"}
REMOTE_CONFIG_RATE_LIMITS: dict[int, str] = {}
with suppress(Exception):
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index 67e044bd086d..e64bf912dc9a 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -681,7 +681,7 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):
def test_allows_action_with_required_scopes(self):
"""OAuth token can access endpoints that match its scopes"""
- response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/local_evaluation")
+ response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/my_flags")
self.assertEqual(response.status_code, 200)
def test_allows_custom_error_tracking_write_action(self):
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 80a5b43aaabf..d5d5aed7fbf6 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -29,7 +29,7 @@ from posthog.rate_limit import (
get_route_from_path,
)
-from products.feature_flags.backend.api.feature_flag import LocalEvaluationThrottle, RemoteConfigThrottle
+from products.feature_flags.backend.api.feature_flag import RemoteConfigThrottle
class TestUserAPI(APIBaseTest):
@@ -642,79 +642,6 @@ class TestUserAPI(APIBaseTest):
},
)
- def test_local_evaluation_throttle_uses_default_rate_when_no_custom_limit(self):
- throttle = LocalEvaluationThrottle()
-
- # Mock view and request
- mock_view = Mock()
- mock_request = Mock()
-
- with (
- patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),
- patch.object(throttle, "safely_get_team_id_from_view", return_value=123),
- patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),
- ):
- result = throttle.allow_request(mock_request, mock_view)
-
- self.assertTrue(result)
- # Rate should remain default
- self.assertEqual(throttle.rate, "600/minute")
-
- def test_local_evaluation_throttle_handles_empty_settings(self):
- throttle = LocalEvaluationThrottle()
-
- # Mock view and request
- mock_view = Mock()
- mock_request = Mock()
-
- with (
- patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),
- patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),
- patch.object(throttle, "safely_get_team_id_from_view", return_value=123),
- patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),
- ):
- result = throttle.allow_request(mock_request, mock_view)
-
- self.assertTrue(result)
- # Should use default rate
- self.assertEqual(throttle.rate, "600/minute")
-
- def test_local_evaluation_throttle_handles_missing_team_gracefully(self):
- throttle = LocalEvaluationThrottle()
-
- # Mock view without team_id
- mock_view = Mock()
- mock_view.team_id = None
-
- # Test with missing team
- with patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True):
- with patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True):
- result = throttle.allow_request(Mock(), mock_view)
-
- self.assertTrue(result)
- # Should keep default rate
- self.assertEqual(throttle.rate, "600/minute")
-
- def test_local_evaluation_throttle_uses_custom_rate_for_team(self):
- throttle = LocalEvaluationThrottle()
-
- # Mock view and request
- mock_view = Mock()
- mock_request = Mock()
-
- with (
- patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {123: "1200/minute"}),
- patch.object(throttle, "safely_get_team_id_from_view", return_value=123),
- patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),
- ):
- result = throttle.allow_request(mock_request, mock_view)
-
- self.assertTrue(result)
- # Should use custom rate
- self.assertEqual(throttle.rate, "1200/minute")
- self.assertEqual(throttle.num_requests, 1200)
- self.assertEqual(throttle.duration, 60) # 1 minute in seconds
-
def test_remote_config_throttle_uses_default_rate_when_no_custom_limit(self):
throttle = RemoteConfigThrottle()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index a8777fc00621..24070fb2f573 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -4,7 +4,6 @@ import re
import copy
import json
import math
-import time
import logging
import functools
from datetime import datetime, timedelta
@@ -18,7 +17,6 @@ import structlog
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse
-from prometheus_client import Counter
from rest_framework import exceptions, request, serializers, status, viewsets
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
@@ -39,15 +37,9 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSet
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action
from posthog.approvals.decorators import approval_gate
from posthog.approvals.mixins import ApprovalHandlingMixin
-from posthog.auth import (
- JwtAuthentication,
- OAuthAccessTokenAuthentication,
- PersonalAPIKeyAuthentication,
- ProjectSecretAPIKeyAuthentication,
- SessionAuthentication,
-)
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.constants import PRODUCT_TOUR_TARGETING_FLAG_PREFIX, SURVEY_TARGETING_FLAG_PREFIX, FlagRequestType
+from posthog.constants import FlagRequestType
from posthog.date_util import thirty_days_ago
from posthog.event_usage import report_user_action
from posthog.exceptions import Conflict
@@ -68,8 +60,7 @@ from posthog.queries.base import determine_parsed_date_for_property_matching
from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
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.storage.hypercache import HyperCacheDependencyUnavailable
+from posthog.settings.feature_flags import REMOTE_CONFIG_RATE_LIMITS
from posthog.utils import is_valid_regex
from posthog.views import format_bytes
@@ -84,11 +75,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
)
from products.feature_flags.backend.flag_analytics import increment_request_count
from products.feature_flags.backend.flag_status import FeatureFlagStatusChecker
-from products.feature_flags.backend.local_evaluation import (
- DATABASE_FOR_LOCAL_EVALUATION,
- _get_flag_properties_from_filters,
- get_flags_response_if_none_match,
-)
+from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filters
from products.feature_flags.backend.models.evaluation_context import normalize_context_name
from products.feature_flags.backend.models.feature_flag import (
FeatureFlag,
@@ -273,52 +260,6 @@ FEATURE_FLAG_CREATION_CONTEXT_CHOICES = (
"product_tours",
)
-LOCAL_EVALUATION_REQUEST_COUNTER = Counter(
- "posthog_local_evaluation_request_total",
- "Local evaluation API requests",
- labelnames=["send_cohorts"],
-)
-
-LOCAL_EVALUATION_ETAG_COUNTER = Counter(
- "posthog_local_evaluation_etag_total",
- "Local evaluation ETag cache results",
- labelnames=["result"], # "hit" (304), "miss" (200), "none" (no client etag)
-)
-
-LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER = Counter(
- "posthog_local_evaluation_secret_api_key_in_body_total",
- "Local evaluation requests where secret_api_key was passed in request body instead of Authorization header",
-)
-
-LOCAL_EVALUATION_AUTH_COUNTER = Counter(
- "posthog_local_evaluation_auth_total",
- "Local evaluation requests by authentication method",
- labelnames=["method"], # "secret_api_key", "personal_api_key", "oauth", "jwt", "session", or "other"
-)
-
-LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER = Counter(
- "posthog_local_evaluation_personal_api_key_source_total",
- "Local evaluation requests authenticated via personal API key, by source",
- labelnames=["source"], # "header", "body", "query_string"
-)
-
-LOCAL_EVALUATION_DEPENDENCY_UNAVAILABLE_COUNTER = Counter(
- "posthog_local_evaluation_dependency_unavailable_total",
- "Local evaluation requests returning 503 because a flag dependency was unavailable on a cold cache",
-)
-
-_AUTH_METHOD_BY_CLASS: dict[type, str] = {
- ProjectSecretAPIKeyAuthentication: "secret_api_key",
- PersonalAPIKeyAuthentication: "personal_api_key",
- OAuthAccessTokenAuthentication: "oauth",
- JwtAuthentication: "jwt",
- SessionAuthentication: "session",
-}
-
-
-def _classify_auth_method(authenticator: object | None) -> str:
- return _AUTH_METHOD_BY_CLASS.get(type(authenticator), "other")
-
def find_dependent_flags(flag_to_check: FeatureFlag) -> list[FeatureFlag]:
"""Find all active flags that depend on the given flag via flag-type filter properties."""
@@ -495,47 +436,6 @@ def check_flag_limits_for_team(
)
-def extract_etag_from_header(header_value: str | None) -> str | None:
- """
- Extract ETag value from an If-None-Match header.
-
- Handles both strong ETags ("abc123") and weak ETags (W/"abc123") per RFC 7232.
- Malformed weak ETags (ex. "W/abc123" where quotes are missing) are returned as-is.
- Returns None if the header is empty or None.
- """
- if not header_value:
- return None
-
- etag = header_value.strip()
- if etag.startswith('W/"'):
- etag = etag[2:] # Remove W/ prefix
- etag = etag.strip('"')
-
- return etag if etag else None
-
-
-class LocalEvaluationThrottle(BurstRateThrottle):
- # Throttle class that's scoped just to the local evaluation endpoint.
- # This makes the rate limit independent of other endpoints.
- scope = "feature_flag_evaluations"
- rate = "600/minute"
-
- def allow_request(self, request, view):
- logger = logging.getLogger(__name__)
-
- team_id = self.safely_get_team_id_from_view(view)
- if team_id:
- try:
- custom_rate = LOCAL_EVAL_RATE_LIMITS.get(team_id)
- if custom_rate:
- self.rate = custom_rate
- self.num_requests, self.duration = self.parse_rate(self.rate)
- except Exception:
- logger.exception(f"Error getting team-specific rate limit for team {team_id}")
-
- return super().allow_request(request, view)
-
-
class RemoteConfigThrottle(BurstRateThrottle):
scope = "feature_flag_remote_config"
rate = "600/minute"
@@ -2101,22 +2001,6 @@ class MyFlagsQuerySerializer(serializers.Serializer):
groups = GroupsJSONField()
-class LocalEvaluationQuerySerializer(serializers.Serializer):
- send_cohorts = serializers.BooleanField(
- required=False,
- default=False,
- allow_null=True,
- help_text="Include cohorts in response",
- )
-
- def to_internal_value(self, data):
- # Handle ?send_cohorts without a value (empty string) as True
- if "send_cohorts" in data and data["send_cohorts"] == "":
- data = data.copy()
- data["send_cohorts"] = True
- return super().to_internal_value(data)
-
-
class EvaluationReasonsQuerySerializer(serializers.Serializer):
distinct_id = serializers.CharField(required=True, help_text="User distinct ID")
groups = GroupsJSONField()
@@ -2380,15 +2264,6 @@ class MyFlagsResponseListSerializer(serializers.ListSerializer):
child = MyFlagsResponseSerializer()
-class LocalEvaluationResponseSerializer(serializers.Serializer):
- flags: serializers.ListSerializer = serializers.ListSerializer(child=MinimalFeatureFlagSerializer())
- group_type_mapping = serializers.DictField(child=serializers.CharField())
- cohorts = serializers.DictField(
- child=serializers.JSONField(),
- help_text="Cohort definitions keyed by cohort ID. Each value is a property group structure with 'type' (OR/AND) and 'values' (array of property groups or property filters).",
- )
-
-
class BulkKeysRequestSerializer(serializers.Serializer):
ids = serializers.ListField(
child=serializers.JSONField(),
@@ -3445,210 +3320,6 @@ class FeatureFlagViewSet(
return queryset
- @validated_request(
- query_serializer=LocalEvaluationQuerySerializer,
- responses={
- 200: OpenApiResponse(response=LocalEvaluationResponseSerializer()),
- 402: OpenApiResponse(description="Payment required"),
- 500: OpenApiResponse(description="Internal server error"),
- 503: OpenApiResponse(description="Feature flag dependencies temporarily unavailable"),
- },
- )
- @action(
- methods=["GET"],
- detail=False,
- throttle_classes=[LocalEvaluationThrottle],
- required_scopes=["feature_flag:read"],
- authentication_classes=[
- ProjectSecretAPIKeyAuthentication,
- ],
- permission_classes=[ProjectSecretAPITokenPermission],
- )
- def local_evaluation(self, request: request.Request, **kwargs) -> Response:
- # **kwargs is required because DRF passes parent_lookup_project_id from nested router
- start_time = time.time()
- logger = logging.getLogger(__name__)
-
- # Track if secret_api_key was passed in request body AND was the actual auth mechanism.
- # If the header also has a phs_ token, the header wins and the body value is ignored,
- # so Rust (header-only) would still authenticate fine — no need to count those.
- auth_header = request.headers.get("authorization", "")
- if (
- request.data.get("secret_api_key")
- and isinstance(request.successful_authenticator, ProjectSecretAPIKeyAuthentication)
- and not re.match(r"^Bearer\s+phs_[a-zA-Z0-9]+$", auth_header)
- ):
- LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER.inc()
-
- # Use validated boolean value from serializer
- include_cohorts = request.validated_query_data.get("send_cohorts", False)
-
- # Extract client ETag from If-None-Match header
- client_etag = extract_etag_from_header(request.headers.get("If-None-Match"))
-
- # Track send_cohorts parameter usage
- LOCAL_EVALUATION_REQUEST_COUNTER.labels(send_cohorts=str(include_cohorts).lower()).inc()
-
- auth_method = _classify_auth_method(request.successful_authenticator)
- LOCAL_EVALUATION_AUTH_COUNTER.labels(method=auth_method).inc()
-
- if isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication):
- source = request.successful_authenticator.personal_api_key_source or "unknown"
- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source).inc()
-
- try:
- # Check if team is quota limited for feature flags
- if getattr(settings, "DECIDE_FEATURE_FLAG_QUOTA_CHECK", True):
- from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes
-
- limited_tokens_flags = list_limited_team_attributes(
- QuotaResource.FEATURE_FLAG_REQUESTS,
- QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
- )
- if self.team.api_token in limited_tokens_flags:
- return Response(
- {
- "type": "quota_limited",
- "detail": "You have exceeded your feature flag request quota",
- "code": "payment_required",
- },
- status=status.HTTP_402_PAYMENT_REQUIRED,
- )
-
- logger.info(
- "Starting local evaluation",
- extra={
- "team_id": self.team.pk,
- "has_send_cohorts": include_cohorts,
- },
- )
-
- response_data, etag, modified = get_flags_response_if_none_match(self.team, include_cohorts, client_etag)
-
- # Track ETag effectiveness
- result = "none" if not client_etag else ("hit" if not modified else "miss")
- LOCAL_EVALUATION_ETAG_COUNTER.labels(result=result).inc()
-
- # Return 304 Not Modified if client's ETag matches
- if not modified and etag:
- response = Response(status=status.HTTP_304_NOT_MODIFIED)
- response["ETag"] = f'W/"{etag}"'
- response["Cache-Control"] = "private, must-revalidate"
- return response
-
- if not response_data:
- raise Exception("No response data")
-
- flag_keys = [flag["key"] for flag in response_data["flags"]]
-
- # Add request for analytics
- if len(flag_keys) > 0 and not all(
- flag_key.startswith(SURVEY_TARGETING_FLAG_PREFIX)
- or flag_key.startswith(PRODUCT_TOUR_TARGETING_FLAG_PREFIX)
- for flag_key in flag_keys
- ):
- increment_request_count(self.team.pk, 1, FlagRequestType.LOCAL_EVALUATION)
-
- response = Response(response_data)
- if etag:
- response["ETag"] = f'W/"{etag}"'
- response["Cache-Control"] = "private, must-revalidate"
- return response
-
- except HyperCacheDependencyUnavailable:
- # Cold cache during an upstream (persons DB) outage. Fail loud with a
- # retryable 503 rather than a generic 500: SDKs treat 5xx as "retry / keep
- # last-known config". The dependency layer already captured this (throttled),
- # so re-capturing per request would flood Sentry during an outage.
- LOCAL_EVALUATION_DEPENDENCY_UNAVAILABLE_COUNTER.inc()
- duration = time.time() - start_time
- logger.warning(
- "Feature flag dependencies unavailable during local evaluation",
- extra={"duration": duration, "team_id": self.team.pk},
- )
- response = Response(
- {
- "type": "service_unavailable",
- "code": "flags_dependency_unavailable",
- "detail": "Feature flag dependencies are temporarily unavailable; retry shortly",
- },
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
- response["Retry-After"] = "30"
- return response
- except Exception as e:
- duration = time.time() - start_time
- logger.error(
- "Unexpected error in local evaluation",
- extra={"duration": duration},
- exc_info=True,
- )
- capture_exception(e)
- return Response(
- {
- "type": "server_error",
- "code": "unexpected_error",
- "detail": "An unexpected error occurred",
- },
- status=500,
- )
-
- def _handle_cached_response(self, cached_response: Optional[dict]) -> Optional[Response]:
- """Handle cached response including analytics tracking."""
- if cached_response is None:
- return None
-
- # Increment request count for analytics (exclude survey and product tour targeting flags)
- if cached_response.get("flags") and not all(
- flag.get("key", "").startswith(SURVEY_TARGETING_FLAG_PREFIX)
- or flag.get("key", "").startswith(PRODUCT_TOUR_TARGETING_FLAG_PREFIX)
- for flag in cached_response["flags"]
- ):
- increment_request_count(self.team.pk, 1, FlagRequestType.LOCAL_EVALUATION)
-
- return Response(cached_response)
-
- def _build_cohort_properties_cache(self, cohorts, seen_cohorts_cache, feature_flag):
- """
- Builds a cache of cohort properties for a feature flag.
-
- This is used to avoid duplicate queries for cohort properties.
-
- Args:
- cohorts: The cache of cohort properties.
- seen_cohorts_cache: The cache of seen cohorts.
- feature_flag: The feature flag to build the cache for.
- """
- logger = logging.getLogger(__name__)
- cohort_ids = feature_flag.get_cohort_ids(
- using_database=DATABASE_FOR_LOCAL_EVALUATION,
- seen_cohorts_cache=seen_cohorts_cache,
- )
-
- for id in cohort_ids:
- # don't duplicate queries for already added cohorts
- if id not in cohorts:
- if id in seen_cohorts_cache:
- cohort = seen_cohorts_cache[id]
- else:
- cohort = (
- Cohort.objects.db_manager(DATABASE_FOR_LOCAL_EVALUATION)
- .filter(id=id, team__project_id=self.project_id, deleted=False)
- .first()
- )
- seen_cohorts_cache[id] = cohort or ""
-
- if cohort and not cohort.is_static:
- try:
- cohorts[str(cohort.pk)] = cohort.properties.to_dict()
- except Exception:
- logger.error(
- "Error processing cohort properties",
- extra={"cohort_id": id},
- exc_info=True,
- )
- continue
-
@validated_request(
query_serializer=EvaluationReasonsQuerySerializer,
responses={
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 0f6a6d09828c..39186a337a9a 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -41,7 +41,7 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, extract_etag_from_header
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload
from products.feature_flags.backend.flag_status import FeatureFlagStatus
from products.feature_flags.backend.models.feature_flag import (
@@ -57,32 +57,6 @@ from products.surveys.backend.models import Survey
from ee.models.rbac.access_control import AccessControl
-class TestExtractEtagFromHeader:
- """Unit tests for extract_etag_from_header function."""
-
- @parameterized.expand(
- [
- # (test_name, input_header, expected_output)
- ("strong_etag_quoted", '"abc123"', "abc123"),
- ("strong_etag_unquoted", "abc123", "abc123"),
- ("weak_etag", 'W/"abc123"', "abc123"),
- # W/abc123 is malformed per RFC 7232 (weak ETags require quotes)
- # We treat it as a literal string, which won't match any stored ETag
- ("weak_etag_malformed", "W/abc123", "W/abc123"),
- ("etag_starting_with_w", '"WXYZ1234"', "WXYZ1234"),
- ("etag_starting_with_slash", '"/path/to/resource"', "/path/to/resource"),
- ("etag_with_special_chars", '"abc-123_456"', "abc-123_456"),
- ("etag_with_whitespace", ' "abc123" ', "abc123"),
- ("empty_string", "", None),
- ("whitespace_only", " ", None),
- ("none_value", None, None),
- ("empty_quotes", '""', None),
- ]
- )
- def test_extract_etag_from_header(self, _name: str, header_value: str | None, expected: str | None):
- assert extract_etag_from_header(header_value) == expected
-
-
class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
feature_flag: FeatureFlag = None # type: ignore
@@ -4152,370 +4126,310 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
},
)
- @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_local_evaluation_for_invalid_cohorts(self, mock_report_user_action):
+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
+ def test_local_evaluation_billing_analytics_for_regular_feature_flag_list(self):
FeatureFlag.objects.all().delete()
- self.team.app_urls = ["https://example.com"]
- self.team.save()
-
- other_team = Team.objects.create(
- organization=self.organization,
- api_token="bazinga_new",
- name="New Team",
+ # old style feature flags
+ FeatureFlag.objects.create(
+ name="Beta feature",
+ key="beta-feature",
+ team=self.team,
+ filters={"properties": [{"key": "beta-property", "value": "beta-value"}]},
+ created_by=self.user,
+ )
+ # and inactive flag
+ FeatureFlag.objects.create(
+ name="Inactive feature",
+ key="inactive-flag",
+ team=self.team,
+ active=False,
+ filters={"properties": []},
+ created_by=self.user,
)
+ client = redis.get_client()
+
personal_api_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
)
- deleted_cohort = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "$some_prop_1",
- "value": "something_1",
- "type": "person",
- }
- ]
- },
- ],
- name="cohort1",
- deleted=True,
- )
+ # request made while logged in, via client cookie auth
+ response = self.client.get(f"/api/feature_flag?token={self.team.api_token}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["count"], 2)
- cohort_from_other_team = Cohort.objects.create(
- team=other_team,
- groups=[
- {
- "properties": [
- {
- "key": "$some_prop_1",
- "value": "something_1",
- "type": "person",
- }
- ]
- },
- ],
- name="cohort1",
- )
+ # shouldn't add to local eval requests
+ self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
- cohort_with_nested_invalid = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "$some_prop_1",
- "value": "something_1",
- "type": "person",
- },
- {
- "key": "id",
- "value": 99999,
- "type": "cohort",
- },
- {
- "key": "id",
- "value": deleted_cohort.pk,
- "type": "cohort",
- },
- {
- "key": "id",
- "value": cohort_from_other_team.pk,
- "type": "cohort",
- },
- ]
- },
- ],
- name="cohort1",
- )
+ self.client.logout()
+ # `local_evaluation` is called by logged out clients!
- cohort_valid = Cohort.objects.create(
- team=self.team,
- groups=[
+ with freeze_time("2022-05-07 12:23:07"):
+ # missing API key
+ response = self.client.get(f"/api/feature_flag?token={self.team.api_token}")
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
+
+ response = self.client.get(f"/api/feature_flag/")
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
+
+ response = self.client.get(
+ f"/api/feature_flag/?token={self.team.api_token}",
+ headers={"authorization": f"Bearer {personal_api_key}"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
+ {b"165192618": b"1"},
+ )
+
+ for _ in range(4):
+ response = self.client.get(
+ f"/api/feature_flag/?token={self.team.api_token}",
+ headers={"authorization": f"Bearer {personal_api_key}"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ self.assertEqual(
+ client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
+ {b"165192618": b"5"},
+ )
+
+ @parameterized.expand(
+ [
+ ("malformed_relative", "6hed", "is_date_before"),
+ ("malformed_absolute", "1234-02-993284", "is_date_after"),
+ ("malformed_exact", "not-a-date", "is_date_exact"),
+ ]
+ )
+ def test_create_flag_with_invalid_date(self, _name, invalid_date, operator):
+ resp = self._create_flag_with_properties(
+ "date-flag",
+ [
{
- "properties": [
- {
- "key": "$some_prop_1",
- "value": "something_1",
- "type": "person",
- },
- ]
- },
+ "key": "created_for",
+ "type": "person",
+ "value": invalid_date,
+ "operator": operator,
+ }
],
- name="cohort1",
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
- FeatureFlag.objects.create(
- team=self.team,
- filters={"groups": [{"properties": [{"key": "id", "value": 99999, "type": "cohort"}]}]},
- name="This is a cohort-based flag",
- key="cohort-flag",
- created_by=self.user,
- )
- FeatureFlag.objects.create(
- team=self.team,
- filters={
- "groups": [
- {
- "properties": [
- {
- "key": "id",
- "value": cohort_with_nested_invalid.pk,
- "type": "cohort",
- }
- ]
- }
- ]
- },
- name="This is a cohort-based flag",
- key="cohort-flag-2",
- created_by=self.user,
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "invalid_date",
+ "detail": f"Invalid date value: {invalid_date}",
+ "attr": "filters",
+ }.items(),
+ resp.json().items(),
)
- FeatureFlag.objects.create(
- team=self.team,
- filters={
- "groups": [
- {
- "properties": [
- {
- "key": "id",
- "value": cohort_from_other_team.pk,
- "type": "cohort",
- }
- ]
- }
- ]
- },
- name="This is a cohort-based flag",
- key="cohort-flag-3",
- created_by=self.user,
+
+ @parameterized.expand(
+ [
+ ("between", "between"),
+ ("not_between", "not_between"),
+ ("is_cleaned_path_exact", "is_cleaned_path_exact"),
+ ]
+ )
+ def test_cant_create_flag_with_unsupported_operator(self, _name, operator):
+ resp = self._create_flag_with_properties(
+ "unsupported-op-flag",
+ [{"key": "age", "type": "person", "value": "test", "operator": operator}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
- FeatureFlag.objects.create(
- team=self.team,
- filters={
- "groups": [
- {"properties": [{"key": "id", "value": cohort_valid.pk, "type": "cohort"}]},
- {
- "properties": [
- {
- "key": "id",
- "value": cohort_with_nested_invalid.pk,
- "type": "cohort",
- }
- ]
- },
- {"properties": [{"key": "id", "value": 99999, "type": "cohort"}]},
- {"properties": [{"key": "id", "value": deleted_cohort.pk, "type": "cohort"}]},
- ]
- },
- name="This is a cohort-based flag",
- key="cohort-flag-4",
- created_by=self.user,
+ self.assertEqual(resp.json()["code"], "unsupported_operator")
+ self.assertIn(operator, resp.json()["detail"])
+
+ @parameterized.expand(
+ [
+ ("between", "between"),
+ ("not_between", "not_between"),
+ ("is_cleaned_path_exact", "is_cleaned_path_exact"),
+ ]
+ )
+ def test_cant_update_flag_with_unsupported_operator(self, _name, operator):
+ flag = self._create_flag_with_properties(
+ f"flag-to-update-{_name}",
+ [{"key": "age", "type": "person", "value": "test", "operator": "exact"}],
)
- self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
+ resp = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.json()['id']}/",
{
- "name": "Alpha feature",
- "key": "alpha-feature",
"filters": {
"groups": [
- {
- "rollout_percentage": 100,
- "properties": [],
- }
- ],
- },
+ {"properties": [{"key": "age", "type": "person", "value": "test", "operator": operator}]}
+ ]
+ }
},
format="json",
)
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(resp.json()["code"], "unsupported_operator")
+ self.assertIn(operator, resp.json()["detail"])
- self.client.logout()
+ @parameterized.expand(
+ [
+ ("min_to_gte", "min", "gte"),
+ ("max_to_lte", "max", "lte"),
+ ]
+ )
+ def test_create_flag_aliases_operator(self, _name, input_op, saved_op):
+ resp = self._create_flag_with_properties(
+ f"alias-flag-{_name}",
+ [{"key": "age", "type": "person", "value": "10", "operator": input_op}],
+ )
+ saved_operator = resp.json()["filters"]["groups"][0]["properties"][0]["operator"]
+ self.assertEqual(saved_operator, saved_op)
- with self.assertNumQueries(FuzzyInt(12, 18)):
- # 1-10: Auth, team, project, membership, and access control queries
- # 11. SELECT surveys (for survey exclusion)
- # 12. SELECT all feature flags (with evaluation tags via ArrayAgg)
- # 13. SELECT cohorts (only loaded because a flag references a cohort)
- # 14. SELECT group type mapping
-
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_data = response.json()
- self.assertTrue("flags" in response_data and "group_type_mapping" in response_data)
- self.assertEqual(len(response_data["flags"]), 5)
- self.assertEqual(len(response_data["cohorts"]), 2)
- assert str(cohort_valid.pk) in response_data["cohorts"]
- assert str(cohort_with_nested_invalid.pk) in response_data["cohorts"]
-
- @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_local_evaluation_for_cohorts_with_variant_overrides(self, mock_report_user_action):
- FeatureFlag.objects.all().delete()
-
- cohort_valid_for_ff = Cohort.objects.create(
- team=self.team,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "$some_prop",
- "value": "nomatchihope",
- "type": "person",
- },
- ],
- }
- ],
- }
- },
- name="cohort1",
+ @parameterized.expand(
+ [
+ ("min_to_gte", "min", "gte"),
+ ("max_to_lte", "max", "lte"),
+ ]
+ )
+ def test_update_flag_aliases_operator(self, _name, input_op, saved_op):
+ flag = self._create_flag_with_properties(
+ f"flag-alias-update-{_name}",
+ [{"key": "age", "type": "person", "value": "5", "operator": "exact"}],
)
-
- self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
+ resp = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.json()['id']}/",
{
- "name": "Alpha feature",
- "key": "alpha-feature",
"filters": {
- "groups": [
- {
- "variant": "test",
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- "rollout_percentage": 100,
- },
- {
- "variant": "test",
- "properties": [
- {
- "key": "email",
- "type": "person",
- "value": "@posthog.com",
- "operator": "icontains",
- }
- ],
- "rollout_percentage": 100,
- },
- ],
- "multivariate": {
- "variants": [
- {"key": "control", "name": "", "rollout_percentage": 100},
- {"key": "test", "name": "", "rollout_percentage": 0},
- ]
- },
- },
+ "groups": [{"properties": [{"key": "age", "type": "person", "value": "10", "operator": input_op}]}]
+ }
},
format="json",
)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ saved_operator = resp.json()["filters"]["groups"][0]["properties"][0]["operator"]
+ self.assertEqual(saved_operator, saved_op)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ @parameterized.expand(
+ [
+ ("not_a_string", "semver_gt", 123),
+ ("list_value", "semver_eq", ["1.2.3"]),
+ ("invalid_format", "semver_lt", "not-semver"),
+ ("empty_string", "semver_gte", ""),
+ ("tilde_invalid", "semver_tilde", "abc"),
+ ("caret_invalid", "semver_caret", "x.y.z"),
+ ("wildcard_invalid", "semver_wildcard", ""),
+ ]
+ )
+ def test_create_flag_with_invalid_semver_value(self, _name, operator, value):
+ resp = self._create_flag_with_properties(
+ "semver-flag",
+ [{"key": "app_version", "type": "person", "value": value, "operator": operator}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
+ self.assertEqual(resp.json()["code"], "invalid_value")
- self.client.logout()
+ @parameterized.expand(
+ [
+ ("eq", "semver_eq", "1.2.3"),
+ ("neq", "semver_neq", "2.0.0"),
+ ("gt", "semver_gt", "1.0"),
+ ("gte", "semver_gte", "0.1.0"),
+ ("lt", "semver_lt", "10.20.30"),
+ ("lte", "semver_lte", "1.0.0"),
+ ("tilde", "semver_tilde", "1.2.3"),
+ ("tilde_bare_major", "semver_tilde", "1"),
+ ("caret", "semver_caret", "0.2.3"),
+ ("wildcard", "semver_wildcard", "1.2.*"),
+ ]
+ )
+ def test_create_flag_with_valid_semver_value(self, _name, operator, value):
+ self._create_flag_with_properties(
+ f"semver-flag-{_name}",
+ [{"key": "app_version", "type": "person", "value": value, "operator": operator}],
+ expected_status=status.HTTP_201_CREATED,
+ )
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ @parameterized.expand(
+ [
+ ("scalar_string", "icontains_multi", "just-a-string"),
+ ("integer", "not_icontains_multi", 42),
+ ]
+ )
+ def test_create_flag_with_invalid_multi_contains_value(self, _name, operator, value):
+ resp = self._create_flag_with_properties(
+ "multi-flag",
+ [{"key": "url", "type": "person", "value": value, "operator": operator}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+ self.assertEqual(resp.json()["code"], "invalid_value")
+ self.assertIn("requires a list", resp.json()["detail"])
+
+ @parameterized.expand(
+ [
+ ("icontains_multi_list", "icontains_multi", ["foo", "bar"]),
+ ("not_icontains_multi_list", "not_icontains_multi", ["baz"]),
+ ]
+ )
+ def test_create_flag_with_valid_multi_contains_value(self, _name, operator, value):
+ self._create_flag_with_properties(
+ f"multi-flag-{_name}",
+ [{"key": "url", "type": "person", "value": value, "operator": operator}],
+ expected_status=status.HTTP_201_CREATED,
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_data = response.json()
- self.assertTrue("flags" in response_data and "group_type_mapping" in response_data)
- self.assertEqual(len(response_data["flags"]), 1)
- sorted_flags = sorted(response_data["flags"], key=lambda x: x["key"])
+ def test_creating_feature_flag_with_non_existant_cohort(self):
+ cohort_request = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": 5151}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
self.assertLessEqual(
{
- "name": "Alpha feature",
- "key": "alpha-feature",
- "filters": {
- "groups": [
- {
- "variant": "test",
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- "rollout_percentage": 100,
- "aggregation_group_type_index": None,
- },
- {
- "variant": "test",
- "properties": [
- {
- "key": "email",
- "type": "person",
- "value": "@posthog.com",
- "operator": "icontains",
- }
- ],
- "rollout_percentage": 100,
- "aggregation_group_type_index": None,
- },
- ],
- "multivariate": {
- "variants": [
- {"key": "control", "name": "", "rollout_percentage": 100},
- {"key": "test", "name": "", "rollout_percentage": 0},
- ]
- },
- "aggregation_group_type_index": None,
- },
- "deleted": False,
- "active": True,
- "ensure_experience_continuity": False,
+ "type": "validation_error",
+ "code": "cohort_does_not_exist",
+ "detail": "Cohort with id 5151 does not exist",
+ "attr": "filters",
}.items(),
- sorted_flags[0].items(),
+ cohort_request.json().items(),
)
- @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_local_evaluation_for_static_cohorts(self, mock_report_user_action):
- FeatureFlag.objects.all().delete()
-
- cohort_valid_for_ff = Cohort.objects.create(
- team=self.team,
- is_static=True,
- name="cohort1",
+ def test_validation_payloads(self):
+ self._create_flag_with_properties(
+ "person-flag",
+ [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "@posthog.com",
+ "operator": "icontains",
+ }
+ ],
+ payloads={"true": 300},
+ expected_status=status.HTTP_201_CREATED,
+ )
+ self._create_flag_with_properties(
+ "person-flag",
+ [
+ {
+ "key": "email",
+ "type": "person",
+ "value": "@posthog.com",
+ "operator": "icontains",
+ }
+ ],
+ payloads={"some-fake-key": 300},
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
- self.client.post(
+ response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Alpha feature",
- "key": "alpha-feature",
+ "name": "Multivariate feature",
+ "key": "multivariate-feature",
"filters": {
- "groups": [
- {
- "rollout_percentage": 20,
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- }
- ],
+ "groups": [{"properties": [], "rollout_percentage": None}],
"multivariate": {
"variants": [
{
@@ -4535,45 +4449,20 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
},
]
},
+ "payloads": {"first-variant": {"some": "payload"}},
},
},
format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_data = response.json()
- self.assertTrue("flags" in response_data and "group_type_mapping" in response_data)
- self.assertEqual(len(response_data["flags"]), 1)
-
- sorted_flags = sorted(response_data["flags"], key=lambda x: x["key"])
-
- self.assertLessEqual(
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Alpha feature",
- "key": "alpha-feature",
+ "name": "Multivariate feature",
+ "key": "multivariate-feature",
"filters": {
- "groups": [
- {
- "rollout_percentage": 20,
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- "aggregation_group_type_index": None,
- }
- ],
+ "groups": [{"properties": [], "rollout_percentage": None}],
"multivariate": {
"variants": [
{
@@ -4593,96 +4482,23 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
},
]
},
- "aggregation_group_type_index": None,
+ "payloads": {
+ "first-variant": {"some": "payload"},
+ "fourth-variant": {"some": "payload"},
+ },
},
- "deleted": False,
- "active": True,
- "ensure_experience_continuity": False,
- }.items(),
- sorted_flags[0].items(),
- )
-
- self.assertEqual(
- response_data["cohorts"],
- {},
- )
-
- @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_local_evaluation_for_arbitrary_cohorts(self, mock_report_user_action):
- FeatureFlag.objects.all().delete()
-
- cohort_valid_for_ff = Cohort.objects.create(
- team=self.team,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "OR",
- "values": [
- {
- "key": "$some_prop",
- "value": "nomatchihope",
- "type": "person",
- },
- {
- "key": "$some_prop2",
- "value": "nomatchihope2",
- "type": "person",
- },
- ],
- }
- ],
- }
- },
- name="cohort1",
- )
-
- cohort2 = Cohort.objects.create(
- team=self.team,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "OR",
- "values": [
- {
- "key": "$some_prop",
- "value": "nomatchihope",
- "type": "person",
- },
- {
- "key": "$some_prop2",
- "value": "nomatchihope2",
- "type": "person",
- },
- {
- "key": "id",
- "value": cohort_valid_for_ff.pk,
- "type": "cohort",
- "negation": True,
- },
- ],
- }
- ],
- }
},
- name="cohort2",
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.client.post(
+ response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Alpha feature",
- "key": "alpha-feature",
+ "name": "Multivariate feature",
+ "key": "multivariate-feature",
"filters": {
- "groups": [
- {
- "rollout_percentage": 20,
- "properties": [{"key": "id", "type": "cohort", "value": cohort2.pk}],
- }
- ],
+ "groups": [{"properties": [], "rollout_percentage": None}],
"multivariate": {
"variants": [
{
@@ -4702,330 +4518,188 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
},
]
},
+ "payloads": {"first-variant": {"some": "payload"}, "true": 2500},
},
},
format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Alpha feature",
- "key": "alpha-feature-2",
- "filters": {
- "groups": [
- {
- "rollout_percentage": 20,
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- }
- ],
- },
- },
- format="json",
+ valid_json_payload = self._create_flag_with_properties(
+ "json-flag",
+ [{"key": "key", "value": "value", "type": "person"}],
+ payloads={"true": json.dumps({"key": "value"})},
+ expected_status=status.HTTP_201_CREATED,
)
+ self.assertEqual(valid_json_payload.status_code, status.HTTP_201_CREATED)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ invalid_json_payload = self._create_flag_with_properties(
+ "invalid-json-flag",
+ [{"key": "key", "value": "value", "type": "person"}],
+ payloads={"true": "{invalid_json}"},
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
+ self.assertEqual(invalid_json_payload.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(invalid_json_payload.json()["detail"], "Payload value is not valid JSON")
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ non_string_payload = self._create_flag_with_properties(
+ "non-string-json-flag",
+ [{"key": "key", "value": "value", "type": "person"}],
+ payloads={"true": {"key": "value"}},
+ expected_status=status.HTTP_201_CREATED,
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_data = response.json()
- self.assertTrue(
- "flags" in response_data and "group_type_mapping" in response_data and "cohorts" in response_data
+ self.assertEqual(non_string_payload.status_code, status.HTTP_201_CREATED)
+ # Object payloads should be normalized to JSON strings
+ stored_payload = non_string_payload.json()["filters"]["payloads"]["true"]
+ self.assertIsInstance(stored_payload, str)
+ self.assertEqual(json.loads(stored_payload), {"key": "value"})
+
+ # Other valid JSON types (number, boolean, null, array) should be accepted
+ number_payload = self._create_flag_with_properties(
+ "number-payload-flag",
+ [{"key": "key", "value": "value", "type": "person"}],
+ payloads={"true": 42},
+ expected_status=status.HTTP_201_CREATED,
)
- self.assertEqual(len(response_data["flags"]), 2)
+ self.assertEqual(number_payload.status_code, status.HTTP_201_CREATED)
- sorted_flags = sorted(response_data["flags"], key=lambda x: x["key"])
+ boolean_payload = self._create_flag_with_properties(
+ "boolean-payload-flag",
+ [{"key": "key", "value": "value", "type": "person"}],
+ payloads={"true": True},
+ expected_status=status.HTTP_201_CREATED,
+ )
+ self.assertEqual(boolean_payload.status_code, status.HTTP_201_CREATED)
- self.assertEqual(
- response_data["cohorts"],
- {
- str(cohort_valid_for_ff.pk): {
- "type": "OR",
+ def test_creating_feature_flag_with_behavioral_cohort(self):
+ cohort_valid_for_ff = Cohort.objects.create(
+ team=self.team,
+ groups=[{"properties": [{"key": "$some_prop", "value": "nomatchihope", "type": "person"}]}],
+ name="cohort1",
+ )
+
+ cohort_not_valid_for_ff = Cohort.objects.create(
+ team=self.team,
+ filters={
+ "properties": {
+ "type": "AND",
"values": [
{
- "type": "OR",
- "values": [
- {
- "key": "$some_prop",
- "type": "person",
- "value": "nomatchihope",
- },
- {
- "key": "$some_prop2",
- "type": "person",
- "value": "nomatchihope2",
- },
- ],
- }
+ "key": "$pageview",
+ "event_type": "events",
+ "time_value": 2,
+ "time_interval": "week",
+ "value": "performed_event_first_time",
+ "type": "behavioral",
+ },
+ {"key": "email", "value": "[email protected]", "type": "person"},
],
- },
- str(cohort2.pk): {
- "type": "OR",
- "values": [
+ }
+ },
+ name="cohort2",
+ )
+
+ cohort_request = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort_not_valid_for_ff.id}],
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
+ "attr": "filters",
+ }.items(),
+ cohort_request.json().items(),
+ )
+
+ cohort_request = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort_valid_for_ff.id}],
+ expected_status=status.HTTP_201_CREATED,
+ )
+ flag_id = cohort_request.json()["id"]
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
+ {
+ "name": "Updated name",
+ "filters": {
+ "groups": [
{
- "type": "OR",
- "values": [
- {
- "key": "$some_prop",
- "type": "person",
- "value": "nomatchihope",
- },
- {
- "key": "$some_prop2",
- "type": "person",
- "value": "nomatchihope2",
- },
+ "rollout_percentage": 65,
+ "properties": [
{
"key": "id",
"type": "cohort",
- "value": cohort_valid_for_ff.pk,
- "negation": True,
- },
+ "value": cohort_not_valid_for_ff.id,
+ }
],
}
- ],
+ ]
},
},
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
self.assertLessEqual(
{
- "name": "Alpha feature",
- "key": "alpha-feature",
- "filters": {
- "groups": [
- {
- "rollout_percentage": 20,
- "properties": [{"key": "id", "type": "cohort", "value": cohort2.pk}],
- "aggregation_group_type_index": None,
- }
- ],
- "multivariate": {
- "variants": [
- {
- "key": "first-variant",
- "name": "First Variant",
- "rollout_percentage": 50,
- },
- {
- "key": "second-variant",
- "name": "Second Variant",
- "rollout_percentage": 25,
- },
- {
- "key": "third-variant",
- "name": "Third Variant",
- "rollout_percentage": 25,
- },
- ]
- },
- "aggregation_group_type_index": None,
- },
- "deleted": False,
- "active": True,
- "ensure_experience_continuity": False,
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
+ "attr": "filters",
}.items(),
- sorted_flags[0].items(),
+ response.json().items(),
)
- self.assertLessEqual(
- {
- "name": "Alpha feature",
- "key": "alpha-feature-2",
- "filters": {
- "groups": [
+ def test_creating_feature_flag_with_nested_behavioral_cohort(self):
+ cohort_not_valid_for_ff = Cohort.objects.create(
+ team=self.team,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
{
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_valid_for_ff.pk,
- }
- ],
- "rollout_percentage": 20,
- "aggregation_group_type_index": None,
+ "key": "$pageview",
+ "event_type": "events",
+ "time_value": 2,
+ "time_interval": "week",
+ "value": "performed_event_first_time",
+ "type": "behavioral",
},
+ {"key": "email", "value": "[email protected]", "type": "person"},
],
- "aggregation_group_type_index": None,
- },
- "deleted": False,
- "active": True,
- "ensure_experience_continuity": False,
- }.items(),
- sorted_flags[1].items(),
- )
-
- @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
- def test_local_evaluation_billing_analytics(self):
- FeatureFlag.objects.all().delete()
-
- # old style feature flags
- FeatureFlag.objects.create(
- name="Beta feature",
- key="beta-feature",
- team=self.team,
- filters={"properties": [{"key": "beta-property", "value": "beta-value"}]},
- created_by=self.user,
- )
- # and inactive flag
- FeatureFlag.objects.create(
- name="Inactive feature",
- key="inactive-flag",
- team=self.team,
- active=False,
- filters={"properties": []},
- created_by=self.user,
- )
-
- client = redis.get_client()
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ }
+ },
+ name="cohort-behavioural",
)
- self.client.logout()
- # `local_evaluation` is called by logged out clients!
-
- with freeze_time("2022-05-07 12:23:07"):
- # missing API key
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
-
- response = self.client.get(f"/api/feature_flag/local_evaluation")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
-
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
- {b"165192618": b"1"},
- )
-
- for _ in range(5):
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- self.assertEqual(
- client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
- {b"165192618": b"6"},
- )
-
- @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
- def test_local_evaluation_billing_analytics_for_regular_feature_flag_list(self):
- FeatureFlag.objects.all().delete()
-
- # old style feature flags
- FeatureFlag.objects.create(
- name="Beta feature",
- key="beta-feature",
- team=self.team,
- filters={"properties": [{"key": "beta-property", "value": "beta-value"}]},
- created_by=self.user,
- )
- # and inactive flag
- FeatureFlag.objects.create(
- name="Inactive feature",
- key="inactive-flag",
+ nested_cohort_not_valid_for_ff = Cohort.objects.create(
team=self.team,
- active=False,
- filters={"properties": []},
- created_by=self.user,
- )
-
- client = redis.get_client()
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ groups=[
+ {
+ "properties": [
+ {
+ "key": "id",
+ "value": cohort_not_valid_for_ff.pk,
+ "type": "cohort",
+ }
+ ]
+ }
+ ],
+ name="cohort-not-behavioural",
)
- # request made while logged in, via client cookie auth
- response = self.client.get(f"/api/feature_flag?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["count"], 2)
-
- # shouldn't add to local eval requests
- self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
-
- self.client.logout()
- # `local_evaluation` is called by logged out clients!
-
- with freeze_time("2022-05-07 12:23:07"):
- # missing API key
- response = self.client.get(f"/api/feature_flag?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
-
- response = self.client.get(f"/api/feature_flag/")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"), {})
-
- response = self.client.get(
- f"/api/feature_flag/?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
- {b"165192618": b"1"},
- )
-
- for _ in range(4):
- response = self.client.get(
- f"/api/feature_flag/?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # local evaluation still works
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- self.assertEqual(
- client.hgetall(f"posthog:local_evaluation_requests:{self.team.pk}"),
- {b"165192618": b"6"},
- )
-
- @parameterized.expand(
- [
- ("malformed_relative", "6hed", "is_date_before"),
- ("malformed_absolute", "1234-02-993284", "is_date_after"),
- ("malformed_exact", "not-a-date", "is_date_exact"),
- ]
- )
- def test_create_flag_with_invalid_date(self, _name, invalid_date, operator):
- resp = self._create_flag_with_properties(
- "date-flag",
+ cohort_request = self._create_flag_with_properties(
+ "cohort-flag",
[
{
- "key": "created_for",
- "type": "person",
- "value": invalid_date,
- "operator": operator,
+ "key": "id",
+ "type": "cohort",
+ "value": nested_cohort_not_valid_for_ff.id,
}
],
expected_status=status.HTTP_400_BAD_REQUEST,
@@ -5034,194 +4708,153 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertLessEqual(
{
"type": "validation_error",
- "code": "invalid_date",
- "detail": f"Invalid date value: {invalid_date}",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
"attr": "filters",
}.items(),
- resp.json().items(),
+ cohort_request.json().items(),
)
- @parameterized.expand(
- [
- ("between", "between"),
- ("not_between", "not_between"),
- ("is_cleaned_path_exact", "is_cleaned_path_exact"),
- ]
- )
- def test_cant_create_flag_with_unsupported_operator(self, _name, operator):
- resp = self._create_flag_with_properties(
- "unsupported-op-flag",
- [{"key": "age", "type": "person", "value": "test", "operator": operator}],
+ cohort_request = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort_not_valid_for_ff.id}],
expected_status=status.HTTP_400_BAD_REQUEST,
)
- self.assertEqual(resp.json()["code"], "unsupported_operator")
- self.assertIn(operator, resp.json()["detail"])
+
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "behavioral_cohort_found",
+ "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
+ "attr": "filters",
+ }.items(),
+ cohort_request.json().items(),
+ )
@parameterized.expand(
[
- ("between", "between"),
- ("not_between", "not_between"),
- ("is_cleaned_path_exact", "is_cleaned_path_exact"),
- ]
- )
- def test_cant_update_flag_with_unsupported_operator(self, _name, operator):
- flag = self._create_flag_with_properties(
- f"flag-to-update-{_name}",
- [{"key": "age", "type": "person", "value": "test", "operator": "exact"}],
- )
- resp = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag.json()['id']}/",
- {
- "filters": {
- "groups": [
- {"properties": [{"key": "age", "type": "person", "value": "test", "operator": operator}]}
- ]
- }
- },
- format="json",
- )
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(resp.json()["code"], "unsupported_operator")
- self.assertIn(operator, resp.json()["detail"])
-
- @parameterized.expand(
- [
- ("min_to_gte", "min", "gte"),
- ("max_to_lte", "max", "lte"),
+ (
+ "realtime_backfilled_flag_on",
+ CohortType.REALTIME,
+ True,
+ True,
+ status.HTTP_201_CREATED,
+ None,
+ ),
+ (
+ "realtime_not_backfilled_flag_on",
+ CohortType.REALTIME,
+ False,
+ True,
+ status.HTTP_400_BAD_REQUEST,
+ "is still being backfilled",
+ ),
+ (
+ "non_realtime_flag_on",
+ None,
+ False,
+ True,
+ status.HTTP_400_BAD_REQUEST,
+ "filters on events",
+ ),
+ (
+ "realtime_backfilled_flag_off",
+ CohortType.REALTIME,
+ True,
+ False,
+ status.HTTP_400_BAD_REQUEST,
+ "filters on events",
+ ),
]
)
- def test_create_flag_aliases_operator(self, _name, input_op, saved_op):
- resp = self._create_flag_with_properties(
- f"alias-flag-{_name}",
- [{"key": "age", "type": "person", "value": "10", "operator": input_op}],
- )
- saved_operator = resp.json()["filters"]["groups"][0]["properties"][0]["operator"]
- self.assertEqual(saved_operator, saved_op)
+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
+ def test_behavioral_cohort_flag_validation(
+ self,
+ _name,
+ cohort_type,
+ is_backfilled,
+ flag_enabled,
+ expected_status,
+ expected_detail_fragment,
+ mock_feature_enabled,
+ ):
+ mock_feature_enabled.return_value = flag_enabled
- @parameterized.expand(
- [
- ("min_to_gte", "min", "gte"),
- ("max_to_lte", "max", "lte"),
- ]
- )
- def test_update_flag_aliases_operator(self, _name, input_op, saved_op):
- flag = self._create_flag_with_properties(
- f"flag-alias-update-{_name}",
- [{"key": "age", "type": "person", "value": "5", "operator": "exact"}],
- )
- resp = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag.json()['id']}/",
- {
- "filters": {
- "groups": [{"properties": [{"key": "age", "type": "person", "value": "10", "operator": input_op}]}]
+ cohort_kwargs: dict[str, Any] = {
+ "team": self.team,
+ "name": "test-cohort",
+ "filters": {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$pageview",
+ "event_type": "events",
+ "time_value": 2,
+ "time_interval": "week",
+ "value": "performed_event_first_time",
+ "type": "behavioral",
+ },
+ ],
}
},
- format="json",
- )
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
- saved_operator = resp.json()["filters"]["groups"][0]["properties"][0]["operator"]
- self.assertEqual(saved_operator, saved_op)
+ }
+ if cohort_type is not None:
+ cohort_kwargs["cohort_type"] = cohort_type
+ if is_backfilled:
+ cohort_kwargs["last_backfill_person_properties_at"] = datetime.now(tz=UTC)
- @parameterized.expand(
- [
- ("not_a_string", "semver_gt", 123),
- ("list_value", "semver_eq", ["1.2.3"]),
- ("invalid_format", "semver_lt", "not-semver"),
- ("empty_string", "semver_gte", ""),
- ("tilde_invalid", "semver_tilde", "abc"),
- ("caret_invalid", "semver_caret", "x.y.z"),
- ("wildcard_invalid", "semver_wildcard", ""),
- ]
- )
- def test_create_flag_with_invalid_semver_value(self, _name, operator, value):
- resp = self._create_flag_with_properties(
- "semver-flag",
- [{"key": "app_version", "type": "person", "value": value, "operator": operator}],
- expected_status=status.HTTP_400_BAD_REQUEST,
- )
- self.assertEqual(resp.json()["code"], "invalid_value")
+ cohort = Cohort.objects.create(**cohort_kwargs)
- @parameterized.expand(
- [
- ("eq", "semver_eq", "1.2.3"),
- ("neq", "semver_neq", "2.0.0"),
- ("gt", "semver_gt", "1.0"),
- ("gte", "semver_gte", "0.1.0"),
- ("lt", "semver_lt", "10.20.30"),
- ("lte", "semver_lte", "1.0.0"),
- ("tilde", "semver_tilde", "1.2.3"),
- ("tilde_bare_major", "semver_tilde", "1"),
- ("caret", "semver_caret", "0.2.3"),
- ("wildcard", "semver_wildcard", "1.2.*"),
- ]
- )
- def test_create_flag_with_valid_semver_value(self, _name, operator, value):
- self._create_flag_with_properties(
- f"semver-flag-{_name}",
- [{"key": "app_version", "type": "person", "value": value, "operator": operator}],
- expected_status=status.HTTP_201_CREATED,
+ response = self._create_flag_with_properties(
+ "cohort-flag",
+ [{"key": "id", "type": "cohort", "value": cohort.id}],
+ expected_status=expected_status,
)
+ self.assertEqual(response.status_code, expected_status)
- @parameterized.expand(
- [
- ("scalar_string", "icontains_multi", "just-a-string"),
- ("integer", "not_icontains_multi", 42),
- ]
- )
- def test_create_flag_with_invalid_multi_contains_value(self, _name, operator, value):
- resp = self._create_flag_with_properties(
- "multi-flag",
- [{"key": "url", "type": "person", "value": value, "operator": operator}],
- expected_status=status.HTTP_400_BAD_REQUEST,
- )
- self.assertEqual(resp.json()["code"], "invalid_value")
- self.assertIn("requires a list", resp.json()["detail"])
+ if expected_detail_fragment is not None:
+ self.assertIn(expected_detail_fragment, response.json()["detail"])
- @parameterized.expand(
- [
- ("icontains_multi_list", "icontains_multi", ["foo", "bar"]),
- ("not_icontains_multi_list", "not_icontains_multi", ["baz"]),
- ]
- )
- def test_create_flag_with_valid_multi_contains_value(self, _name, operator, value):
- self._create_flag_with_properties(
- f"multi-flag-{_name}",
- [{"key": "url", "type": "person", "value": value, "operator": operator}],
- expected_status=status.HTTP_201_CREATED,
+ def test_validation_group_properties(self):
+ groups_request = self._create_flag_with_properties(
+ "groups-flag",
+ [
+ {
+ "key": "industry",
+ "value": "finance",
+ "type": "group",
+ "group_type_index": 0,
+ }
+ ],
+ aggregation_group_type_index=0,
)
+ self.assertEqual(groups_request.status_code, status.HTTP_201_CREATED)
- def test_creating_feature_flag_with_non_existant_cohort(self):
- cohort_request = self._create_flag_with_properties(
- "cohort-flag",
- [{"key": "id", "type": "cohort", "value": 5151}],
+ illegal_groups_request = self._create_flag_with_properties(
+ "illegal-groups-flag",
+ [
+ {
+ "key": "industry",
+ "value": "finance",
+ "type": "group",
+ "group_type_index": 0,
+ }
+ ],
+ aggregation_group_type_index=3,
expected_status=status.HTTP_400_BAD_REQUEST,
)
-
- self.assertLessEqual(
+ self.assertEqual(
+ illegal_groups_request.json(),
{
"type": "validation_error",
- "code": "cohort_does_not_exist",
- "detail": "Cohort with id 5151 does not exist",
+ "code": "invalid_input",
+ "detail": "Filters are not valid (group properties must match the condition set's group type)",
"attr": "filters",
- }.items(),
- cohort_request.json().items(),
+ },
)
- def test_validation_payloads(self):
- self._create_flag_with_properties(
- "person-flag",
- [
- {
- "key": "email",
- "type": "person",
- "value": "@posthog.com",
- "operator": "icontains",
- }
- ],
- payloads={"true": 300},
- expected_status=status.HTTP_201_CREATED,
- )
- self._create_flag_with_properties(
+ person_request = self._create_flag_with_properties(
"person-flag",
[
{
@@ -5231,1260 +4864,815 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
"operator": "icontains",
}
],
- payloads={"some-fake-key": 300},
+ aggregation_group_type_index=0,
expected_status=status.HTTP_400_BAD_REQUEST,
)
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
+ self.assertEqual(
+ person_request.json(),
{
- "name": "Multivariate feature",
- "key": "multivariate-feature",
- "filters": {
- "groups": [{"properties": [], "rollout_percentage": None}],
- "multivariate": {
- "variants": [
- {
- "key": "first-variant",
- "name": "First Variant",
- "rollout_percentage": 50,
- },
- {
- "key": "second-variant",
- "name": "Second Variant",
- "rollout_percentage": 25,
- },
- {
- "key": "third-variant",
- "name": "Third Variant",
- "rollout_percentage": 25,
- },
- ]
- },
- "payloads": {"first-variant": {"some": "payload"}},
- },
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "Filters are not valid (group-aggregated conditions can only use group properties)",
+ "attr": "filters",
},
- format="json",
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ @parameterized.expand(
+ [
+ (
+ "flag_enabled",
+ True,
+ status.HTTP_201_CREATED,
+ ),
+ (
+ "flag_disabled",
+ False,
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
+ def test_mixed_aggregation_types_across_condition_sets(
+ self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled
+ ):
+ mock_feature_enabled.return_value = mixed_targeting_enabled
+
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
+ )
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Multivariate feature",
- "key": "multivariate-feature",
+ "name": "Mixed aggregation flag",
+ "key": "mixed-aggregation-flag",
"filters": {
- "groups": [{"properties": [], "rollout_percentage": None}],
- "multivariate": {
- "variants": [
- {
- "key": "first-variant",
- "name": "First Variant",
- "rollout_percentage": 50,
- },
- {
- "key": "second-variant",
- "name": "Second Variant",
- "rollout_percentage": 25,
- },
- {
- "key": "third-variant",
- "name": "Third Variant",
- "rollout_percentage": 25,
- },
- ]
- },
- "payloads": {
- "first-variant": {"some": "payload"},
- "fourth-variant": {"some": "payload"},
- },
+ "groups": [
+ {
+ "properties": [],
+ "rollout_percentage": 50,
+ "aggregation_group_type_index": None, # Person aggregation
+ },
+ {
+ "properties": [],
+ "rollout_percentage": 50,
+ "aggregation_group_type_index": 0, # Group aggregation
+ },
+ ]
},
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.status_code, expected_status)
- response = self.client.post(
+ if expected_status == status.HTTP_201_CREATED:
+ # Flag-level aggregation is None when condition sets have mixed aggregation types
+ self.assertIsNone(response.json()["filters"]["aggregation_group_type_index"])
+ # Each condition set retains its own aggregation type
+ groups = response.json()["filters"]["groups"]
+ self.assertIsNone(groups[0]["aggregation_group_type_index"])
+ self.assertEqual(groups[1]["aggregation_group_type_index"], 0)
+ else:
+ self.assertIn("Mixed aggregation types", response.json()["detail"])
+
+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
+ def test_mixed_aggregation_round_trip(self, mock_feature_enabled):
+ mock_feature_enabled.return_value = True
+
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
+ )
+
+ create_response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Multivariate feature",
- "key": "multivariate-feature",
+ "name": "Round-trip flag",
+ "key": "round-trip-mixed",
"filters": {
- "groups": [{"properties": [], "rollout_percentage": None}],
- "multivariate": {
- "variants": [
- {
- "key": "first-variant",
- "name": "First Variant",
- "rollout_percentage": 50,
- },
- {
- "key": "second-variant",
- "name": "Second Variant",
- "rollout_percentage": 25,
- },
- {
- "key": "third-variant",
- "name": "Third Variant",
- "rollout_percentage": 25,
- },
- ]
- },
- "payloads": {"first-variant": {"some": "payload"}, "true": 2500},
+ "groups": [
+ {"properties": [], "rollout_percentage": 50, "aggregation_group_type_index": None},
+ {"properties": [], "rollout_percentage": 75, "aggregation_group_type_index": 0},
+ ]
},
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
- valid_json_payload = self._create_flag_with_properties(
- "json-flag",
- [{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": json.dumps({"key": "value"})},
- expected_status=status.HTTP_201_CREATED,
- )
- self.assertEqual(valid_json_payload.status_code, status.HTTP_201_CREATED)
+ get_response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{create_response.json()['id']}/")
+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)
+ filters = get_response.json()["filters"]
+ self.assertIsNone(filters["aggregation_group_type_index"])
+ self.assertIsNone(filters["groups"][0]["aggregation_group_type_index"])
+ self.assertEqual(filters["groups"][1]["aggregation_group_type_index"], 0)
- invalid_json_payload = self._create_flag_with_properties(
- "invalid-json-flag",
- [{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": "{invalid_json}"},
- expected_status=status.HTTP_400_BAD_REQUEST,
- )
- self.assertEqual(invalid_json_payload.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(invalid_json_payload.json()["detail"], "Payload value is not valid JSON")
+ @parameterized.expand(
+ [
+ ("flag_enabled", True, status.HTTP_201_CREATED),
+ ("flag_disabled", False, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
+ def test_mixed_aggregation_with_properties(
+ self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled
+ ):
+ mock_feature_enabled.return_value = mixed_targeting_enabled
- non_string_payload = self._create_flag_with_properties(
- "non-string-json-flag",
- [{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": {"key": "value"}},
- expected_status=status.HTTP_201_CREATED,
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
)
- self.assertEqual(non_string_payload.status_code, status.HTTP_201_CREATED)
- # Object payloads should be normalized to JSON strings
- stored_payload = non_string_payload.json()["filters"]["payloads"]["true"]
- self.assertIsInstance(stored_payload, str)
- self.assertEqual(json.loads(stored_payload), {"key": "value"})
- # Other valid JSON types (number, boolean, null, array) should be accepted
- number_payload = self._create_flag_with_properties(
- "number-payload-flag",
- [{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": 42},
- expected_status=status.HTTP_201_CREATED,
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Mixed flag with properties",
+ "key": "mixed-with-props",
+ "filters": {
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "value": ["[email protected]"], "operator": "exact", "type": "person"}
+ ],
+ "rollout_percentage": 100,
+ "aggregation_group_type_index": None,
+ },
+ {
+ "properties": [
+ {
+ "key": "created_at",
+ "value": "2026-03-10",
+ "operator": "is_date_after",
+ "type": "group",
+ "group_type_index": 0,
+ }
+ ],
+ "rollout_percentage": 100,
+ "aggregation_group_type_index": 0,
+ },
+ ]
+ },
+ },
+ format="json",
)
- self.assertEqual(number_payload.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.status_code, expected_status)
- boolean_payload = self._create_flag_with_properties(
- "boolean-payload-flag",
- [{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": True},
- expected_status=status.HTTP_201_CREATED,
- )
- self.assertEqual(boolean_payload.status_code, status.HTTP_201_CREATED)
+ if expected_status == status.HTTP_201_CREATED:
+ groups = response.json()["filters"]["groups"]
+ self.assertIsNone(groups[0]["aggregation_group_type_index"])
+ self.assertEqual(groups[1]["aggregation_group_type_index"], 0)
+ else:
+ self.assertIn("Mixed aggregation types", response.json()["detail"])
- def test_creating_feature_flag_with_behavioral_cohort(self):
- cohort_valid_for_ff = Cohort.objects.create(
- team=self.team,
- groups=[{"properties": [{"key": "$some_prop", "value": "nomatchihope", "type": "person"}]}],
- name="cohort1",
+ @parameterized.expand(
+ [
+ ("flag_enabled", True, status.HTTP_200_OK),
+ ("flag_disabled", False, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
+ def test_patch_uniform_flag_to_mixed(self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled):
+ mock_feature_enabled.return_value = mixed_targeting_enabled
+
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
)
- cohort_not_valid_for_ff = Cohort.objects.create(
+ # Create a uniform person-aggregated flag (no feature flag check needed for uniform)
+ flag = FeatureFlag.objects.create(
team=self.team,
+ key="uniform-to-mixed",
+ name="Uniform flag",
filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 2,
- "time_interval": "week",
- "value": "performed_event_first_time",
- "type": "behavioral",
- },
- {"key": "email", "value": "[email protected]", "type": "person"},
- ],
+ "groups": [
+ {"properties": [], "rollout_percentage": 100, "aggregation_group_type_index": None},
+ ]
+ },
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ {
+ "filters": {
+ "groups": [
+ {"properties": [], "rollout_percentage": 50, "aggregation_group_type_index": None},
+ {"properties": [], "rollout_percentage": 75, "aggregation_group_type_index": 0},
+ ]
}
},
- name="cohort2",
+ format="json",
)
+ self.assertEqual(response.status_code, expected_status)
- cohort_request = self._create_flag_with_properties(
- "cohort-flag",
- [{"key": "id", "type": "cohort", "value": cohort_not_valid_for_ff.id}],
- expected_status=status.HTTP_400_BAD_REQUEST,
+ def test_per_condition_aggregation_normalization(self):
+ """Test that flag-level aggregation is distributed to condition sets without one"""
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
)
- self.assertLessEqual(
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
{
- "type": "validation_error",
- "code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
- "attr": "filters",
- }.items(),
- cohort_request.json().items(),
+ "name": "Normalized aggregation flag",
+ "key": "normalized-aggregation-flag",
+ "filters": {
+ "aggregation_group_type_index": 0,
+ "groups": [
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ },
+ },
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ result = response.json()
+ # Flag-level should be preserved
+ self.assertEqual(result["filters"]["aggregation_group_type_index"], 0)
+ # Condition set should have inherited the flag-level value
+ self.assertEqual(result["filters"]["groups"][0]["aggregation_group_type_index"], 0)
- cohort_request = self._create_flag_with_properties(
- "cohort-flag",
- [{"key": "id", "type": "cohort", "value": cohort_valid_for_ff.id}],
- expected_status=status.HTTP_201_CREATED,
+ def test_per_condition_aggregation_roundtrip(self):
+ """Test that per-condition aggregation values persist through create/read"""
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
)
- flag_id = cohort_request.json()["id"]
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
+
+ # Create with explicit per-condition value
+ create_response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
{
- "name": "Updated name",
+ "name": "Per-condition aggregation flag",
+ "key": "per-condition-aggregation-flag",
"filters": {
"groups": [
{
- "rollout_percentage": 65,
- "properties": [
- {
- "key": "id",
- "type": "cohort",
- "value": cohort_not_valid_for_ff.id,
- }
- ],
- }
- ]
+ "properties": [],
+ "rollout_percentage": 100,
+ "aggregation_group_type_index": 0,
+ },
+ ],
},
},
format="json",
)
+ self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
+ flag_id = create_response.json()["id"]
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ # Read it back
+ get_response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/")
+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)
+ result = get_response.json()
- self.assertLessEqual(
+ # Both flag-level and condition-level should be present and consistent
+ self.assertEqual(result["filters"]["aggregation_group_type_index"], 0)
+ self.assertEqual(result["filters"]["groups"][0]["aggregation_group_type_index"], 0)
+
+ def test_validation_empty_groups(self):
+ """Test that creating a flag with empty groups raises validation error"""
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Empty groups flag",
+ "key": "empty-groups-flag",
+ "filters": {"groups": []},
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
{
"type": "validation_error",
- "code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort2' with filters on events cannot be used in feature flags.",
+ "code": "invalid_input",
+ "detail": "Feature flags must have at least one condition set (group).",
"attr": "filters",
- }.items(),
- response.json().items(),
- )
-
- def test_creating_feature_flag_with_nested_behavioral_cohort(self):
- cohort_not_valid_for_ff = Cohort.objects.create(
- team=self.team,
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 2,
- "time_interval": "week",
- "value": "performed_event_first_time",
- "type": "behavioral",
- },
- {"key": "email", "value": "[email protected]", "type": "person"},
- ],
- }
},
- name="cohort-behavioural",
)
- nested_cohort_not_valid_for_ff = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "id",
- "value": cohort_not_valid_for_ff.pk,
- "type": "cohort",
- }
- ]
- }
- ],
- name="cohort-not-behavioural",
+ def test_create_without_filters_persists_groups_invariant(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"name": "No filters flag", "key": "no-filters-flag"},
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ instance = FeatureFlag.objects.get(id=response.json()["id"])
+ self.assertEqual(instance.filters, {"groups": []})
- cohort_request = self._create_flag_with_properties(
- "cohort-flag",
- [
- {
- "key": "id",
- "type": "cohort",
- "value": nested_cohort_not_valid_for_ff.id,
- }
- ],
- expected_status=status.HTTP_400_BAD_REQUEST,
+ def test_validation_groups_with_empty_properties_allowed(self):
+ """Test that creating a flag with groups having empty properties but valid rollout is allowed"""
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Valid flag with empty properties",
+ "key": "valid-empty-properties",
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},
+ },
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertLessEqual(
- {
- "type": "validation_error",
- "code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
- "attr": "filters",
- }.items(),
- cohort_request.json().items(),
+ def test_validation_empty_groups_allowed_on_update(self):
+ """Test that updating an existing flag with empty groups is allowed (for scheduled changes)"""
+ # First create a valid flag
+ flag = FeatureFlag.objects.create(
+ name="Test flag",
+ key="test-flag-update",
+ team=self.team,
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- cohort_request = self._create_flag_with_properties(
- "cohort-flag",
- [{"key": "id", "type": "cohort", "value": cohort_not_valid_for_ff.id}],
- expected_status=status.HTTP_400_BAD_REQUEST,
+ # Now try to update it with empty groups (this should be allowed)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ {"filters": {"groups": []}},
+ format="json",
)
+ # Should succeed since it's an update, not creation
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertLessEqual(
+ @parameterized.expand(
+ [
+ # name, bucketing_identifier, ensure_experience_continuity, expected_status
+ ("device_with_persist_blocked", "device_id", True, status.HTTP_400_BAD_REQUEST),
+ ("device_without_persist_allowed", "device_id", False, status.HTTP_201_CREATED),
+ ]
+ )
+ def test_validation_device_bucketing_create(
+ self, _name: str, bucketing_identifier: str, ensure_experience_continuity: bool, expected_status: int
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
{
- "type": "validation_error",
- "code": "behavioral_cohort_found",
- "detail": "Cohort 'cohort-behavioural' with filters on events cannot be used in feature flags.",
- "attr": "filters",
- }.items(),
- cohort_request.json().items(),
+ "name": f"Device bucketing {_name}",
+ "key": f"device-{_name.replace('_', '-')}-flag",
+ "bucketing_identifier": bucketing_identifier,
+ "ensure_experience_continuity": ensure_experience_continuity,
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
+ },
+ format="json",
)
+ self.assertEqual(response.status_code, expected_status)
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
@parameterized.expand(
[
+ # name, initial_persist, patch_payload, expected_status
(
- "realtime_backfilled_flag_on",
- CohortType.REALTIME,
- True,
+ "grandfathered_combination_can_save",
True,
- status.HTTP_201_CREATED,
- None,
- ),
- (
- "realtime_not_backfilled_flag_on",
- CohortType.REALTIME,
- False,
- True,
- status.HTTP_400_BAD_REQUEST,
- "is still being backfilled",
- ),
- (
- "non_realtime_flag_on",
- None,
- False,
- True,
- status.HTTP_400_BAD_REQUEST,
- "filters on events",
+ {"name": "Updated grandfathered flag"},
+ status.HTTP_200_OK,
),
(
- "realtime_backfilled_flag_off",
- CohortType.REALTIME,
- True,
+ "enabling_persist_on_device_flag_blocked",
False,
+ {"ensure_experience_continuity": True},
status.HTTP_400_BAD_REQUEST,
- "filters on events",
),
]
)
- @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
- def test_behavioral_cohort_flag_validation(
- self,
- _name,
- cohort_type,
- is_backfilled,
- flag_enabled,
- expected_status,
- expected_detail_fragment,
- mock_feature_enabled,
+ def test_validation_device_bucketing_update(
+ self, _name: str, initial_persist: bool, patch_payload: dict, expected_status: int
):
- mock_feature_enabled.return_value = flag_enabled
+ flag = FeatureFlag.objects.create(
+ name=f"Existing flag {_name}",
+ key=f"existing-{_name.replace('_', '-')}",
+ team=self.team,
+ created_by=self.user,
+ bucketing_identifier="device_id",
+ ensure_experience_continuity=initial_persist,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
- cohort_kwargs: dict[str, Any] = {
- "team": self.team,
- "name": "test-cohort",
- "filters": {
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "$pageview",
- "event_type": "events",
- "time_value": 2,
- "time_interval": "week",
- "value": "performed_event_first_time",
- "type": "behavioral",
- },
- ],
- }
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ patch_payload,
+ format="json",
+ )
+ self.assertEqual(response.status_code, expected_status)
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
+
+ def test_validation_device_bucketing_blocked_for_surveys_creation_context(self):
+ # Locks in the validation reorder: device_id + persist must be rejected even for the
+ # surveys creation_context, which has its own early return in validate(). Without the
+ # hoist, this combination would slip through for survey-created flags.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Survey-created device persist flag",
+ "key": "survey-device-persist-flag",
+ "creation_context": "surveys",
+ "bucketing_identifier": "device_id",
+ "ensure_experience_continuity": True,
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
},
- }
- if cohort_type is not None:
- cohort_kwargs["cohort_type"] = cohort_type
- if is_backfilled:
- cohort_kwargs["last_backfill_person_properties_at"] = datetime.now(tz=UTC)
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
- cohort = Cohort.objects.create(**cohort_kwargs)
+ def _create_flag_with_properties(
+ self,
+ name: str,
+ properties,
+ team_id: Optional[int] = None,
+ expected_status: int = status.HTTP_201_CREATED,
+ **kwargs,
+ ):
+ if team_id is None:
+ team_id = self.team.id
- response = self._create_flag_with_properties(
- "cohort-flag",
- [{"key": "id", "type": "cohort", "value": cohort.id}],
- expected_status=expected_status,
+ create_response = self.client.post(
+ f"/api/projects/{team_id}/feature_flags/",
+ data={
+ "name": name,
+ "key": name,
+ "filters": {**kwargs, "groups": [{"properties": properties}]},
+ },
+ format="json",
)
- self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(create_response.status_code, expected_status)
+ return create_response
- if expected_detail_fragment is not None:
- self.assertIn(expected_detail_fragment, response.json()["detail"])
+ def _get_feature_flag_activity(
+ self,
+ flag_id: Optional[int] = None,
+ team_id: Optional[int] = None,
+ expected_status: int = status.HTTP_200_OK,
+ ):
+ if team_id is None:
+ team_id = self.team.id
- def test_validation_group_properties(self):
- groups_request = self._create_flag_with_properties(
- "groups-flag",
- [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- }
- ],
- aggregation_group_type_index=0,
- )
- self.assertEqual(groups_request.status_code, status.HTTP_201_CREATED)
+ if flag_id:
+ url = f"/api/projects/{team_id}/feature_flags/{flag_id}/activity"
+ else:
+ url = f"/api/projects/{team_id}/feature_flags/activity"
- illegal_groups_request = self._create_flag_with_properties(
- "illegal-groups-flag",
- [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- }
- ],
- aggregation_group_type_index=3,
- expected_status=status.HTTP_400_BAD_REQUEST,
- )
- self.assertEqual(
- illegal_groups_request.json(),
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Filters are not valid (group properties must match the condition set's group type)",
- "attr": "filters",
+ activity = self.client.get(url)
+ self.assertEqual(activity.status_code, expected_status)
+ if activity.status_code == status.HTTP_404_NOT_FOUND:
+ return None
+ return activity.json()
+
+ def assert_feature_flag_activity(self, flag_id: Optional[int], expected: list[dict]):
+ activity_response = self._get_feature_flag_activity(flag_id)
+
+ activity: list[dict] = activity_response["results"]
+ for item in activity:
+ item.pop("id", None)
+ self.maxDiff = None
+ assert activity == expected
+
+ def test_patch_api_as_form_data(self):
+ another_feature_flag = FeatureFlag.objects.create(
+ team=self.team,
+ name="some feature",
+ key="some-feature",
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": None,
},
+ active=True,
)
- person_request = self._create_flag_with_properties(
- "person-flag",
- [
- {
- "key": "email",
- "type": "person",
- "value": "@posthog.com",
- "operator": "icontains",
- }
- ],
- aggregation_group_type_index=0,
- expected_status=status.HTTP_400_BAD_REQUEST,
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{another_feature_flag.pk}/",
+ data="active=False&name=replaced",
+ content_type="application/x-www-form-urlencoded",
)
+
+ self.assertEqual(response.status_code, 200)
+ updated_flag = FeatureFlag.objects.get(pk=another_feature_flag.pk)
+ self.assertEqual(updated_flag.active, False)
+ self.assertEqual(updated_flag.name, "replaced")
self.assertEqual(
- person_request.json(),
+ updated_flag.filters,
{
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Filters are not valid (group-aggregated conditions can only use group properties)",
- "attr": "filters",
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": None,
},
)
- @parameterized.expand(
- [
- (
- "flag_enabled",
- True,
- status.HTTP_201_CREATED,
- ),
- (
- "flag_disabled",
- False,
- status.HTTP_400_BAD_REQUEST,
- ),
- ]
- )
- @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
- def test_mixed_aggregation_types_across_condition_sets(
- self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled
- ):
- mock_feature_enabled.return_value = mixed_targeting_enabled
-
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
-
- response = self.client.post(
+ def test_feature_flag_threshold(self):
+ feature_flag = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Mixed aggregation flag",
- "key": "mixed-aggregation-flag",
+ data={
+ "name": "Beta feature",
+ "key": "beta-feature",
"filters": {
- "groups": [
- {
- "properties": [],
- "rollout_percentage": 50,
- "aggregation_group_type_index": None, # Person aggregation
- },
- {
- "properties": [],
- "rollout_percentage": 50,
- "aggregation_group_type_index": 0, # Group aggregation
- },
- ]
- },
- },
- format="json",
- )
- self.assertEqual(response.status_code, expected_status)
-
- if expected_status == status.HTTP_201_CREATED:
- # Flag-level aggregation is None when condition sets have mixed aggregation types
- self.assertIsNone(response.json()["filters"]["aggregation_group_type_index"])
- # Each condition set retains its own aggregation type
- groups = response.json()["filters"]["groups"]
- self.assertIsNone(groups[0]["aggregation_group_type_index"])
- self.assertEqual(groups[1]["aggregation_group_type_index"], 0)
- else:
- self.assertIn("Mixed aggregation types", response.json()["detail"])
-
- @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
- def test_mixed_aggregation_round_trip(self, mock_feature_enabled):
- mock_feature_enabled.return_value = True
-
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
-
- create_response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Round-trip flag",
- "key": "round-trip-mixed",
- "filters": {
- "groups": [
- {"properties": [], "rollout_percentage": 50, "aggregation_group_type_index": None},
- {"properties": [], "rollout_percentage": 75, "aggregation_group_type_index": 0},
- ]
+ "aggregation_group_type_index": 0,
+ "groups": [{"rollout_percentage": 65}],
},
+ "rollback_conditions": [
+ {
+ "threshold": 5000,
+ "threshold_metric": {
+ "insight": "trends",
+ "events": [{"order": 0, "id": "$pageview"}],
+ "properties": [
+ {
+ "key": "$geoip_country_name",
+ "type": "person",
+ "value": ["france"],
+ "operator": "exact",
+ }
+ ],
+ },
+ "operator": "lt",
+ "threshold_type": "insight",
+ }
+ ],
+ "auto-rollback": True,
},
format="json",
- )
- self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
-
- get_response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{create_response.json()['id']}/")
- self.assertEqual(get_response.status_code, status.HTTP_200_OK)
- filters = get_response.json()["filters"]
- self.assertIsNone(filters["aggregation_group_type_index"])
- self.assertIsNone(filters["groups"][0]["aggregation_group_type_index"])
- self.assertEqual(filters["groups"][1]["aggregation_group_type_index"], 0)
-
- @parameterized.expand(
- [
- ("flag_enabled", True, status.HTTP_201_CREATED),
- ("flag_disabled", False, status.HTTP_400_BAD_REQUEST),
- ]
- )
- @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
- def test_mixed_aggregation_with_properties(
- self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled
- ):
- mock_feature_enabled.return_value = mixed_targeting_enabled
+ ).json()
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
+ self.assertEqual(len(feature_flag["rollback_conditions"]), 1)
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Mixed flag with properties",
- "key": "mixed-with-props",
- "filters": {
+ def test_get_flags_dont_return_survey_targeting_flags(self):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
+ survey = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={
+ "name": "Notebooks power users survey",
+ "type": "popover",
+ "questions": [
+ {
+ "type": "open",
+ "question": "What would you want to improve from notebooks?",
+ }
+ ],
+ "targeting_flag_filters": {
"groups": [
{
- "properties": [
- {"key": "email", "value": ["[email protected]"], "operator": "exact", "type": "person"}
- ],
- "rollout_percentage": 100,
- "aggregation_group_type_index": None,
- },
- {
+ "variant": None,
+ "rollout_percentage": None,
"properties": [
{
- "key": "created_at",
- "value": "2026-03-10",
- "operator": "is_date_after",
- "type": "group",
- "group_type_index": 0,
+ "key": "billing_plan",
+ "value": ["cloud"],
+ "operator": "exact",
+ "type": "person",
}
],
- "rollout_percentage": 100,
- "aggregation_group_type_index": 0,
- },
+ }
]
},
+ "conditions": {"url": "https://app.posthog.com/notebooks"},
},
format="json",
)
- self.assertEqual(response.status_code, expected_status)
-
- if expected_status == status.HTTP_201_CREATED:
- groups = response.json()["filters"]["groups"]
- self.assertIsNone(groups[0]["aggregation_group_type_index"])
- self.assertEqual(groups[1]["aggregation_group_type_index"], 0)
- else:
- self.assertIn("Mixed aggregation types", response.json()["detail"])
+ assert FeatureFlag.objects.filter(id=survey.json()["targeting_flag"]["id"]).exists()
- @parameterized.expand(
- [
- ("flag_enabled", True, status.HTTP_200_OK),
- ("flag_disabled", False, status.HTTP_400_BAD_REQUEST),
- ]
- )
- @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")
- def test_patch_uniform_flag_to_mixed(self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled):
- mock_feature_enabled.return_value = mixed_targeting_enabled
+ flags_list = self.client.get(f"/api/projects/@current/feature_flags")
+ response = flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["id"] is not survey.json()["targeting_flag"]["id"]
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
+ def test_get_flags_dont_return_product_tour_internal_targeting_flags(self):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
- # Create a uniform person-aggregated flag (no feature flag check needed for uniform)
- flag = FeatureFlag.objects.create(
+ internal_flag = FeatureFlag.objects.create(
team=self.team,
- key="uniform-to-mixed",
- name="Uniform flag",
- filters={
- "groups": [
- {"properties": [], "rollout_percentage": 100, "aggregation_group_type_index": None},
- ]
- },
created_by=self.user,
+ key="product-tour-targeting-test-tour-abc123",
+ filters={"groups": [{"rollout_percentage": 100}]},
)
-
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
- {
- "filters": {
- "groups": [
- {"properties": [], "rollout_percentage": 50, "aggregation_group_type_index": None},
- {"properties": [], "rollout_percentage": 75, "aggregation_group_type_index": 0},
- ]
- }
- },
- format="json",
+ ProductTour.objects.create(
+ team=self.team,
+ name="Test Tour",
+ content={"steps": []},
+ internal_targeting_flag=internal_flag,
)
- self.assertEqual(response.status_code, expected_status)
- def test_per_condition_aggregation_normalization(self):
- """Test that flag-level aggregation is distributed to condition sets without one"""
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
+ flags_list = self.client.get("/api/projects/@current/feature_flags")
+ response = flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "red_button"
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Normalized aggregation flag",
- "key": "normalized-aggregation-flag",
- "filters": {
- "aggregation_group_type_index": 0,
- "groups": [
- {"properties": [], "rollout_percentage": 100},
- ],
- },
- },
- format="json",
+ def test_get_flags_with_active_and_created_by_id_filters(self):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
+ another_user = User.objects.create(email="[email protected]")
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="blue_button")
+ FeatureFlag.objects.create(team=self.team, created_by=another_user, key="orange_button", active=False)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="green_button", active=False)
+
+ filtered_flags_list = self.client.get(
+ f"/api/projects/@current/feature_flags?created_by_id={self.user.id}&active=false"
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- result = response.json()
- # Flag-level should be preserved
- self.assertEqual(result["filters"]["aggregation_group_type_index"], 0)
- # Condition set should have inherited the flag-level value
- self.assertEqual(result["filters"]["groups"][0]["aggregation_group_type_index"], 0)
+ response = filtered_flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "green_button"
- def test_per_condition_aggregation_roundtrip(self):
- """Test that per-condition aggregation values persist through create/read"""
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
+ def test_get_flags_with_type_filters(self):
+ feature_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
+ Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Experiment 1",
+ feature_flag_id=feature_flag.id,
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="purple_button",
+ filters={"multivariate": {"variants": [{"foo": "bar"}]}},
)
- # Create with explicit per-condition value
- create_response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Per-condition aggregation flag",
- "key": "per-condition-aggregation-flag",
- "filters": {
- "groups": [
- {
- "properties": [],
- "rollout_percentage": 100,
- "aggregation_group_type_index": 0,
- },
- ],
- },
- },
- format="json",
- )
- self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
- flag_id = create_response.json()["id"]
+ filtered_flags_list_boolean = self.client.get(f"/api/projects/@current/feature_flags?type=boolean")
+ response = filtered_flags_list_boolean.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == feature_flag.key
- # Read it back
- get_response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/")
- self.assertEqual(get_response.status_code, status.HTTP_200_OK)
- result = get_response.json()
+ filtered_flags_list_multivariant = self.client.get(f"/api/projects/@current/feature_flags?type=multivariant")
+ response = filtered_flags_list_multivariant.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "purple_button"
- # Both flag-level and condition-level should be present and consistent
- self.assertEqual(result["filters"]["aggregation_group_type_index"], 0)
- self.assertEqual(result["filters"]["groups"][0]["aggregation_group_type_index"], 0)
+ filtered_flags_list_experiment = self.client.get(f"/api/projects/@current/feature_flags?type=experiment")
+ response = filtered_flags_list_experiment.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == feature_flag.key
- def test_validation_empty_groups(self):
- """Test that creating a flag with empty groups raises validation error"""
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Empty groups flag",
- "key": "empty-groups-flag",
- "filters": {"groups": []},
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Feature flags must have at least one condition set (group).",
- "attr": "filters",
- },
+ def test_get_flags_with_search(self):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="blue_search_term_button")
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="green_search_term_button",
+ active=False,
)
- def test_create_without_filters_persists_groups_invariant(self):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {"name": "No filters flag", "key": "no-filters-flag"},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- instance = FeatureFlag.objects.get(id=response.json()["id"])
- self.assertEqual(instance.filters, {"groups": []})
+ # Test searching by flag key
+ filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?active=true&search=search_term")
+ response = filtered_flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "blue_search_term_button"
- def test_validation_groups_with_empty_properties_allowed(self):
- """Test that creating a flag with groups having empty properties but valid rollout is allowed"""
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Valid flag with empty properties",
- "key": "valid-empty-properties",
- "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},
- },
- format="json",
+ # Test searching by experiment name
+ flag_with_experiment = FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="experiment_flag", active=True
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- def test_validation_empty_groups_allowed_on_update(self):
- """Test that updating an existing flag with empty groups is allowed (for scheduled changes)"""
- # First create a valid flag
- flag = FeatureFlag.objects.create(
- name="Test flag",
- key="test-flag-update",
+ Experiment.objects.create(
team=self.team,
created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ name="unique_experiment_name",
+ feature_flag=flag_with_experiment,
+ deleted=False,
)
- # Now try to update it with empty groups (this should be allowed)
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
- {"filters": {"groups": []}},
- format="json",
- )
- # Should succeed since it's an update, not creation
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ filtered_by_experiment = self.client.get(f"/api/projects/@current/feature_flags?search=unique_experiment_name")
+ response = filtered_by_experiment.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "experiment_flag"
- @parameterized.expand(
- [
- # name, bucketing_identifier, ensure_experience_continuity, expected_status
- ("device_with_persist_blocked", "device_id", True, status.HTTP_400_BAD_REQUEST),
- ("device_without_persist_allowed", "device_id", False, status.HTTP_201_CREATED),
- ]
- )
- def test_validation_device_bucketing_create(
- self, _name: str, bucketing_identifier: str, ensure_experience_continuity: bool, expected_status: int
- ):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": f"Device bucketing {_name}",
- "key": f"device-{_name.replace('_', '-')}-flag",
- "bucketing_identifier": bucketing_identifier,
- "ensure_experience_continuity": ensure_experience_continuity,
- "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
- },
- format="json",
+ # Test that deleted experiments are not included in search
+ deleted_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="deleted_experiment_flag",
+ active=True,
)
- self.assertEqual(response.status_code, expected_status)
- if expected_status == status.HTTP_400_BAD_REQUEST:
- self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
-
- @parameterized.expand(
- [
- # name, initial_persist, patch_payload, expected_status
- (
- "grandfathered_combination_can_save",
- True,
- {"name": "Updated grandfathered flag"},
- status.HTTP_200_OK,
- ),
- (
- "enabling_persist_on_device_flag_blocked",
- False,
- {"ensure_experience_continuity": True},
- status.HTTP_400_BAD_REQUEST,
- ),
- ]
- )
- def test_validation_device_bucketing_update(
- self, _name: str, initial_persist: bool, patch_payload: dict, expected_status: int
- ):
- flag = FeatureFlag.objects.create(
- name=f"Existing flag {_name}",
- key=f"existing-{_name.replace('_', '-')}",
+ Experiment.objects.create(
team=self.team,
created_by=self.user,
- bucketing_identifier="device_id",
- ensure_experience_continuity=initial_persist,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ name="deleted_unique_experiment",
+ feature_flag=deleted_flag,
+ deleted=True,
)
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
- patch_payload,
- format="json",
- )
- self.assertEqual(response.status_code, expected_status)
- if expected_status == status.HTTP_400_BAD_REQUEST:
- self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
+ filtered_deleted = self.client.get(f"/api/projects/@current/feature_flags?search=deleted_unique_experiment")
+ response = filtered_deleted.json()
+ assert len(response["results"]) == 0
- def test_validation_device_bucketing_blocked_for_surveys_creation_context(self):
- # Locks in the validation reorder: device_id + persist must be rejected even for the
- # surveys creation_context, which has its own early return in validate(). Without the
- # hoist, this combination would slip through for survey-created flags.
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Survey-created device persist flag",
- "key": "survey-device-persist-flag",
- "creation_context": "surveys",
- "bucketing_identifier": "device_id",
- "ensure_experience_continuity": True,
- "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
- },
- format="json",
+ def test_get_flags_with_search_word_boundaries(self):
+ """Test that search handles word boundaries correctly (spaces, hyphens, underscores)."""
+ # Create flags with different word separators
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="feature-flag-test", active=True)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="feature_flag_experiment", active=True)
+ FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="my_feature_button", active=True, name="Feature Button Display"
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("Cannot enable 'persist across authentication steps'", response.json()["detail"])
-
- def _create_flag_with_properties(
- self,
- name: str,
- properties,
- team_id: Optional[int] = None,
- expected_status: int = status.HTTP_201_CREATED,
- **kwargs,
- ):
- if team_id is None:
- team_id = self.team.id
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated-item", active=True)
- create_response = self.client.post(
- f"/api/projects/{team_id}/feature_flags/",
- data={
- "name": name,
- "key": name,
- "filters": {**kwargs, "groups": [{"properties": properties}]},
- },
- format="json",
- )
- self.assertEqual(create_response.status_code, expected_status)
- return create_response
+ # Test searching for "feature flag" should match hyphenated and underscored versions
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=feature flag")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
- def _get_feature_flag_activity(
- self,
- flag_id: Optional[int] = None,
- team_id: Optional[int] = None,
- expected_status: int = status.HTTP_200_OK,
- ):
- if team_id is None:
- team_id = self.team.id
+ # Full-text search should find flags where "feature" and "flag" appear as separate words
+ # This should match hyphenated and underscored versions
+ expected_matches = {"feature-flag-test", "feature_flag_experiment"}
+ assert expected_matches.issubset(matched_keys), f"Expected {expected_matches} to be found in {matched_keys}"
+ assert "unrelated-item" not in matched_keys
- if flag_id:
- url = f"/api/projects/{team_id}/feature_flags/{flag_id}/activity"
- else:
- url = f"/api/projects/{team_id}/feature_flags/activity"
+ # Test searching by name (which has spaces)
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=Feature Button")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
- activity = self.client.get(url)
- self.assertEqual(activity.status_code, expected_status)
- if activity.status_code == status.HTTP_404_NOT_FOUND:
- return None
- return activity.json()
-
- def assert_feature_flag_activity(self, flag_id: Optional[int], expected: list[dict]):
- activity_response = self._get_feature_flag_activity(flag_id)
+ # Should match flag by name
+ assert "my_feature_button" in matched_keys, f"Expected to find flag by name, got {matched_keys}"
- activity: list[dict] = activity_response["results"]
- for item in activity:
- item.pop("id", None)
- self.maxDiff = None
- assert activity == expected
+ # Test searching for "feature" should match all flags containing that word
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=feature")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
- def test_patch_api_as_form_data(self):
- another_feature_flag = FeatureFlag.objects.create(
- team=self.team,
- name="some feature",
- key="some-feature",
- created_by=self.user,
- filters={
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "multivariate": None,
- },
- active=True,
- )
+ # Should match all flags containing "feature"
+ expected_matches = {"feature-flag-test", "feature_flag_experiment", "my_feature_button"}
+ assert expected_matches.issubset(matched_keys), f"Expected {expected_matches} to be found in {matched_keys}"
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{another_feature_flag.pk}/",
- data="active=False&name=replaced",
- content_type="application/x-www-form-urlencoded",
+ def test_get_flags_with_search_partial_word_matching(self):
+ """Test that search handles partial word matching using regex patterns."""
+ # Create flags to test different word separators
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web_dashboard", active=True)
+ FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="web analytics", name="Web Analytics Feature", active=True
)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="mobile-analytics", active=True)
- self.assertEqual(response.status_code, 200)
- updated_flag = FeatureFlag.objects.get(pk=another_feature_flag.pk)
- self.assertEqual(updated_flag.active, False)
- self.assertEqual(updated_flag.name, "replaced")
- self.assertEqual(
- updated_flag.filters,
- {
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "multivariate": None,
- },
- )
+ # Test searching for "web ana" should match various separators
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=web ana")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
- def test_feature_flag_threshold(self):
- feature_flag = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- data={
- "name": "Beta feature",
- "key": "beta-feature",
- "filters": {
- "aggregation_group_type_index": 0,
- "groups": [{"rollout_percentage": 65}],
- },
- "rollback_conditions": [
- {
- "threshold": 5000,
- "threshold_metric": {
- "insight": "trends",
- "events": [{"order": 0, "id": "$pageview"}],
- "properties": [
- {
- "key": "$geoip_country_name",
- "type": "person",
- "value": ["france"],
- "operator": "exact",
- }
- ],
- },
- "operator": "lt",
- "threshold_type": "insight",
- }
- ],
- "auto-rollback": True,
- },
- format="json",
- ).json()
+ # Should match web-analytics and "web analytics" (by name)
+ assert "web-analytics" in matched_keys, f"Expected 'web-analytics' in {matched_keys}"
+ assert "web analytics" in matched_keys, f"Expected 'web analytics' in {matched_keys}"
+ assert "mobile-analytics" not in matched_keys, "Should not match mobile-analytics"
- self.assertEqual(len(feature_flag["rollback_conditions"]), 1)
+ # Test different word separators
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=web dash")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
+ assert "web_dashboard" in matched_keys, f"Expected 'web_dashboard' in {matched_keys}"
- def test_get_flags_dont_return_survey_targeting_flags(self):
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
- survey = self.client.post(
- f"/api/projects/{self.team.id}/surveys/",
- data={
- "name": "Notebooks power users survey",
- "type": "popover",
- "questions": [
- {
- "type": "open",
- "question": "What would you want to improve from notebooks?",
- }
- ],
- "targeting_flag_filters": {
- "groups": [
- {
- "variant": None,
- "rollout_percentage": None,
- "properties": [
- {
- "key": "billing_plan",
- "value": ["cloud"],
- "operator": "exact",
- "type": "person",
- }
- ],
- }
- ]
- },
- "conditions": {"url": "https://app.posthog.com/notebooks"},
- },
- format="json",
- )
- assert FeatureFlag.objects.filter(id=survey.json()["targeting_flag"]["id"]).exists()
+ # Test single word still works
+ response = self.client.get(f"/api/projects/@current/feature_flags?search=web")
+ data = response.json()
+ matched_keys = {result["key"] for result in data["results"]}
- flags_list = self.client.get(f"/api/projects/@current/feature_flags")
- response = flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["id"] is not survey.json()["targeting_flag"]["id"]
+ # Should match all web flags
+ web_flags = {"web-analytics", "web_dashboard", "web analytics"}
+ assert web_flags.issubset(matched_keys), f"Expected {web_flags} in {matched_keys}"
+ assert "mobile-analytics" not in matched_keys
- def test_get_flags_dont_return_product_tour_internal_targeting_flags(self):
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
+ def test_get_flags_with_search_exact_api_case(self):
+ """Test the exact case from the user's API call: web%20ana should match web-analytics."""
+ # Create the exact flag mentioned by the user
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-flag", active=True)
- internal_flag = FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="product-tour-targeting-test-tour-abc123",
- filters={"groups": [{"rollout_percentage": 100}]},
- )
- ProductTour.objects.create(
- team=self.team,
- name="Test Tour",
- content={"steps": []},
- internal_targeting_flag=internal_flag,
+ # Test the exact API call pattern: search=web%20ana (which becomes "web ana")
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/?search=web ana&page=1&limit=100&offset=0"
)
+ data = response.json()
- flags_list = self.client.get("/api/projects/@current/feature_flags")
- response = flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "red_button"
+ # The search should find web-analytics
+ assert response.status_code == 200
+ assert "results" in data
+ matched_keys = {result["key"] for result in data["results"]}
+ assert "web-analytics" in matched_keys, f"Expected 'web-analytics' in {matched_keys}"
- def test_get_flags_with_active_and_created_by_id_filters(self):
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
- another_user = User.objects.create(email="[email protected]")
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="blue_button")
- FeatureFlag.objects.create(team=self.team, created_by=another_user, key="orange_button", active=False)
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="green_button", active=False)
+ def test_get_flags_with_search_trailing_space(self):
+ """Test that search handles trailing spaces correctly by trimming them."""
+ # Create flags to test with
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="mobile-app", active=True)
- filtered_flags_list = self.client.get(
- f"/api/projects/@current/feature_flags?created_by_id={self.user.id}&active=false"
- )
- response = filtered_flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "green_button"
+ # Test search with trailing space (URL encoded as "web%20")
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search=web ")
+ data = response.json()
- def test_get_flags_with_type_filters(self):
- feature_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
- Experiment.objects.create(
- team=self.team,
- created_by=self.user,
- name="Experiment 1",
- feature_flag_id=feature_flag.id,
- )
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="purple_button",
- filters={"multivariate": {"variants": [{"foo": "bar"}]}},
+ assert response.status_code == 200
+ assert "results" in data
+ matched_keys = {result["key"] for result in data["results"]}
+ assert "web-analytics" in matched_keys, (
+ f"Expected 'web-analytics' with trailing space search, got {matched_keys}"
)
+ assert "mobile-app" not in matched_keys
- filtered_flags_list_boolean = self.client.get(f"/api/projects/@current/feature_flags?type=boolean")
- response = filtered_flags_list_boolean.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == feature_flag.key
-
- filtered_flags_list_multivariant = self.client.get(f"/api/projects/@current/feature_flags?type=multivariant")
- response = filtered_flags_list_multivariant.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "purple_button"
-
- filtered_flags_list_experiment = self.client.get(f"/api/projects/@current/feature_flags?type=experiment")
- response = filtered_flags_list_experiment.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == feature_flag.key
+ # Test search with leading space
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search= web")
+ data = response.json()
- def test_get_flags_with_search(self):
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="blue_search_term_button")
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="green_search_term_button",
- active=False,
+ assert response.status_code == 200
+ matched_keys = {result["key"] for result in data["results"]}
+ assert "web-analytics" in matched_keys, (
+ f"Expected 'web-analytics' with leading space search, got {matched_keys}"
)
- # Test searching by flag key
- filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?active=true&search=search_term")
- response = filtered_flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "blue_search_term_button"
-
- # Test searching by experiment name
- flag_with_experiment = FeatureFlag.objects.create(
- team=self.team, created_by=self.user, key="experiment_flag", active=True
- )
- Experiment.objects.create(
- team=self.team,
- created_by=self.user,
- name="unique_experiment_name",
- feature_flag=flag_with_experiment,
- deleted=False,
- )
-
- filtered_by_experiment = self.client.get(f"/api/projects/@current/feature_flags?search=unique_experiment_name")
- response = filtered_by_experiment.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "experiment_flag"
-
- # Test that deleted experiments are not included in search
- deleted_flag = FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="deleted_experiment_flag",
- active=True,
- )
- Experiment.objects.create(
- team=self.team,
- created_by=self.user,
- name="deleted_unique_experiment",
- feature_flag=deleted_flag,
- deleted=True,
- )
-
- filtered_deleted = self.client.get(f"/api/projects/@current/feature_flags?search=deleted_unique_experiment")
- response = filtered_deleted.json()
- assert len(response["results"]) == 0
-
- def test_get_flags_with_search_word_boundaries(self):
- """Test that search handles word boundaries correctly (spaces, hyphens, underscores)."""
- # Create flags with different word separators
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="feature-flag-test", active=True)
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="feature_flag_experiment", active=True)
- FeatureFlag.objects.create(
- team=self.team, created_by=self.user, key="my_feature_button", active=True, name="Feature Button Display"
- )
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated-item", active=True)
-
- # Test searching for "feature flag" should match hyphenated and underscored versions
- response = self.client.get(f"/api/projects/@current/feature_flags?search=feature flag")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
-
- # Full-text search should find flags where "feature" and "flag" appear as separate words
- # This should match hyphenated and underscored versions
- expected_matches = {"feature-flag-test", "feature_flag_experiment"}
- assert expected_matches.issubset(matched_keys), f"Expected {expected_matches} to be found in {matched_keys}"
- assert "unrelated-item" not in matched_keys
-
- # Test searching by name (which has spaces)
- response = self.client.get(f"/api/projects/@current/feature_flags?search=Feature Button")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
-
- # Should match flag by name
- assert "my_feature_button" in matched_keys, f"Expected to find flag by name, got {matched_keys}"
-
- # Test searching for "feature" should match all flags containing that word
- response = self.client.get(f"/api/projects/@current/feature_flags?search=feature")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
-
- # Should match all flags containing "feature"
- expected_matches = {"feature-flag-test", "feature_flag_experiment", "my_feature_button"}
- assert expected_matches.issubset(matched_keys), f"Expected {expected_matches} to be found in {matched_keys}"
-
- def test_get_flags_with_search_partial_word_matching(self):
- """Test that search handles partial word matching using regex patterns."""
- # Create flags to test different word separators
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web_dashboard", active=True)
- FeatureFlag.objects.create(
- team=self.team, created_by=self.user, key="web analytics", name="Web Analytics Feature", active=True
- )
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="mobile-analytics", active=True)
-
- # Test searching for "web ana" should match various separators
- response = self.client.get(f"/api/projects/@current/feature_flags?search=web ana")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
-
- # Should match web-analytics and "web analytics" (by name)
- assert "web-analytics" in matched_keys, f"Expected 'web-analytics' in {matched_keys}"
- assert "web analytics" in matched_keys, f"Expected 'web analytics' in {matched_keys}"
- assert "mobile-analytics" not in matched_keys, "Should not match mobile-analytics"
-
- # Test different word separators
- response = self.client.get(f"/api/projects/@current/feature_flags?search=web dash")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
- assert "web_dashboard" in matched_keys, f"Expected 'web_dashboard' in {matched_keys}"
-
- # Test single word still works
- response = self.client.get(f"/api/projects/@current/feature_flags?search=web")
- data = response.json()
- matched_keys = {result["key"] for result in data["results"]}
-
- # Should match all web flags
- web_flags = {"web-analytics", "web_dashboard", "web analytics"}
- assert web_flags.issubset(matched_keys), f"Expected {web_flags} in {matched_keys}"
- assert "mobile-analytics" not in matched_keys
-
- def test_get_flags_with_search_exact_api_case(self):
- """Test the exact case from the user's API call: web%20ana should match web-analytics."""
- # Create the exact flag mentioned by the user
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-flag", active=True)
-
- # Test the exact API call pattern: search=web%20ana (which becomes "web ana")
- response = self.client.get(
- f"/api/projects/{self.team.id}/feature_flags/?search=web ana&page=1&limit=100&offset=0"
- )
- data = response.json()
-
- # The search should find web-analytics
- assert response.status_code == 200
- assert "results" in data
- matched_keys = {result["key"] for result in data["results"]}
- assert "web-analytics" in matched_keys, f"Expected 'web-analytics' in {matched_keys}"
-
- def test_get_flags_with_search_trailing_space(self):
- """Test that search handles trailing spaces correctly by trimming them."""
- # Create flags to test with
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="web-analytics", active=True)
- FeatureFlag.objects.create(team=self.team, created_by=self.user, key="mobile-app", active=True)
-
- # Test search with trailing space (URL encoded as "web%20")
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search=web ")
- data = response.json()
-
- assert response.status_code == 200
- assert "results" in data
- matched_keys = {result["key"] for result in data["results"]}
- assert "web-analytics" in matched_keys, (
- f"Expected 'web-analytics' with trailing space search, got {matched_keys}"
- )
- assert "mobile-app" not in matched_keys
-
- # Test search with leading space
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search= web")
- data = response.json()
-
- assert response.status_code == 200
- matched_keys = {result["key"] for result in data["results"]}
- assert "web-analytics" in matched_keys, (
- f"Expected 'web-analytics' with leading space search, got {matched_keys}"
- )
-
- # Test search with both leading and trailing spaces
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search= web ")
- data = response.json()
+ # Test search with both leading and trailing spaces
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/?search= web ")
+ data = response.json()
assert response.status_code == 200
matched_keys = {result["key"] for result in data["results"]}
@@ -6776,1873 +5964,699 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
],
"release_percentage": 100,
},
- },
- )
- with_props_flag.last_called_at = datetime.now(UTC) - timedelta(days=1)
- with_props_flag.save()
-
- # Test filtering by stale status
- filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?active=STALE")
- response = filtered_flags_list.json()
-
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "stale_multivariate"
- assert response["results"][0]["status"] == "STALE"
-
- def test_get_flags_with_stale_filter_explicit_multivariate_null(self):
- # Regression test: flags created via frontend have explicit multivariate: null
- # The SQL filter should handle both missing key AND explicit null value
- # No last_called_at so it falls back to config-based detection
- with freeze_time("2024-01-01"):
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="stale_with_explicit_null",
- active=True,
- filters={
- "groups": [{"rollout_percentage": 100, "properties": []}],
- "multivariate": None, # Frontend explicitly sets this to null
- "payloads": {},
- },
- )
-
- # Create a non-stale flag with explicit multivariate: null (recent)
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="recent_with_explicit_null",
- active=True,
- filters={
- "groups": [{"rollout_percentage": 100, "properties": []}],
- "multivariate": None,
- "payloads": {},
- },
- last_called_at=datetime.now(UTC) - timedelta(days=1),
- )
-
- filtered_flags_list = self.client.get("/api/projects/@current/feature_flags?active=STALE")
- response = filtered_flags_list.json()
-
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "stale_with_explicit_null"
- assert response["results"][0]["status"] == "STALE"
-
- @parameterized.expand(
- [
- (
- "json_null_variant",
- {
- "groups": [{"rollout_percentage": 100, "properties": [], "variant": None}],
- "multivariate": {
- "variants": [
- {"key": "test", "rollout_percentage": 50},
- {"key": "test2", "rollout_percentage": 50},
- ],
- },
- },
- False, # JSON null variant is not a real override, should not be stale
- ),
- (
- "empty_multivariate_object",
- {
- "groups": [{"rollout_percentage": 100, "properties": []}],
- "multivariate": {},
- },
- True, # empty multivariate {} should be treated like no multivariate
- ),
- ]
- )
- def test_get_flags_with_stale_filter_jsonb_edge_cases(self, flag_key, flag_filters, expect_stale):
- with freeze_time("2023-01-01"):
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key=flag_key,
- active=True,
- filters=flag_filters,
- )
-
- response = self.client.get("/api/projects/@current/feature_flags?active=STALE").json()
- is_in_results = any(f["key"] == flag_key for f in response["results"])
- assert is_in_results == expect_stale
-
- def test_get_flags_with_evaluation_runtime_filter(self):
- # Create flags with different evaluation runtimes
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="server_flag",
- evaluation_runtime="server",
- )
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="client_flag",
- evaluation_runtime="client",
- )
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="both_flag",
- evaluation_runtime="both",
- )
-
- # Test filtering by server environment
- filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=server")
- response = filtered_flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "server_flag"
-
- # Test filtering by client environment
- filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=client")
- response = filtered_flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "client_flag"
-
- # Test filtering by both environment
- filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=both")
- response = filtered_flags_list.json()
- assert len(response["results"]) == 1
- assert response["results"][0]["key"] == "both_flag"
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_flag_is_cached_on_create_and_update(self, mock_on_commit):
- # Ensure empty feature flag list
- FeatureFlag.objects.all().delete()
-
- feature_flag = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- data={
- "name": "Beta feature",
- "key": "beta-feature",
- "filters": {
- "aggregation_group_type_index": 0,
- "groups": [{"rollout_percentage": 65}],
- },
- },
- format="json",
- ).json()
-
- flags = get_feature_flags_for_team_in_cache(self.team.id)
-
- assert flags is not None
- self.assertEqual(len(flags), 1)
- self.assertEqual(flags[0].id, feature_flag["id"])
- self.assertEqual(flags[0].key, "beta-feature")
- self.assertEqual(flags[0].name, "Beta feature")
-
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",
- {"name": "XYZ", "key": "red_button"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- flags = get_feature_flags_for_team_in_cache(self.team.id)
-
- assert flags is not None
- self.assertEqual(len(flags), 1)
- self.assertEqual(flags[0].id, feature_flag["id"])
- self.assertEqual(flags[0].key, "red_button")
- self.assertEqual(flags[0].name, "XYZ")
-
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",
- {"deleted": True},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- flags = get_feature_flags_for_team_in_cache(self.team.id)
-
- assert flags is not None
- self.assertEqual(len(flags), 0)
-
- @patch("products.feature_flags.backend.api.feature_flag.LocalEvaluationThrottle.rate", new="7/minute")
- @patch("posthog.rate_limit.BurstRateThrottle.rate", new="5/minute")
- @patch("posthog.rate_limit.statsd.incr")
- @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
- def test_rate_limits_for_local_evaluation_are_independent(self, rate_limit_enabled_mock, incr_mock):
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- for _ in range(5):
- response = self.client.get(
- f"/api/projects/{self.team.pk}/feature_flags",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # Call to flags gets rate limited
- response = self.client.get(
- f"/api/projects/{self.team.pk}/feature_flags",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
- self.assertEqual(
- len([1 for name, args, kwargs in incr_mock.mock_calls if args[0] == "rate_limit_exceeded"]),
- 1,
- )
- incr_mock.assert_any_call(
- "rate_limit_exceeded",
- tags={
- "team_id": self.team.pk,
- "scope": "burst",
- "rate": "5/minute",
- "route": "/api/projects/TEAM_ID/feature_flags/",
- "hashed_personal_api_key": hash_key_value(personal_api_key),
- },
- )
-
- incr_mock.reset_mock()
-
- # but not call to local evaluation
- for _ in range(7):
- response = self.client.get(
- f"/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- len([1 for name, args, kwargs in incr_mock.mock_calls if args[0] == "rate_limit_exceeded"]),
- 0,
- )
-
- def test_feature_flag_dashboard(self):
- another_feature_flag = FeatureFlag.objects.create(
- team=self.team,
- name="some feature",
- key="some-feature",
- created_by=self.user,
- )
- dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
- relationship = FeatureFlagDashboards.objects.create(
- feature_flag=another_feature_flag, dashboard_id=dashboard.pk
- )
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk))
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
-
- self.assertEqual(len(response_json["analytics_dashboards"]), 1)
-
- # check deleting the dashboard doesn't delete flag, but deletes the relationship
- dashboard.delete()
- another_feature_flag.refresh_from_db()
-
- with self.assertRaises(FeatureFlagDashboards.DoesNotExist):
- relationship.refresh_from_db()
-
- def test_feature_flag_dashboard_patch(self):
- another_feature_flag = FeatureFlag.objects.create(
- team=self.team,
- name="some feature",
- key="some-feature",
- created_by=self.user,
- )
- dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
- {"analytics_dashboards": [dashboard.pk]},
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk))
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
-
- self.assertEqual(len(response_json["analytics_dashboards"]), 1)
-
- def test_feature_flag_dashboard_already_exists(self):
- another_feature_flag = FeatureFlag.objects.create(
- team=self.team,
- name="some feature",
- key="some-feature",
- created_by=self.user,
- )
- dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
- {"analytics_dashboards": [dashboard.pk]},
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
- {"analytics_dashboards": [dashboard.pk]},
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
-
- self.assertEqual(len(response_json["analytics_dashboards"]), 1)
-
- @freeze_time("2021-01-01")
- @snapshot_clickhouse_queries
- def test_creating_static_cohort(self):
- flag = FeatureFlag.objects.create(
- team=self.team,
- filters={
- "groups": [{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- "multivariate": None,
- },
- name="some feature",
- key="some-feature",
- created_by=self.user,
- )
-
- _create_person(
- team=self.team,
- distinct_ids=[f"person1"],
- properties={"key": "value"},
- )
- _create_person(
- team=self.team,
- distinct_ids=[f"person2"],
- properties={"key": "value2"},
- )
- _create_person(
- team=self.team,
- distinct_ids=[f"person3"],
- properties={"key2": "value3"},
- )
- flush_persons_and_events()
-
- with (
- snapshot_postgres_queries_context(self),
- self.settings(
- CELERY_TASK_ALWAYS_EAGER=True,
- PERSON_ON_EVENTS_OVERRIDE=False,
- PERSON_ON_EVENTS_V2_OVERRIDE=False,
- ),
- ):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/{flag.id}/create_static_cohort_for_flag",
- {},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- # fires an async task for computation, but celery runs sync in tests
- cohort_id = response.json()["cohort"]["id"]
- cohort = Cohort.objects.get(id=cohort_id)
- self.assertEqual(
- cohort.name,
- "Users with feature flag some-feature enabled at 2021-01-01 00:00:00",
- )
- self.assertEqual(cohort.count, 1)
-
- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")
- self.assertEqual(len(response.json()["results"]), 1, response)
-
- def test_cant_update_early_access_flag_with_group(self):
- feature_flag = FeatureFlag.objects.create(
- team=self.team,
- filters={
- "aggregation_group_type_index": None,
- "groups": [{"properties": [], "rollout_percentage": None}],
- },
- name="some feature",
- key="some-feature",
- created_by=self.user,
- )
-
- EarlyAccessFeature.objects.create(
- team=self.team,
- name="earlyAccessFeature",
- description="early access feature",
- stage="alpha",
- feature_flag=feature_flag,
- )
-
- update_data = {
- "filters": {
- "aggregation_group_type_index": 2,
- "groups": [{"properties": [], "rollout_percentage": 100}],
- }
- }
- response = self.client.patch(
- f"/api/projects/{self.team.id}/feature_flags/{feature_flag.id}/",
- update_data,
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertLessEqual(
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Cannot use group aggregation in any condition set when the flag is linked to an Early Access Feature.",
- }.items(),
- response.json().items(),
- )
-
- def test_feature_flag_includes_cohort_names(self):
- cohort = Cohort.objects.create(
- team=self.team,
- name="test_cohort",
- groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Alpha feature",
- "key": "alpha-feature",
- "filters": {
- "groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}],
- },
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- # Get the flag
- response = self.client.get(
- f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- response.json()["filters"]["groups"][0]["properties"][0],
- {
- "key": "id",
- "type": "cohort",
- "value": cohort.pk,
- "cohort_name": "test_cohort",
- },
- )
-
- def test_feature_flag_includes_group_key_names(self):
- GroupTypeMapping.objects.create(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- Group.objects.create(
- team=self.team,
- group_key="org-uuid-1",
- group_type_index=0,
- group_properties={"name": "Acme Corp"},
- version=0,
- )
- Group.objects.create(
- team=self.team,
- group_key="org-uuid-2",
- group_type_index=0,
- group_properties={"name": "Widget Inc"},
- version=0,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {
- "name": "Group flag",
- "key": "group-flag",
- "filters": {
- "aggregation_group_type_index": 0,
- "groups": [
- {
- "properties": [
- {
- "key": "$group_key",
- "type": "group",
- "value": ["org-uuid-1", "org-uuid-2"],
- "operator": "exact",
- "group_type_index": 0,
- }
- ]
- }
- ],
- },
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- response = self.client.get(
- f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- prop = response.json()["filters"]["groups"][0]["properties"][0]
- self.assertEqual(prop["key"], "$group_key")
- self.assertEqual(
- prop["group_key_names"],
- {"org-uuid-1": "Acme Corp", "org-uuid-2": "Widget Inc"},
- )
-
- def test_create_feature_flag_in_specific_folder(self):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- data={
- "key": "my-test-flag-in-folder",
- "name": "Test Flag in Folder",
- "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},
- "_create_in_folder": "Special Folder/Flags",
- },
- format="json",
- )
- assert response.status_code == 201, response.json()
- flag_id = response.json()["id"]
- assert flag_id is not None
-
- from posthog.models.file_system.file_system import FileSystem
-
- fs_entry = FileSystem.objects.filter(team=self.team, ref=str(flag_id), type="feature_flag").first()
- assert fs_entry, "No FileSystem entry found for this feature flag."
- assert "Special Folder/Flags" in fs_entry.path, (
- f"Expected 'Special Folder/Flags' in path, got: '{fs_entry.path}'"
- )
-
- def test_feature_flag_experiment_set(self):
- # Create a feature flag
- feature_flag = FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- name="Test Flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- # Initially, experiment_set should be empty
- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
- assert response.status_code == 200
- assert response.json()["experiment_set"] == []
-
- # Create an active experiment linked to the flag
- experiment = Experiment.objects.create(
- team=self.team,
- created_by=self.user,
- name="Test Experiment",
- feature_flag=feature_flag,
- start_date=datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),
- )
-
- # experiment_set should now include the experiment ID
- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
- assert response.status_code == 200
- assert response.json()["experiment_set"] == [experiment.id]
-
- # Create a deleted experiment - should not be included
- experiment2 = Experiment.objects.create(
- team=self.team,
- created_by=self.user,
- name="Another Experiment",
- feature_flag=feature_flag,
- start_date=datetime(2024, 1, 1, 12, 1, 0, tzinfo=UTC),
- )
-
- # experiment_set should include both experiments
- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
- assert response.status_code == 200
- assert response.json()["experiment_set"] == [experiment.id, experiment2.id]
-
- # Delete the active experiments
- experiment.deleted = True
- experiment.save()
- experiment2.deleted = True
- experiment2.save()
-
- # experiment_set should now be empty again
- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
- assert response.status_code == 200
- assert response.json()["experiment_set"] == []
-
- def test_bulk_keys_valid_ids(self):
- """Test that valid IDs return correct key mapping"""
- # Create test flags
- flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
- flag2 = FeatureFlag.objects.create(key="test-flag-2", name="Test Flag 2", team=self.team, created_by=self.user)
- flag3 = FeatureFlag.objects.create(key="test-flag-3", name="Test Flag 3", team=self.team, created_by=self.user)
-
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [flag1.id, flag2.id, flag3.id]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert "keys" in data
- assert data["keys"] == {
- str(flag1.id): "test-flag-1",
- str(flag2.id): "test-flag-2",
- str(flag3.id): "test-flag-3",
- }
-
- def test_bulk_keys_empty_list(self):
- """Test that empty ID list returns empty keys object"""
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": []},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert data == {"keys": {}}
-
- def test_bulk_keys_invalid_ids(self):
- """Test that invalid IDs (non-integers) return error"""
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": ["invalid", "not-a-number"]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- data = response.json()
- assert "error" in data
- assert "Invalid flag IDs provided" in data["error"]
-
- def test_bulk_keys_mixed_valid_invalid_ids(self):
- """Test that mixed valid/invalid IDs filter out invalid ones"""
- flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
-
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [flag1.id, "invalid", 99999]}, # valid ID, invalid string, non-existent ID
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert "keys" in data
- assert data["keys"] == {str(flag1.id): "test-flag-1"}
- assert "warning" in data
- assert "Invalid flag IDs ignored: ['invalid']" in data["warning"]
-
- def test_bulk_keys_nonexistent_ids(self):
- """Test that non-existent flag IDs are filtered out"""
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [99999, 88888]}, # Non-existent IDs
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert data == {"keys": {}}
-
- def test_bulk_keys_team_isolation(self):
- """Test that flags from other teams are not returned"""
- # Create flag in current team
- flag1 = FeatureFlag.objects.create(
- key="current-team-flag",
- name="Current Team Flag",
- team=self.team,
- created_by=self.user,
- )
-
- # Create another team and flag
- other_user = User.objects.create_user(email="[email protected]", password="password", first_name="Other")
- other_organization, _, other_team = Organization.objects.bootstrap(other_user)
- flag2 = FeatureFlag.objects.create(
- key="other-team-flag",
- name="Other Team Flag",
- team=other_team,
- created_by=other_user,
- )
-
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [flag1.id, flag2.id]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert "keys" in data
- # Should only return flag from current team
- assert data["keys"] == {str(flag1.id): "current-team-flag"}
-
- def test_bulk_keys_deleted_flags(self):
- """Test that deleted flags are not returned"""
- flag1 = FeatureFlag.objects.create(key="active-flag", name="Active Flag", team=self.team, created_by=self.user)
- flag2 = FeatureFlag.objects.create(
- key="deleted-flag",
- name="Deleted Flag",
- team=self.team,
- created_by=self.user,
- deleted=True,
- )
-
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [flag1.id, flag2.id]},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert "keys" in data
- # Should only return non-deleted flag
- assert data["keys"] == {str(flag1.id): "active-flag"}
-
- def test_bulk_keys_no_ids_param(self):
- """Test that missing 'ids' parameter returns empty keys object"""
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {}, # No 'ids' parameter
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert data == {"keys": {}}
-
- def test_bulk_keys_string_ids(self):
- """Test that string representations of valid IDs work"""
- flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
-
- response = self.client.post(
- f"/api/projects/@current/feature_flags/bulk_keys/",
- {"ids": [str(flag1.id)]}, # String ID instead of integer
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert "keys" in data
- assert data["keys"] == {str(flag1.id): "test-flag-1"}
-
- def test_local_evaluation_caching_basic(self):
- """Test basic caching functionality for local_evaluation endpoint."""
- # Clear any existing flags for this team to avoid interference
- FeatureFlag.objects.filter(team=self.team).delete()
-
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- # Clear both Redis and S3 caches
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- # First request should miss cache and populate it
- self.client.logout()
- response = self.client.get(
- f"/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # Check that cache is now populated (using HyperCache format)
- cache_key = f"cache/teams/{self.team.id}/feature_flags/flags_without_cohorts.json"
- cached_data = cache.get(cache_key)
- self.assertIsNotNone(cached_data)
- cached_json = json.loads(cached_data)
- self.assertEqual(len(cached_json["flags"]), 1)
- self.assertEqual(cached_json["flags"][0]["key"], "test-flag")
-
- @patch("products.feature_flags.backend.api.feature_flag.capture_exception")
- def test_local_evaluation_returns_503_when_dependency_unavailable(self, mock_capture):
- """A cold cache during a persons-DB outage fails loud with a retryable 503, not a
- generic 500, and does not re-capture (the dependency layer already did, throttled).
-
- Drives the real cache→hypercache→endpoint chain (only the group-type fetch is
- patched), so a regressed source token would also surface here."""
- from posthog.models.group_type_mapping import GroupTypesUnavailable
-
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- # Cold cache (Redis + S3) so the read falls through to load_fn, whose group-type
- # fetch is the unavailable dependency. GroupTypesUnavailable subclasses
- # HyperCacheDependencyUnavailable, so this also confirms the endpoint catches the base.
- clear_flag_definition_caches(self.team)
- self.client.logout()
- with patch(
- "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",
- side_effect=GroupTypesUnavailable([self.team.project_id]),
- ):
- response = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
-
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
- self.assertEqual(
- response.json(),
- {
- "type": "service_unavailable",
- "code": "flags_dependency_unavailable",
- "detail": "Feature flag dependencies are temporarily unavailable; retry shortly",
- },
- )
- self.assertEqual(response.headers.get("Retry-After"), "30")
- mock_capture.assert_not_called()
-
- def test_local_evaluation_serves_cached_flags_when_dependency_unavailable(self):
- """A warm cache keeps serving the last-known-good payload during a persons-DB
- outage and never reaches load_fn — the PR's headline behavior. A regression that
- let a warm read fall through to the loader would 503 users who have good data
- cached.
-
- Drives the real cache→hypercache→endpoint chain; the loader is replaced only
- after the cache is warmed, so a warm hit must not invoke it."""
- from posthog.models.group_type_mapping import GroupTypesUnavailable
-
- from products.feature_flags.backend import local_evaluation
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- # Warm the cache (Redis + S3) with one successful read.
- clear_flag_definition_caches(self.team)
- self.client.logout()
- warm = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(warm.status_code, status.HTTP_200_OK)
-
- # The dependency now fails on any rebuild. Patching the loader directly proves a
- # warm hit never reaches it: if it did, this would raise → 503.
- with patch.object(
- local_evaluation,
- "_get_flags_response_for_local_evaluation",
- side_effect=GroupTypesUnavailable([self.team.project_id]),
- ) as mock_load:
- response = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
- self.assertEqual([flag["key"] for flag in data["flags"]], ["test-flag"])
- mock_load.assert_not_called()
-
- def test_local_evaluation_caching_with_cohorts(self):
- """Test caching with send_cohorts parameter."""
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
-
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag-cohort",
- filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- cache.clear()
-
- # Test cache for send_cohorts=true
- self.client.logout()
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # Check separate cache key for cohorts version (using HyperCache format)
- cache_key_cohorts = f"cache/teams/{self.team.id}/feature_flags/flags_with_cohorts.json"
- cache_key_regular = f"cache/teams/{self.team.id}/feature_flags/flags_without_cohorts.json"
-
- cached_cohorts = cache.get(cache_key_cohorts)
- cached_regular = cache.get(cache_key_regular)
-
- self.assertIsNotNone(cached_cohorts)
- self.assertIsNone(cached_regular) # Regular cache should not be populated yet
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_cache_invalidation_on_flag_change(self, mock_on_commit):
- """Test cache invalidation when feature flags change."""
- flag = FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
- )
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- cache.clear()
-
- # Populate cache
- self.client.logout()
- response = self.client.get(
- f"/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # Verify cache is populated and get original content
- cache_key = f"cache/teams/{self.team.id}/feature_flags/flags_without_cohorts.json"
- cache_key_cohorts = f"cache/teams/{self.team.id}/feature_flags/flags_with_cohorts.json"
- original_cache = cache.get(cache_key)
- self.assertIsNotNone(original_cache)
-
- # Update the flag (this should trigger cache update via signal handler)
- flag.filters = {"groups": [{"properties": [], "rollout_percentage": 100}]}
- flag.save()
-
- # Cache should now be updated with fresh data
- updated_cache = cache.get(cache_key)
- updated_cache_cohorts = cache.get(cache_key_cohorts)
- self.assertIsNotNone(updated_cache)
- self.assertIsNotNone(updated_cache_cohorts)
-
- # Cache content should have changed (flag filters should be updated)
- self.assertNotEqual(original_cache, updated_cache)
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_cache_invalidation_on_cohort_change(self, mock_on_commit):
- """Test cache invalidation when cohorts change."""
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
-
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag-cohort",
- filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- cache.clear()
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- # Populate both cache variants
- self.client.logout()
- response1 = self.client.get(
- f"/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- response2 = self.client.get(
- f"/api/feature_flag/local_evaluation?send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
-
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- self.assertEqual(response2.status_code, status.HTTP_200_OK)
-
- # Update the cohort (this should trigger cache update via signal handler)
- cohort.name = "Updated Test Cohort"
- cohort.save()
-
- # Make new requests to get potentially updated cache
- self.client.logout()
- updated_response1 = self.client.get(
- f"/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- updated_response2 = self.client.get(
- f"/api/feature_flag/local_evaluation?send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
-
- self.assertEqual(updated_response1.status_code, status.HTTP_200_OK)
- self.assertEqual(updated_response2.status_code, status.HTTP_200_OK)
-
- # Cache content should have changed (cohort name should be updated in the cohorts response)
- updated_response_without_cohorts = updated_response1.json()
- updated_response_with_cohorts = updated_response2.json()
-
- # For cohorts response, verify that cache was invalidated by checking the response content changed
- # The exact structure may not include cohort name, so let's just verify cache invalidation occurred
- # by checking that the responses are still valid but potentially different
- self.assertIn("flags", updated_response_without_cohorts)
- self.assertIn("flags", updated_response_with_cohorts)
-
- # Verify cohorts are included in the cohorts response
- if updated_response_with_cohorts.get("cohorts"):
- self.assertIsInstance(updated_response_with_cohorts["cohorts"], dict)
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_basic(self, mock_on_commit):
- """Test that local evaluation returns proper flag data."""
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- # Test the local evaluation endpoint
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- data = response.json()
- self.assertIn("flags", data)
- self.assertIn("group_type_mapping", data)
- self.assertIn("cohorts", data)
- self.assertEqual(len(data["flags"]), 1)
- self.assertEqual(data["flags"][0]["key"], "test-flag")
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_with_cohorts(self, mock_on_commit):
- """Test local evaluation with cohorts - verifies cohorts are properly included."""
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
-
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag-cohort",
- filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Test with send_cohorts parameter
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- data = response.json()
- self.assertIn("flags", data)
- self.assertIn("cohorts", data)
- self.assertEqual(len(data["flags"]), 1)
- self.assertEqual(data["flags"][0]["key"], "test-flag-cohort")
- self.assertEqual(len(data["cohorts"]), 1) # Should contain the cohort
- self.assertIn(str(cohort.id), data["cohorts"])
- self.assertEqual(
- data["cohorts"][str(cohort.id)],
- {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "value": "[email protected]",
- "type": "person",
- }
- ],
- }
- ],
- },
- )
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_functionality(self, mock_on_commit):
- """Test that local evaluation works without breaking existing functionality."""
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- # Basic test that local evaluation endpoint works
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- data = response.json()
- self.assertIn("flags", data)
- self.assertIn("group_type_mapping", data)
- self.assertIn("cohorts", data)
- self.assertEqual(len(data["flags"]), 1)
- self.assertEqual(data["flags"][0]["key"], "test-flag")
-
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_transformation_with_send_cohorts_true(self, mock_on_commit):
- """
- Test that responses with send_cohorts=true do NOT transform filters.
- """
- # Create cohort for testing
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
-
- # Create flag with single cohort reference (triggers transformation logic)
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag-cohort",
- filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
- },
- )
-
- # Get response with send_cohorts (should NOT transform filters)
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
-
- # Should have cohorts
- self.assertEqual(len(data["cohorts"]), 1)
- self.assertIn(str(cohort.id), data["cohorts"])
+ },
+ )
+ with_props_flag.last_called_at = datetime.now(UTC) - timedelta(days=1)
+ with_props_flag.save()
- # Verify that filters are NOT transformed (cohort reference preserved)
- flag = data["flags"][0]
- self.assertEqual(flag["key"], "test-flag-cohort")
+ # Test filtering by stale status
+ filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?active=STALE")
+ response = filtered_flags_list.json()
- # The filter should still contain the original cohort reference
- original_property = flag["filters"]["groups"][0]["properties"][0]
- self.assertEqual(original_property["type"], "cohort")
- self.assertEqual(original_property["value"], cohort.id)
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "stale_multivariate"
+ assert response["results"][0]["status"] == "STALE"
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_transformation_with_send_cohorts_false(self, mock_on_commit):
- """
- Test that responses without send_cohorts DO transform filters.
- """
- # Create cohort for testing
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
+ def test_get_flags_with_stale_filter_explicit_multivariate_null(self):
+ # Regression test: flags created via frontend have explicit multivariate: null
+ # The SQL filter should handle both missing key AND explicit null value
+ # No last_called_at so it falls back to config-based detection
+ with freeze_time("2024-01-01"):
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="stale_with_explicit_null",
+ active=True,
+ filters={
+ "groups": [{"rollout_percentage": 100, "properties": []}],
+ "multivariate": None, # Frontend explicitly sets this to null
+ "payloads": {},
+ },
+ )
- # Create flag with single cohort reference (triggers transformation logic)
+ # Create a non-stale flag with explicit multivariate: null (recent)
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
- key="test-flag-cohort",
+ key="recent_with_explicit_null",
+ active=True,
filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
+ "groups": [{"rollout_percentage": 100, "properties": []}],
+ "multivariate": None,
+ "payloads": {},
},
+ last_called_at=datetime.now(UTC) - timedelta(days=1),
)
- # Get response without send_cohorts (should transform filters)
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
+ filtered_flags_list = self.client.get("/api/projects/@current/feature_flags?active=STALE")
+ response = filtered_flags_list.json()
- # Should not have cohorts in response
- self.assertEqual(len(data["cohorts"]), 0)
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "stale_with_explicit_null"
+ assert response["results"][0]["status"] == "STALE"
- # Should have transformed filters (cohort properties expanded)
- flag = data["flags"][0]
- self.assertEqual(flag["key"], "test-flag-cohort")
+ @parameterized.expand(
+ [
+ (
+ "json_null_variant",
+ {
+ "groups": [{"rollout_percentage": 100, "properties": [], "variant": None}],
+ "multivariate": {
+ "variants": [
+ {"key": "test", "rollout_percentage": 50},
+ {"key": "test2", "rollout_percentage": 50},
+ ],
+ },
+ },
+ False, # JSON null variant is not a real override, should not be stale
+ ),
+ (
+ "empty_multivariate_object",
+ {
+ "groups": [{"rollout_percentage": 100, "properties": []}],
+ "multivariate": {},
+ },
+ True, # empty multivariate {} should be treated like no multivariate
+ ),
+ ]
+ )
+ def test_get_flags_with_stale_filter_jsonb_edge_cases(self, flag_key, flag_filters, expect_stale):
+ with freeze_time("2023-01-01"):
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key=flag_key,
+ active=True,
+ filters=flag_filters,
+ )
- # Check that response has transformed filters (should contain person properties)
- properties = flag["filters"]["groups"][0]["properties"]
- self.assertTrue(
- any(prop.get("type") == "person" for prop in properties),
- "Response should have transformed cohort to person properties",
- )
+ response = self.client.get("/api/projects/@current/feature_flags?active=STALE").json()
+ is_in_results = any(f["key"] == flag_key for f in response["results"])
+ assert is_in_results == expect_stale
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_cache_invalidation_on_feature_flag_delete(self, mock_on_commit):
- """Test that cache invalidates when FeatureFlag is deleted."""
- from products.feature_flags.backend.local_evaluation import (
- flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
+ def test_get_flags_with_evaluation_runtime_filter(self):
+ # Create flags with different evaluation runtimes
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="server_flag",
+ evaluation_runtime="server",
)
-
- # Create two feature flags
- flag1 = FeatureFlag.objects.create(
+ FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
- key="test-flag-1",
- name="Test Flag 1",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ key="client_flag",
+ evaluation_runtime="client",
)
-
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
- key="test-flag-2",
- name="Test Flag 2",
- filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ key="both_flag",
+ evaluation_runtime="both",
)
- # Clear caches to start fresh
- flag_definitions_hypercache.clear_cache(self.team)
- flag_definitions_without_cohorts_hypercache.clear_cache(self.team)
+ # Test filtering by server environment
+ filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=server")
+ response = filtered_flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "server_flag"
- # Populate both cache variants using use_cache parameter
- response1 = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- response2 = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts")
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- self.assertEqual(response2.status_code, status.HTTP_200_OK)
+ # Test filtering by client environment
+ filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=client")
+ response = filtered_flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "client_flag"
- # Verify both flags are in the responses
- data1 = response1.json()
- data2 = response2.json()
- self.assertEqual(len(data1["flags"]), 2)
- self.assertEqual(len(data2["flags"]), 2)
+ # Test filtering by both environment
+ filtered_flags_list = self.client.get(f"/api/projects/@current/feature_flags?evaluation_runtime=both")
+ response = filtered_flags_list.json()
+ assert len(response["results"]) == 1
+ assert response["results"][0]["key"] == "both_flag"
- flag_keys_1 = {flag["key"] for flag in data1["flags"]}
- flag_keys_2 = {flag["key"] for flag in data2["flags"]}
- self.assertEqual(flag_keys_1, {"test-flag-1", "test-flag-2"})
- self.assertEqual(flag_keys_2, {"test-flag-1", "test-flag-2"})
+ @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
+ def test_flag_is_cached_on_create_and_update(self, mock_on_commit):
+ # Ensure empty feature flag list
+ FeatureFlag.objects.all().delete()
- # Verify caches are populated by checking we get the same data on subsequent calls
- cached_response1 = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- cached_response2 = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts"
- )
- self.assertEqual(cached_response1.json(), data1)
- self.assertEqual(cached_response2.json(), data2)
+ feature_flag = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ data={
+ "name": "Beta feature",
+ "key": "beta-feature",
+ "filters": {
+ "aggregation_group_type_index": 0,
+ "groups": [{"rollout_percentage": 65}],
+ },
+ },
+ format="json",
+ ).json()
+
+ flags = get_feature_flags_for_team_in_cache(self.team.id)
- # Delete one of the feature flags - this should trigger cache invalidation via post_delete signal
- flag1.delete()
+ assert flags is not None
+ self.assertEqual(len(flags), 1)
+ self.assertEqual(flags[0].id, feature_flag["id"])
+ self.assertEqual(flags[0].key, "beta-feature")
+ self.assertEqual(flags[0].name, "Beta feature")
- # Get responses again - they should reflect the deletion (meaning cache was invalidated)
- updated_response1 = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}")
- updated_response2 = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts"
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",
+ {"name": "XYZ", "key": "red_button"},
)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- # Verify only one flag remains in both responses
- updated_data1 = updated_response1.json()
- updated_data2 = updated_response2.json()
- self.assertEqual(len(updated_data1["flags"]), 1)
- self.assertEqual(len(updated_data2["flags"]), 1)
- self.assertEqual(updated_data1["flags"][0]["key"], "test-flag-2")
- self.assertEqual(updated_data2["flags"][0]["key"], "test-flag-2")
+ flags = get_feature_flags_for_team_in_cache(self.team.id)
- # Verify responses changed from the original cached versions (flag count decreased)
- self.assertNotEqual(len(data1["flags"]), len(updated_data1["flags"]))
- self.assertNotEqual(len(data2["flags"]), len(updated_data2["flags"]))
+ assert flags is not None
+ self.assertEqual(len(flags), 1)
+ self.assertEqual(flags[0].id, feature_flag["id"])
+ self.assertEqual(flags[0].key, "red_button")
+ self.assertEqual(flags[0].name, "XYZ")
- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
- def test_local_evaluation_cache_invalidation_on_cohort_delete(self, mock_on_commit):
- """Test that cache invalidates when Cohort is deleted."""
- from products.feature_flags.backend.local_evaluation import (
- flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",
+ {"deleted": True},
)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- # Create a cohort
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
+ flags = get_feature_flags_for_team_in_cache(self.team.id)
- # Create a feature flag that references the cohort
- FeatureFlag.objects.create(
+ assert flags is not None
+ self.assertEqual(len(flags), 0)
+
+ def test_feature_flag_dashboard(self):
+ another_feature_flag = FeatureFlag.objects.create(
team=self.team,
+ name="some feature",
+ key="some-feature",
created_by=self.user,
- key="test-flag-cohort",
- name="Test Flag with Cohort",
- filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
- },
)
-
- # Clear caches to start fresh
- flag_definitions_hypercache.clear_cache(self.team)
- flag_definitions_without_cohorts_hypercache.clear_cache(self.team)
-
- # Populate cache with cohorts using use_cache parameter
- response = self.client.get(f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- data = response.json()
-
- # Verify cohort is present in the response
- self.assertIn("cohorts", data)
- self.assertIn(str(cohort.id), data["cohorts"])
-
- # Verify cache is populated by checking we get the same data on subsequent calls
- cached_response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts"
+ dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
+ relationship = FeatureFlagDashboards.objects.create(
+ feature_flag=another_feature_flag, dashboard_id=dashboard.pk
)
- self.assertEqual(cached_response.json(), data)
- # Delete the cohort - this should trigger cache invalidation via post_delete signal
- cohort.delete()
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk))
- # Get response again - cohort should be gone from the response
- updated_response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}&send_cohorts"
- )
- updated_data = updated_response.json()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ response_json = response.json()
- # Cohort should no longer exist in the response
- self.assertNotIn(str(cohort.id), updated_data.get("cohorts", {}))
+ self.assertEqual(len(response_json["analytics_dashboards"]), 1)
- # Verify response changed from the original cached version
- self.assertNotEqual(data["cohorts"], updated_data.get("cohorts", {}))
+ # check deleting the dashboard doesn't delete flag, but deletes the relationship
+ dashboard.delete()
+ another_feature_flag.refresh_from_db()
- @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_create_feature_flag_without_usage_dashboard(self, mock_report_user_action):
- response = self.client.post(
- f"/api/projects/{self.team.id}/feature_flags/",
- {"key": "no-usage-dashboard", "_should_create_usage_dashboard": False},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertEqual(response.json()["key"], "no-usage-dashboard")
- self.assertEqual(response.json()["name"], "")
- instance = FeatureFlag.objects.get(id=response.json()["id"])
- self.assertEqual(instance.key, "no-usage-dashboard")
- self.assertEqual(instance.name, "")
- assert instance.usage_dashboard is None, "Usage dashboard should not be created"
+ with self.assertRaises(FeatureFlagDashboards.DoesNotExist):
+ relationship.refresh_from_db()
- def test_local_evaluation_returns_etag_header(self):
- """Test that local_evaluation returns an ETag header in the response."""
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ def test_feature_flag_dashboard_patch(self):
+ another_feature_flag = FeatureFlag.objects.create(
team=self.team,
+ name="some feature",
+ key="some-feature",
created_by=self.user,
- key="test-flag-etag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
+ {"analytics_dashboards": [dashboard.pk]},
)
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
- response = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("ETag", response.headers)
- self.assertTrue(response.headers["ETag"].startswith('W/"'))
- self.assertTrue(response.headers["ETag"].endswith('"'))
- self.assertIn("Cache-Control", response.headers)
- self.assertEqual(response.headers["Cache-Control"], "private, must-revalidate")
-
- def test_local_evaluation_returns_304_when_etag_matches(self):
- """Test that local_evaluation returns 304 when If-None-Match header matches."""
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag-304",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
-
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk))
- # First request to get the ETag
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- etag = response1.headers["ETag"]
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ response_json = response.json()
- # Second request with If-None-Match header
- response2 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": etag,
- },
- )
- self.assertEqual(response2.status_code, status.HTTP_304_NOT_MODIFIED)
- self.assertEqual(response2.headers["ETag"], etag)
+ self.assertEqual(len(response_json["analytics_dashboards"]), 1)
- def test_local_evaluation_returns_200_when_etag_does_not_match(self):
- """Test that local_evaluation returns 200 with new data when ETag doesn't match."""
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ def test_feature_flag_dashboard_already_exists(self):
+ another_feature_flag = FeatureFlag.objects.create(
team=self.team,
+ name="some feature",
+ key="some-feature",
created_by=self.user,
- key="test-flag-new-etag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
+ {"analytics_dashboards": [dashboard.pk]},
)
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- # Request with non-matching ETag
- response = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": '"wrong-etag"',
- },
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/" + str(another_feature_flag.pk),
+ {"analytics_dashboards": [dashboard.pk]},
)
+
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("ETag", response.headers)
- self.assertIn("flags", response.json())
+ response_json = response.json()
- @patch("django.db.transaction.on_commit", side_effect=lambda f: f())
- def test_local_evaluation_etag_changes_when_flag_updated(self, mock_on_commit):
- """Test that ETag changes when a feature flag is modified."""
- FeatureFlag.objects.filter(team=self.team).delete()
+ self.assertEqual(len(response_json["analytics_dashboards"]), 1)
+
+ @freeze_time("2021-01-01")
+ @snapshot_clickhouse_queries
+ def test_creating_static_cohort(self):
flag = FeatureFlag.objects.create(
team=self.team,
+ filters={
+ "groups": [{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
+ "multivariate": None,
+ },
+ name="some feature",
+ key="some-feature",
created_by=self.user,
- key="test-flag-update",
- filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ _create_person(
+ team=self.team,
+ distinct_ids=[f"person1"],
+ properties={"key": "value"},
)
-
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
-
- # First request to get the initial ETag
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ _create_person(
+ team=self.team,
+ distinct_ids=[f"person2"],
+ properties={"key": "value2"},
+ )
+ _create_person(
+ team=self.team,
+ distinct_ids=[f"person3"],
+ properties={"key2": "value3"},
)
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- etag1 = response1.headers["ETag"]
+ flush_persons_and_events()
- # Update the flag
- flag.filters = {"groups": [{"properties": [], "rollout_percentage": 100}]}
- flag.save()
+ with (
+ snapshot_postgres_queries_context(self),
+ self.settings(
+ CELERY_TASK_ALWAYS_EAGER=True,
+ PERSON_ON_EVENTS_OVERRIDE=False,
+ PERSON_ON_EVENTS_V2_OVERRIDE=False,
+ ),
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/create_static_cohort_for_flag",
+ {},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- # Second request should have a different ETag
- response2 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ # fires an async task for computation, but celery runs sync in tests
+ cohort_id = response.json()["cohort"]["id"]
+ cohort = Cohort.objects.get(id=cohort_id)
+ self.assertEqual(
+ cohort.name,
+ "Users with feature flag some-feature enabled at 2021-01-01 00:00:00",
)
- self.assertEqual(response2.status_code, status.HTTP_200_OK)
- etag2 = response2.headers["ETag"]
+ self.assertEqual(cohort.count, 1)
- self.assertNotEqual(etag1, etag2)
+ response = self.client.get(f"/api/cohort/{cohort.pk}/persons")
+ self.assertEqual(len(response.json()["results"]), 1, response)
- def test_local_evaluation_etag_works_with_send_cohorts(self):
- """Test that ETag works correctly with send_cohorts parameter."""
- FeatureFlag.objects.filter(team=self.team).delete()
- cohort = Cohort.objects.create(
- team=self.team,
- name="Test Cohort",
- groups=[{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}],
- )
- FeatureFlag.objects.create(
+ def test_cant_update_early_access_flag_with_group(self):
+ feature_flag = FeatureFlag.objects.create(
team=self.team,
- created_by=self.user,
- key="test-flag-cohort-etag",
filters={
- "groups": [
- {
- "properties": [{"key": "id", "value": cohort.id, "type": "cohort"}],
- "rollout_percentage": 100,
- }
- ]
+ "aggregation_group_type_index": None,
+ "groups": [{"properties": [], "rollout_percentage": None}],
},
+ name="some feature",
+ key="some-feature",
+ created_by=self.user,
)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ EarlyAccessFeature.objects.create(
+ team=self.team,
+ name="earlyAccessFeature",
+ description="early access feature",
+ stage="alpha",
+ feature_flag=feature_flag,
)
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
+ update_data = {
+ "filters": {
+ "aggregation_group_type_index": 2,
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ }
+ }
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{feature_flag.id}/",
+ update_data,
+ format="json",
+ )
- # Request with send_cohorts
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation?send_cohorts",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertLessEqual(
+ {
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "Cannot use group aggregation in any condition set when the flag is linked to an Early Access Feature.",
+ }.items(),
+ response.json().items(),
)
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- etag_with_cohorts = response1.headers["ETag"]
- # Second request with same ETag should return 304
- response2 = self.client.get(
- "/api/feature_flag/local_evaluation?send_cohorts",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": etag_with_cohorts,
+ def test_feature_flag_includes_cohort_names(self):
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="test_cohort",
+ groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Alpha feature",
+ "key": "alpha-feature",
+ "filters": {
+ "groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}],
+ },
},
+ format="json",
)
- self.assertEqual(response2.status_code, status.HTTP_304_NOT_MODIFIED)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- # Request without send_cohorts should have different ETag
- response3 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ # Get the flag
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["filters"]["groups"][0]["properties"][0],
+ {
+ "key": "id",
+ "type": "cohort",
+ "value": cohort.pk,
+ "cohort_name": "test_cohort",
+ },
)
- self.assertEqual(response3.status_code, status.HTTP_200_OK)
- etag_without_cohorts = response3.headers["ETag"]
-
- # Different caches should have different ETags
- self.assertNotEqual(etag_with_cohorts, etag_without_cohorts)
- def test_local_evaluation_304_response_has_empty_body(self):
- """Test that 304 responses have empty body per HTTP spec."""
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ def test_feature_flag_includes_group_key_names(self):
+ GroupTypeMapping.objects.create(
+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
+ )
+ Group.objects.create(
team=self.team,
- created_by=self.user,
- key="test-flag-empty-body",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ group_key="org-uuid-1",
+ group_type_index=0,
+ group_properties={"name": "Acme Corp"},
+ version=0,
)
-
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ Group.objects.create(
+ team=self.team,
+ group_key="org-uuid-2",
+ group_type_index=0,
+ group_properties={"name": "Widget Inc"},
+ version=0,
)
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Group flag",
+ "key": "group-flag",
+ "filters": {
+ "aggregation_group_type_index": 0,
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": "$group_key",
+ "type": "group",
+ "value": ["org-uuid-1", "org-uuid-2"],
+ "operator": "exact",
+ "group_type_index": 0,
+ }
+ ]
+ }
+ ],
+ },
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.client.logout()
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
- # First request to get the ETag
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ prop = response.json()["filters"]["groups"][0]["properties"][0]
+ self.assertEqual(prop["key"], "$group_key")
+ self.assertEqual(
+ prop["group_key_names"],
+ {"org-uuid-1": "Acme Corp", "org-uuid-2": "Widget Inc"},
)
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
- etag = response1.headers["ETag"]
- # Second request with matching ETag should return 304 with empty body
- response2 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": etag,
+ def test_create_feature_flag_in_specific_folder(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ data={
+ "key": "my-test-flag-in-folder",
+ "name": "Test Flag in Folder",
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},
+ "_create_in_folder": "Special Folder/Flags",
},
+ format="json",
)
- self.assertEqual(response2.status_code, status.HTTP_304_NOT_MODIFIED)
- self.assertEqual(response2.content, b"")
+ assert response.status_code == 201, response.json()
+ flag_id = response.json()["id"]
+ assert flag_id is not None
- @parameterized.expand(
- [
- ("quoted", lambda etag: etag), # Send as-is with quotes
- ("unquoted", lambda etag: etag.removeprefix('W/"').removesuffix('"')), # Strip quotes
- ]
- )
- def test_local_evaluation_etag_header_parsing(self, _name, transform_etag):
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key=f"test-flag-{_name}",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ from posthog.models.file_system.file_system import FileSystem
+
+ fs_entry = FileSystem.objects.filter(team=self.team, ref=str(flag_id), type="feature_flag").first()
+ assert fs_entry, "No FileSystem entry found for this feature flag."
+ assert "Special Folder/Flags" in fs_entry.path, (
+ f"Expected 'Special Folder/Flags' in path, got: '{fs_entry.path}'"
)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ def test_feature_flag_experiment_set(self):
+ # Create a feature flag
+ feature_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="test-flag",
+ name="Test Flag",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
-
- clear_flag_definition_caches(self.team)
-
- self.client.logout()
+ # Initially, experiment_set should be empty
+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
+ assert response.status_code == 200
+ assert response.json()["experiment_set"] == []
- # Get initial ETag
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ # Create an active experiment linked to the flag
+ experiment = Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Test Experiment",
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),
)
- etag = response1.headers["ETag"]
- # ETag is returned as weak ETag, e.g., 'W/"abc123"'
- self.assertTrue(etag.startswith('W/"') and etag.endswith('"'))
- # Client sends ETag (transformed based on test case) - should match
- response2 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": transform_etag(etag),
- },
- )
- self.assertEqual(response2.status_code, status.HTTP_304_NOT_MODIFIED)
+ # experiment_set should now include the experiment ID
+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
+ assert response.status_code == 200
+ assert response.json()["experiment_set"] == [experiment.id]
- def test_local_evaluation_etag_idempotent_304_responses(self):
- """Test that same ETag consistently returns 304 across multiple requests."""
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ # Create a deleted experiment - should not be included
+ experiment2 = Experiment.objects.create(
team=self.team,
created_by=self.user,
- key="test-flag-idempotent",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ name="Another Experiment",
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1, 12, 1, 0, tzinfo=UTC),
)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
- )
+ # experiment_set should include both experiments
+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
+ assert response.status_code == 200
+ assert response.json()["experiment_set"] == [experiment.id, experiment2.id]
- from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches
+ # Delete the active experiments
+ experiment.deleted = True
+ experiment.save()
+ experiment2.deleted = True
+ experiment2.save()
- clear_flag_definition_caches(self.team)
+ # experiment_set should now be empty again
+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")
+ assert response.status_code == 200
+ assert response.json()["experiment_set"] == []
- self.client.logout()
+ def test_bulk_keys_valid_ids(self):
+ """Test that valid IDs return correct key mapping"""
+ # Create test flags
+ flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
+ flag2 = FeatureFlag.objects.create(key="test-flag-2", name="Test Flag 2", team=self.team, created_by=self.user)
+ flag3 = FeatureFlag.objects.create(key="test-flag-3", name="Test Flag 3", team=self.team, created_by=self.user)
- # Get initial ETag
- response1 = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={"authorization": f"Bearer {personal_api_key}"},
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [flag1.id, flag2.id, flag3.id]},
+ format="json",
)
- etag = response1.headers["ETag"]
-
- # Make 5 sequential requests with same ETag - all should return 304
- for i in range(5):
- response = self.client.get(
- "/api/feature_flag/local_evaluation",
- headers={
- "authorization": f"Bearer {personal_api_key}",
- "If-None-Match": etag,
- },
- )
- self.assertEqual(
- response.status_code,
- status.HTTP_304_NOT_MODIFIED,
- f"Request {i + 1} should return 304",
- )
- self.assertEqual(response.headers["ETag"], etag)
-
- def test_local_evaluation_secret_key_in_body_counter_not_incremented_for_header_auth(self):
- from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER
- self.team.secret_api_token = "phs_testtokenforheaderauth"
- self.team.save()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "keys" in data
+ assert data["keys"] == {
+ str(flag1.id): "test-flag-1",
+ str(flag2.id): "test-flag-2",
+ str(flag3.id): "test-flag-3",
+ }
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ def test_bulk_keys_empty_list(self):
+ """Test that empty ID list returns empty keys object"""
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": []},
+ format="json",
)
- self.client.logout()
- before = LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data == {"keys": {}}
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {self.team.secret_api_token}"},
+ def test_bulk_keys_invalid_ids(self):
+ """Test that invalid IDs (non-integers) return error"""
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": ["invalid", "not-a-number"]},
+ format="json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before)
- def test_local_evaluation_secret_key_in_body_counter_incremented_for_body_auth(self):
- from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ data = response.json()
+ assert "error" in data
+ assert "Invalid flag IDs provided" in data["error"]
- self.team.secret_api_token = "phs_testtokenforbodyauth"
- self.team.save()
+ def test_bulk_keys_mixed_valid_invalid_ids(self):
+ """Test that mixed valid/invalid IDs filter out invalid ones"""
+ flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [flag1.id, "invalid", 99999]}, # valid ID, invalid string, non-existent ID
+ format="json",
)
- self.client.logout()
- before = LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "keys" in data
+ assert data["keys"] == {str(flag1.id): "test-flag-1"}
+ assert "warning" in data
+ assert "Invalid flag IDs ignored: ['invalid']" in data["warning"]
- response = self.client.generic(
- "GET",
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- data=json.dumps({"secret_api_key": self.team.secret_api_token}),
- content_type="application/json",
+ def test_bulk_keys_nonexistent_ids(self):
+ """Test that non-existent flag IDs are filtered out"""
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [99999, 88888]}, # Non-existent IDs
+ format="json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before + 1)
- def test_local_evaluation_secret_key_in_body_counter_not_incremented_when_header_wins(self):
- from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER
-
- self.team.secret_api_token = "phs_testtokenforheaderwins"
- self.team.save()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data == {"keys": {}}
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ def test_bulk_keys_team_isolation(self):
+ """Test that flags from other teams are not returned"""
+ # Create flag in current team
+ flag1 = FeatureFlag.objects.create(
+ key="current-team-flag",
+ name="Current Team Flag",
team=self.team,
created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- self.client.logout()
- before = LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get()
-
- # Both header AND body have the secret token — header wins, body is ignored
- response = self.client.generic(
- "GET",
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- data=json.dumps({"secret_api_key": self.team.secret_api_token}),
- content_type="application/json",
- headers={"authorization": f"Bearer {self.team.secret_api_token}"},
+ # Create another team and flag
+ other_user = User.objects.create_user(email="[email protected]", password="password", first_name="Other")
+ other_organization, _, other_team = Organization.objects.bootstrap(other_user)
+ flag2 = FeatureFlag.objects.create(
+ key="other-team-flag",
+ name="Other Team Flag",
+ team=other_team,
+ created_by=other_user,
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before)
- @parameterized.expand(
- [
- ("header", "header"),
- ("body", "body"),
- ("query_string", "query_string"),
- ]
- )
- def test_local_evaluation_personal_api_key_source_counter(self, name, source):
- from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [flag1.id, flag2.id]},
+ format="json",
+ )
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "keys" in data
+ # Should only return flag from current team
+ assert data["keys"] == {str(flag1.id): "current-team-flag"}
+
+ def test_bulk_keys_deleted_flags(self):
+ """Test that deleted flags are not returned"""
+ flag1 = FeatureFlag.objects.create(key="active-flag", name="Active Flag", team=self.team, created_by=self.user)
+ flag2 = FeatureFlag.objects.create(
+ key="deleted-flag",
+ name="Deleted Flag",
team=self.team,
created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ deleted=True,
)
- personal_api_key = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [flag1.id, flag2.id]},
+ format="json",
)
- self.client.logout()
- before = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get()
-
- url = f"/api/feature_flag/local_evaluation?token={self.team.api_token}"
- if source == "header":
- response = self.client.get(
- url,
- headers={"authorization": f"Bearer {personal_api_key}"},
- )
- elif source == "body":
- response = self.client.generic( # type: ignore[assignment]
- "GET",
- url,
- data=json.dumps({"personal_api_key": personal_api_key}),
- content_type="application/json",
- )
- else:
- response = self.client.get(
- f"{url}&personal_api_key={personal_api_key}",
- )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "keys" in data
+ # Should only return non-deleted flag
+ assert data["keys"] == {str(flag1.id): "active-flag"}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get(),
- before + 1,
+ def test_bulk_keys_no_ids_param(self):
+ """Test that missing 'ids' parameter returns empty keys object"""
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {}, # No 'ids' parameter
+ format="json",
)
- def test_local_evaluation_personal_api_key_source_counter_not_incremented_for_secret_key(self):
- from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data == {"keys": {}}
- self.team.secret_api_token = "phs_testtokenforpaksource"
- self.team.save()
+ def test_bulk_keys_string_ids(self):
+ """Test that string representations of valid IDs work"""
+ flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)
- FeatureFlag.objects.filter(team=self.team).delete()
- FeatureFlag.objects.create(
- team=self.team,
- created_by=self.user,
- key="test-flag",
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ response = self.client.post(
+ f"/api/projects/@current/feature_flags/bulk_keys/",
+ {"ids": [str(flag1.id)]}, # String ID instead of integer
+ format="json",
)
- self.client.logout()
- before_header = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get()
- before_body = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "keys" in data
+ assert data["keys"] == {str(flag1.id): "test-flag-1"}
- response = self.client.get(
- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",
- headers={"authorization": f"Bearer {self.team.secret_api_token}"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get(), before_header
- )
- self.assertEqual(
- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get(), before_body
+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
+ def test_create_feature_flag_without_usage_dashboard(self, mock_report_user_action):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "no-usage-dashboard", "_should_create_usage_dashboard": False},
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["key"], "no-usage-dashboard")
+ self.assertEqual(response.json()["name"], "")
+ instance = FeatureFlag.objects.get(id=response.json()["id"])
+ self.assertEqual(instance.key, "no-usage-dashboard")
+ self.assertEqual(instance.name, "")
+ assert instance.usage_dashboard is None, "Usage dashboard should not be created"
def test_feature_flag_detail_actions_respect_access_control(self) -> None:
self.organization.available_product_features = [
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 61d763de59f5..da95c7f9c245 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -416,20 +416,6 @@ def get_flags_response_for_local_evaluation(team: Team, include_cohorts: bool) -
)
-def get_flags_response_if_none_match(
- team: Team, include_cohorts: bool, client_etag: str | None
-) -> tuple[dict | None, str | None, bool]:
- """
- Get flags response with ETag support for HTTP 304 responses.
-
- Returns: (data, etag, modified)
- - If client_etag matches current: (None, current_etag, False) - 304 case
- - Otherwise: (data, current_etag, True) - 200 case with full data
- """
- hypercache = flag_definitions_hypercache if include_cohorts else flag_definitions_without_cohorts_hypercache
- return hypercache.get_if_none_match(team, client_etag)
-
-
def _resolve_team(team: Team | int) -> Team | None:
"""Resolve a Team object or ID to a Team, returning None if not found."""
if isinstance(team, int):
diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.py
index 56367ae9ed23..4fd23b6c1050 100644
--- a/products/feature_flags/backend/test/test_local_evaluation.py
+++ b/products/feature_flags/backend/test/test_local_evaluation.py
@@ -1711,3 +1711,371 @@ class TestFlagDefinitionsCacheWithoutRedis(BaseTest):
result = update_flag_definitions_cache(self.team)
assert result is True
+
+
+class TestFlagDependencyChainTransformation(BaseTest):
+ """`dependency_chain` transformation in the local evaluation payload.
+
+ Ported from the removed Django-endpoint tests; exercises `_build_all_dependency_chains`
+ via the response builder directly, now that the HTTP endpoint is served by Rust.
+ """
+
+ def setUp(self):
+ super().setUp()
+ FeatureFlag.objects.filter(team=self.team).delete()
+ clear_flag_definition_caches(self.team)
+
+ def _find_flag(self, flags: list[dict], key: str) -> dict:
+ return next(flag for flag in flags if flag["key"] == key)
+
+ def test_complex_chain(self):
+ """Dependency transformation with a chain C -> B -> A (topologically sorted)."""
+ flag_a = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-a",
+ name="Flag A",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ flag_b = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-b",
+ name="Flag B",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-c",
+ name="Flag C",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ flag_c_data = self._find_flag(flags, "flag-c")
+ properties = flag_c_data["filters"]["groups"][0]["properties"]
+ flag_property = next(prop for prop in properties if prop["type"] == "flag")
+ # ID should be converted to key, with the full chain (topologically sorted)
+ self.assertEqual(flag_property["key"], "flag-b")
+ self.assertIn("dependency_chain", flag_property)
+ self.assertEqual(flag_property["dependency_chain"], ["flag-a", "flag-b"])
+
+ flag_b_data = self._find_flag(flags, "flag-b")
+ properties_b = flag_b_data["filters"]["groups"][0]["properties"]
+ flag_property_b = next(prop for prop in properties_b if prop["type"] == "flag")
+ self.assertEqual(flag_property_b["dependency_chain"], ["flag-a"])
+
+ def test_circular_dependency(self):
+ """A <-> B cycle yields empty dependency chains."""
+ flag_a = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-a",
+ name="Flag A",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ flag_b = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-b",
+ name="Flag B",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ flag_a.filters = {
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ }
+ flag_a.save()
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+ self.assertEqual(len(flags), 2)
+
+ flag_a_data = self._find_flag(flags, "flag-a")
+ flag_b_data = self._find_flag(flags, "flag-b")
+
+ properties_a = flag_a_data["filters"]["groups"][0]["properties"]
+ flag_properties_a = [prop for prop in properties_a if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties_a), 1)
+ self.assertEqual(flag_properties_a[0]["dependency_chain"], [])
+
+ properties_b = flag_b_data["filters"]["groups"][0]["properties"]
+ flag_properties_b = [prop for prop in properties_b if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties_b), 1)
+ self.assertEqual(flag_properties_b[0]["dependency_chain"], [])
+
+ def test_multiple_and_transitive_dependencies(self):
+ """C depends on A and B; D depends on C (transitive chain A,B,C)."""
+ flag_a = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-a",
+ name="Flag A",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ flag_b = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-b",
+ name="Flag B",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ flag_c = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-c",
+ name="Flag C",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_a.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
+ {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
+ {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-d",
+ name="Flag D",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_c.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
+ {"key": "country", "type": "person", "value": "US", "operator": "exact"},
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ flag_c_data = self._find_flag(flags, "flag-c")
+ properties = flag_c_data["filters"]["groups"][0]["properties"]
+ flag_properties = [prop for prop in properties if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties), 2)
+ self.assertEqual({prop["key"] for prop in flag_properties}, {"flag-a", "flag-b"})
+ for prop in flag_properties:
+ self.assertIn("dependency_chain", prop)
+ if prop["key"] == "flag-a":
+ self.assertEqual(prop["dependency_chain"], ["flag-a"])
+ elif prop["key"] == "flag-b":
+ self.assertEqual(prop["dependency_chain"], ["flag-b"])
+
+ flag_d_data = self._find_flag(flags, "flag-d")
+ properties_d = flag_d_data["filters"]["groups"][0]["properties"]
+ flag_properties_d = [prop for prop in properties_d if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties_d), 1)
+ self.assertEqual(flag_properties_d[0]["key"], "flag-c")
+ self.assertEqual(flag_properties_d[0]["dependency_chain"], ["flag-a", "flag-b", "flag-c"])
+
+ def test_self_dependency(self):
+ """A flag referencing itself yields an empty dependency chain."""
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="self-flag",
+ name="Self Flag",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "self-flag", "type": "flag", "value": True, "operator": "flag_evaluates_to"},
+ {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ self_flag_data = self._find_flag(flags, "self-flag")
+ properties = self_flag_data["filters"]["groups"][0]["properties"]
+ flag_properties = [prop for prop in properties if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties), 1)
+ self.assertEqual(flag_properties[0]["key"], "self-flag")
+ self.assertEqual(flag_properties[0]["dependency_chain"], [])
+
+ def test_self_referencing_circular_dependency(self):
+ """A -> B where B references itself: both chains empty."""
+ flag_b = FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-b",
+ name="Flag B",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "flag-b", "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-a",
+ name="Flag A",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(flag_b.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ flag_b_data = self._find_flag(flags, "flag-b")
+ properties_b = flag_b_data["filters"]["groups"][0]["properties"]
+ flag_properties_b = [prop for prop in properties_b if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties_b), 1)
+ self.assertEqual(flag_properties_b[0]["key"], "flag-b")
+ self.assertEqual(flag_properties_b[0]["dependency_chain"], [])
+
+ flag_a_data = self._find_flag(flags, "flag-a")
+ properties_a = flag_a_data["filters"]["groups"][0]["properties"]
+ flag_properties_a = [prop for prop in properties_a if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties_a), 1)
+ self.assertEqual(flag_properties_a[0]["key"], "flag-b")
+ self.assertEqual(flag_properties_a[0]["dependency_chain"], [])
+
+ def test_missing_dependency(self):
+ """A reference to a non-existent flag id keeps the id and yields an empty chain."""
+ non_existent_flag_id = "999999"
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="flag-a",
+ name="Flag A",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": non_existent_flag_id,
+ "type": "flag",
+ "value": True,
+ "operator": "flag_evaluates_to",
+ },
+ {"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"},
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ flag_a_data = self._find_flag(flags, "flag-a")
+ properties = flag_a_data["filters"]["groups"][0]["properties"]
+ flag_properties = [prop for prop in properties if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties), 1)
+ self.assertEqual(flag_properties[0]["key"], non_existent_flag_id)
+ self.assertEqual(flag_properties[0]["dependency_chain"], [])
+
+ def test_shared_dependencies(self):
+ """Multiple flags depending on the same shared flag each get the same chain."""
+ shared_flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="shared-dependency",
+ name="Shared Dependency",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ dependent_flags = []
+ for i in range(5):
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=f"dependent-flag-{i}",
+ name=f"Dependent Flag {i}",
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": str(shared_flag.id),
+ "type": "flag",
+ "value": True,
+ "operator": "flag_evaluates_to",
+ }
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+ dependent_flags.append(flag)
+
+ response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ flags = response["flags"]
+
+ for i, _flag in enumerate(dependent_flags):
+ flag_data = self._find_flag(flags, f"dependent-flag-{i}")
+ properties = flag_data["filters"]["groups"][0]["properties"]
+ flag_properties = [prop for prop in properties if prop["type"] == "flag"]
+ self.assertEqual(len(flag_properties), 1)
+ self.assertEqual(flag_properties[0]["key"], "shared-dependency")
+ self.assertEqual(flag_properties[0]["dependency_chain"], ["shared-dependency"])
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index d9bbf6b7bfea..a581beb0caa7 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1098,13 +1098,6 @@ export interface BulkUpdateTagsResponseApi {
skipped: BulkUpdateTagsErrorApi[]
}
-export type LocalEvaluationResponseApiGroupTypeMapping = { [key: string]: string }
-
-/**
- * Cohort definitions keyed by cohort ID. Each value is a property group structure with 'type' (OR/AND) and 'values' (array of property groups or property filters).
- */
-export type LocalEvaluationResponseApiCohorts = { [key: string]: unknown }
-
export type MinimalFeatureFlagApiFilters = { [key: string]: unknown }
export interface MinimalFeatureFlagApi {
@@ -1138,13 +1131,6 @@ export interface MinimalFeatureFlagApi {
readonly evaluation_contexts: readonly string[]
}
-export interface LocalEvaluationResponseApi {
- flags: MinimalFeatureFlagApi[]
- group_type_mapping: LocalEvaluationResponseApiGroupTypeMapping
- /** Cohort definitions keyed by cohort ID. Each value is a property group structure with 'type' (OR/AND) and 'values' (array of property groups or property filters). */
- cohorts: LocalEvaluationResponseApiCohorts
-}
-
export interface MyFlagsResponseApi {
feature_flag: MinimalFeatureFlagApi
value: unknown
@@ -1425,14 +1411,6 @@ export type FeatureFlagsEvaluationReasonsRetrieveParams = {
groups?: string
}
-export type FeatureFlagsLocalEvaluationRetrieveParams = {
- /**
- * Include cohorts in response
- * @nullable
- */
- send_cohorts?: boolean | null
-}
-
export type FeatureFlagsMyFlagsRetrieveParams = {
/**
* Groups for feature flag evaluation (JSON object string)
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 84b77098b178..dc026d52edcd 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -29,11 +29,9 @@ import type {
FeatureFlagsAllActivityRetrieveParams,
FeatureFlagsEvaluationReasonsRetrieveParams,
FeatureFlagsListParams,
- FeatureFlagsLocalEvaluationRetrieveParams,
FeatureFlagsMyFlagsRetrieveParams,
FlagValueResponseApi,
FlagValueValuesRetrieveParams,
- LocalEvaluationResponseApi,
MyFlagsResponseApi,
PaginatedFeatureFlagListApi,
PaginatedScheduledChangeListApi,
@@ -594,41 +592,6 @@ export const featureFlagsEvaluationReasonsRetrieve = async (
})
}
-export const getFeatureFlagsLocalEvaluationRetrieveUrl = (
- projectId: string,
- params?: FeatureFlagsLocalEvaluationRetrieveParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/feature_flags/local_evaluation/?${stringifiedParams}`
- : `/api/projects/${projectId}/feature_flags/local_evaluation/`
-}
-
-/**
- * Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
-
-If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.
- */
-export const featureFlagsLocalEvaluationRetrieve = async (
- projectId: string,
- params?: FeatureFlagsLocalEvaluationRetrieveParams,
- options?: RequestInit
-): Promise<LocalEvaluationResponseApi> => {
- return apiMutator<LocalEvaluationResponseApi>(getFeatureFlagsLocalEvaluationRetrieveUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
export const getFeatureFlagsMatchingIdsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/feature_flags/matching_ids/`
}
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 569b4d61bbde..27e6e82c5b3e 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -222,9 +222,6 @@ tools:
Debug why feature flags evaluate a certain way for a given user. Provide a distinct_id and optionally groups
to see each flag's evaluated value and the reason for that evaluation (e.g. condition_match,
no_condition_match, disabled).
- feature-flags-local-evaluation-retrieve:
- operation: feature_flags_local_evaluation_retrieve
- enabled: false
feature-flags-matching-ids-retrieve:
operation: feature_flags_matching_ids_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6ec96229ab5a..939659a61644 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21893,20 +21893,6 @@ export namespace Schemas {
readonly updated_at: string;
}
- export type LocalEvaluationResponseGroupTypeMapping = {[key: string]: string};
-
- /**
- * Cohort definitions keyed by cohort ID. Each value is a property group structure with 'type' (OR/AND) and 'values' (array of property groups or property filters).
- */
- export type LocalEvaluationResponseCohorts = { [key: string]: unknown };
-
- export interface LocalEvaluationResponse {
- flags: MinimalFeatureFlag[];
- group_type_mapping: LocalEvaluationResponseGroupTypeMapping;
- /** Cohort definitions keyed by cohort ID. Each value is a property group structure with 'type' (OR/AND) and 'values' (array of property groups or property filters). */
- cohorts: LocalEvaluationResponseCohorts;
- }
-
export interface LogsAlertFilters {
filterGroup?: PropertyGroupFilter | null;
serviceNames?: string[] | null;
@@ -48882,14 +48868,6 @@ export namespace Schemas {
groups?: string;
};
- export type FeatureFlagsLocalEvaluationRetrieveParams = {
- /**
- * Include cohorts in response
- * @nullable
- */
- send_cohorts?: boolean | null;
- };
-
export type FeatureFlagsMyFlagsRetrieveParams = {
/**
* Groups for feature flag evaluation (JSON object string)