Skip to content

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

fix(flags): explain the empty condition list in test evaluation for config version 2 (#123446)

Anders3197d197f5b4
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index a8d3233f3759..cfbe867c565a 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -683,6 +683,12 @@ def calculate_filter_size_bytes(filters: dict | None) -> int:
return len(filter_json.encode("utf-8"))
+V2_CONDITIONS_UNAVAILABLE_REASON = (
+ "Per-rule analysis is not available for flags with config version 2. "
+ "`condition_index` is the zero-based index of the deciding rule in `filters.rules`, or null when no rule decided."
+)
+
+
def _filter_person_properties_for_flag(
filters: dict[str, Any], person_properties: dict[str, Any], flag_key: str | None = None
) -> dict[str, Any]:
@@ -3471,7 +3477,11 @@ class FeatureFlagTestEvaluationResponseSerializer(serializers.Serializer):
),
)
condition_index = serializers.IntegerField(
- allow_null=True, help_text="The index of the condition that matched, if applicable"
+ allow_null=True,
+ help_text=(
+ "The index of the condition that matched, if applicable. For a flag with config version 2, the "
+ "zero-based index of the rule in `filters.rules` that decided the result, or null when no rule decided it."
+ ),
)
payload = serializers.JSONField(allow_null=True, help_text="Payload associated with the flag result, if any")
person_properties = serializers.DictField(
@@ -3486,7 +3496,18 @@ class FeatureFlagTestEvaluationResponseSerializer(serializers.Serializer):
),
)
conditions = FeatureFlagConditionAnalysisSerializer(
- many=True, help_text="Detailed analysis of each condition in the feature flag"
+ many=True,
+ help_text=(
+ "Detailed analysis of each condition in the feature flag. Always empty for a flag with config "
+ "version 2, which `conditions_unavailable_reason` then explains."
+ ),
+ )
+ conditions_unavailable_reason = serializers.CharField(
+ required=False,
+ help_text=(
+ "Present only when `conditions` is empty because the evaluated config has no per-condition "
+ "analysis. An empty list then does not mean the flag has no conditions or rules."
+ ),
)
@@ -5966,6 +5987,8 @@ class FeatureFlagViewSet(
"evaluation_distinct_id": response_evaluation_distinct_id,
"conditions": detailed_conditions,
}
+ if detect_config_format(evaluation_filters).kind == "v2":
+ response_data["conditions_unavailable_reason"] = V2_CONDITIONS_UNAVAILABLE_REASON
response_serializer = FeatureFlagTestEvaluationResponseSerializer(data=response_data)
if not response_serializer.is_valid():
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 f14f32a70cef..68647e50f86e 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -67,6 +67,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.api.feature_flag import (
FLAG_FILTERS_VIOLATION_COUNTER,
FLAG_FILTERS_WRITE_COUNTER,
+ V2_CONDITIONS_UNAVAILABLE_REASON,
FeatureFlagSerializer,
FeatureFlagStatusResponseSerializer,
_flag_write_source,
@@ -14547,6 +14548,10 @@ class TestFeatureFlagVersions(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
+_V1_ON = {"groups": [{"properties": [], "rollout_percentage": 100}]}
+_V2_OFF = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}
+
+
class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
@patch("products.feature_flags.backend.api.feature_flag.get_person_and_distinct_ids_for_identifier")
@@ -14603,6 +14608,115 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(data["evaluation_distinct_id"], "test-user")
self.assertEqual(mock_get_flags.call_args.kwargs["distinct_id"], "test-user")
self.assertEqual(mock_get_flags.call_args.kwargs["max_retries"], 1)
+ self.assertNotIn("conditions_unavailable_reason", data)
+
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
+ def test_test_evaluation_explains_missing_conditions_for_v2_flag(self, mock_get_flags):
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="rules-flag",
+ filters={
+ "version": 2,
+ "return_type": "string",
+ "default_value": "off",
+ "rules": [
+ {
+ "id": "rule-a",
+ "rule_type": "targeted_release",
+ "targeting": {"properties": []},
+ "value": "on",
+ }
+ ],
+ },
+ )
+ create_person(team=self.team, distinct_ids=["test-user"])
+ mock_get_flags.return_value = {
+ "flags": {
+ "rules-flag": {
+ "enabled": True,
+ "variant": "on",
+ "reason": {"code": "condition_match", "condition_index": 0},
+ "metadata": {"payload": None},
+ "conditions": [],
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual((data["result"], data["condition_index"], data["conditions"]), ("on", 0, []))
+ self.assertEqual(data["conditions_unavailable_reason"], V2_CONDITIONS_UNAVAILABLE_REASON)
+
+ @parameterized.expand(
+ [
+ ("v2_before_v1", _V2_OFF, _V1_ON, True),
+ ("v1_before_v2", _V1_ON, _V2_OFF, False),
+ ("v2_before_v2", _V2_OFF, {**_V2_OFF, "default_value": True}, True),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.build_person_properties_at_time", return_value={})
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
+ def test_test_evaluation_at_timestamp_reads_the_historical_config_format(
+ self, _name, historical_filters, current_filters, explains_conditions, mock_get_flags, _mock_build_props
+ ):
+ from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+
+ flag = FeatureFlag.objects.create(team=self.team, key="format-flag", filters=historical_filters, version=1)
+ flag.filters = current_filters
+ flag.version = 2
+ flag.save()
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=flag.id,
+ scope="FeatureFlag",
+ activity="updated",
+ detail=Detail(
+ name=flag.key,
+ changes=[
+ Change(type="FeatureFlag", action="changed", field="version", before=1, after=2),
+ Change(
+ type="FeatureFlag",
+ action="changed",
+ field="filters",
+ before=historical_filters,
+ after=current_filters,
+ ),
+ ],
+ ),
+ )
+ mock_get_flags.return_value = {
+ "flags": {
+ "format-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match", "condition_index": None},
+ "metadata": {},
+ "conditions": [],
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": flag.created_at.isoformat()},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ sent = mock_get_flags.call_args.kwargs["override_flags_definitions"]["format-flag"]
+ self.assertEqual(sent["filters"], historical_filters)
+ self.assertEqual("conditions_unavailable_reason" in response.json(), explains_conditions)
@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
@patch("products.feature_flags.backend.api.feature_flag.get_person_and_distinct_ids_for_identifier")
diff --git a/products/feature_flags/backend/test/test_version_history.py b/products/feature_flags/backend/test/test_version_history.py
index 256fa7cfab70..b56cf489faa2 100644
--- a/products/feature_flags/backend/test/test_version_history.py
+++ b/products/feature_flags/backend/test/test_version_history.py
@@ -267,6 +267,16 @@ class TestReconstructFlagAtVersion(BaseTest):
result = reconstruct_flag_at_version(flag, target_version=1, team_id=self.team.id)
assert result["filters"] == expected
+ def test_reconstruct_leaves_config_version_2_filters_unchanged(self):
+ v2_filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}
+ current_filters = {**v2_filters, "default_value": True}
+
+ flag = self._create_flag(filters=current_filters, version=1)
+ self._simulate_update(flag, {"filters": (v2_filters, current_filters)})
+
+ result = reconstruct_flag_at_version(flag, target_version=1, team_id=self.team.id)
+ assert result["filters"] == v2_filters
+
def test_reconstruct_field_cleared_to_none(self):
flag = self._create_flag(ensure_experience_continuity=True, version=1)
self._simulate_update(flag, {"ensure_experience_continuity": (True, None)})
diff --git a/products/feature_flags/backend/version_history.py b/products/feature_flags/backend/version_history.py
index a686b7129f78..4adbe1d616fa 100644
--- a/products/feature_flags/backend/version_history.py
+++ b/products/feature_flags/backend/version_history.py
@@ -5,6 +5,7 @@ from django.utils import timezone
from posthog.models.activity_logging.activity_log import ActivityLog, common_field_exclusions, field_exclusions
+from products.feature_flags.backend.facade.config import is_v1_config
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -165,11 +166,12 @@ def reconstruct_flag_at_version(
# Historical activity log entries may store filters in legacy shapes
# (None, {}, or missing "groups"). Normalize so the response shape is
- # predictable for API consumers.
+ # predictable for API consumers. Other config formats stay as stored: the v2 schema allows
+ # no extra keys, so adding "groups" would make the document invalid.
raw_filters = fields.get("filters")
if not raw_filters:
fields["filters"] = {"groups": []}
- elif "groups" not in raw_filters:
+ elif is_v1_config(raw_filters) and "groups" not in raw_filters:
fields["filters"] = {**raw_filters, "groups": []}
return _build_response(
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 9fbf9ccdf9a5..d021922fd435 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1784,7 +1784,7 @@ export interface FeatureFlagTestEvaluationResponseApi {
*/
reason_description?: string | null
/**
- * The index of the condition that matched, if applicable
+ * The index of the condition that matched, if applicable. For a flag with config version 2, the zero-based index of the rule in `filters.rules` that decided the result, or null when no rule decided it.
* @nullable
*/
condition_index: number | null
@@ -1797,8 +1797,10 @@ export interface FeatureFlagTestEvaluationResponseApi {
* @nullable
*/
evaluation_distinct_id: string | null
- /** Detailed analysis of each condition in the feature flag */
+ /** Detailed analysis of each condition in the feature flag. Always empty for a flag with config version 2, which `conditions_unavailable_reason` then explains. */
conditions: FeatureFlagConditionAnalysisApi[]
+ /** Present only when `conditions` is empty because the evaluated config has no per-condition analysis. An empty list then does not mean the flag has no conditions or rules. */
+ conditions_unavailable_reason?: string
}
export type FeatureFlagVersionResponseApiFilters = { [key: string]: unknown }
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0895143777f1..b07ae1e7212e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54717,7 +54717,7 @@ export namespace Schemas {
*/
reason_description?: string | null;
/**
- * The index of the condition that matched, if applicable
+ * The index of the condition that matched, if applicable. For a flag with config version 2, the zero-based index of the rule in `filters.rules` that decided the result, or null when no rule decided it.
* @nullable
*/
condition_index: number | null;
@@ -54730,8 +54730,10 @@ export namespace Schemas {
* @nullable
*/
evaluation_distinct_id: string | null;
- /** Detailed analysis of each condition in the feature flag */
+ /** Detailed analysis of each condition in the feature flag. Always empty for a flag with config version 2, which `conditions_unavailable_reason` then explains. */
conditions: FeatureFlagConditionAnalysis[];
+ /** Present only when `conditions` is empty because the evaluated config has no per-condition analysis. An empty list then does not mean the flag has no conditions or rules. */
+ conditions_unavailable_reason?: string;
}
export type FeatureFlagVersionResponseFilters = { [key: string]: unknown };