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): surface real errors in the flag testing tab (#108975)

posthog[bot]1d83b7ded05b
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
index 36b6ae4a92d9..d681a6570bff 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx
@@ -99,22 +99,11 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
setIncludeTime,
setSelectedResultDistinctId,
clearTestForm,
- testFlagEvaluation,
- testAllDistinctIds,
+ submitTestEvaluation,
} = useActions(logic)
const isLoading = testEvaluationLoading || allEvaluationsLoading
- const handleSubmit = (): void => {
- if (hasMultipleDistinctIds) {
- // Evaluate every merged distinct ID in one go so their variants can be
- // compared side by side, rather than re-running the tool per ID.
- testAllDistinctIds({ flagId: featureFlag.id!, distinctIds: personDistinctIds, formData })
- } else {
- testFlagEvaluation({ flagId: featureFlag.id!, formData })
- }
- }
-
const hasConditions = !!result?.conditions?.length
// The batch row whose detail is currently expanded — the explicit selection, or
// the first row when nothing has been clicked yet (matches the activeResult selector).
@@ -270,7 +259,7 @@ export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFla
<LemonButton
type="primary"
loading={isLoading}
- onClick={handleSubmit}
+ onClick={() => submitTestEvaluation()}
disabledReason={!hasValidPerson ? 'Please select a person' : undefined}
>
{hasMultipleDistinctIds
diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
index 2969bd9af60a..9127356e5711 100644
--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
@@ -445,11 +445,7 @@ describe('featureFlagTestingLogic', () => {
})
})
- describe('groups validation through testFlagEvaluation', () => {
- // The invalid-groups cases fail the evaluation loader on purpose; kea-loaders would log each
- beforeEach(silenceKeaLoadersErrors)
- afterEach(resumeKeaLoadersErrors)
-
+ describe('form validation through submitTestEvaluation', () => {
it.each([
{ description: 'valid object succeeds', groups: '{"team": "backend"}', expectedError: null },
{ description: 'empty string succeeds', groups: '', expectedError: null },
@@ -466,13 +462,99 @@ describe('featureFlagTestingLogic', () => {
expectedError: 'groups must be a JSON object',
},
{ description: 'json number fails', groups: '42', expectedError: 'groups must be a JSON object' },
- ])('$description', async ({ groups, expectedError }) => {
+ { description: 'json null fails', groups: 'null', expectedError: 'groups must be a JSON object' },
+ {
+ description: 'malformed timestamp fails',
+ groups: '',
+ timestamp: '2024-01-01',
+ expectedError: 'Invalid timestamp format',
+ },
+ ])('$description', async ({ groups, timestamp = '', expectedError }) => {
+ logic.actions.setTestFormData({ distinct_id: 'p1', timestamp, groups })
+
+ if (expectedError) {
+ // Invalid input must never reach the loader, where kea-loaders reports it as an exception.
+ await expectLogic(logic, () => {
+ logic.actions.submitTestEvaluation()
+ })
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions(['testFlagEvaluation', 'testFlagEvaluationFailure'])
+ } else {
+ await expectLogic(logic, () => {
+ logic.actions.submitTestEvaluation()
+ }).toDispatchActions(['testFlagEvaluation', 'testFlagEvaluationSuccess'])
+ }
+
+ expect(logic.values.testError).toBe(expectedError)
+ })
+
+ it('runs the batch evaluation for a person with merged distinct IDs', async () => {
+ logic.actions.setSelectedPerson({
+ name: 'Jane Doe',
+ uuid: 'uuid-abc',
+ distinct_ids: ['user-123', 'user-456'],
+ })
+ logic.actions.setTestFormData({ distinct_id: 'user-123', timestamp: '', groups: '' })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitTestEvaluation()
+ })
+ .toDispatchActions([
+ logic.actionCreators.testAllDistinctIds({
+ flagId: 1,
+ distinctIds: ['user-123', 'user-456'],
+ formData: { distinct_id: 'user-123', timestamp: '', groups: '' },
+ }),
+ 'testAllDistinctIdsSuccess',
+ ])
+ .toNotHaveDispatchedActions(['testFlagEvaluation'])
+ })
+ })
+
+ describe('API error messages', () => {
+ // The failing responses fail the evaluation loader on purpose; kea-loaders would log each
+ beforeEach(silenceKeaLoadersErrors)
+ afterEach(resumeKeaLoadersErrors)
+
+ it.each([
+ {
+ description: 'maps a timestamp failure in the error field',
+ status: 500,
+ body: { error: 'Failed to build person properties at specified timestamp.' },
+ expectedError:
+ 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.',
+ },
+ {
+ description: 'maps an invalid timestamp in the error field',
+ status: 400,
+ body: { error: 'Invalid timestamp format.' },
+ expectedError: 'Invalid timestamp. Please select a valid date and time.',
+ },
+ {
+ description: 'keeps a specific timestamp reason as is',
+ status: 400,
+ body: { error: "Feature flag 'test-flag' did not exist at the specified timestamp." },
+ expectedError: "Feature flag 'test-flag' did not exist at the specified timestamp.",
+ },
+ {
+ description: 'maps a missing person in the detail field',
+ status: 404,
+ body: { detail: 'Person not found for person_id: abc' },
+ expectedError: 'Person not found. This person may not have existed at the selected timestamp.',
+ },
+ ])('$description', async ({ status, body, expectedError }) => {
+ useMocks({
+ post: {
+ '/api/projects/:team/feature_flags/1/test_evaluation': () => [status, body],
+ },
+ })
+
await expectLogic(logic, () => {
logic.actions.testFlagEvaluation({
flagId: 1,
- formData: { distinct_id: 'p1', timestamp: '', groups },
+ formData: { distinct_id: 'p1', timestamp: '', groups: '' },
})
- }).toFinishAllListeners()
+ }).toDispatchActions(['testFlagEvaluationFailure'])
expect(logic.values.testError).toBe(expectedError)
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
index 00135be1ae58..caebc4f9cc54 100644
--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts
@@ -45,8 +45,8 @@ const testEvaluationConcurrencyController = new ConcurrencyController(TEST_EVALU
// Build the request body for a single evaluation. Shared by the single-ID and
// batch paths so groups/timestamp are parsed and validated identically. Throws on
-// invalid groups or timestamp — callers let that fail the loader so the error
-// surfaces once via testError rather than per distinct ID.
+// invalid groups or timestamp. submitTestEvaluation checks the form with
+// testFormValidationError first, so this throw does not reach the loaders.
function buildEvaluationRequest(formData: TestFormData, distinctId: string): FeatureFlagTestEvaluationRequestApi {
const data: FeatureFlagTestEvaluationRequestApi = {}
@@ -70,34 +70,38 @@ function buildEvaluationRequest(formData: TestFormData, distinctId: string): Fea
return data
}
+// A loader that throws an error without an HTTP status is reported to error tracking,
+// so invalid user input must stop before a loader runs.
+function testFormValidationError(formData: TestFormData): string | null {
+ try {
+ buildEvaluationRequest(formData, '')
+ return null
+ } catch (e) {
+ return e instanceof Error ? e.message : String(e)
+ }
+}
+
// Map an evaluation failure to the user-facing message. Shared by the single-ID
// and batch failure handlers so both surface the same friendly rewrites.
function evaluationErrorMessage(error: string, errorObject?: unknown): string {
- const apiError = errorObject as ApiError
- if (apiError?.detail) {
- const errorDetail = apiError.detail
-
- if (errorDetail.includes('Failed to build person properties at specified timestamp')) {
- return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
- }
-
- if (errorDetail.includes('person') && errorDetail.includes('not found')) {
- return 'Person not found. This person may not have existed at the selected timestamp.'
- }
+ const apiError = errorObject as ApiError | undefined
+ // ApiError.message already holds the body's `error` field, which test_evaluation uses for its own failures.
+ const message = apiError?.detail || apiError?.message || error || ''
+ const lowerMessage = message.toLowerCase()
- if (errorDetail.includes('timestamp') || errorDetail.toLowerCase() === 'invalid timestamp') {
- return 'Invalid timestamp. Please select a valid date and time.'
- }
+ if (lowerMessage.includes('failed to build person properties at specified timestamp')) {
+ return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
+ }
- return errorDetail
+ if (lowerMessage.includes('person') && lowerMessage.includes('not found')) {
+ return 'Person not found. This person may not have existed at the selected timestamp.'
}
- const errorMessage = apiError?.message || error || ''
- if (errorMessage.includes('Failed to build person properties at specified timestamp')) {
- return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'
+ if (lowerMessage.includes('invalid timestamp') || apiError?.attr === 'timestamp') {
+ return 'Invalid timestamp. Please select a valid date and time.'
}
- return errorMessage || 'An unexpected error occurred while testing the feature flag'
+ return message || 'An unexpected error occurred while testing the feature flag'
}
function validateAndParseGroups(groups: string): Record<string, any> {
@@ -108,7 +112,7 @@ function validateAndParseGroups(groups: string): Record<string, any> {
try {
const parsed = JSON.parse(trimmed)
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('groups must be a JSON object')
}
return parsed
@@ -271,6 +275,9 @@ export interface featureFlagTestingLogicActions {
setTestFormData: (formData: Partial<TestFormData>) => {
formData: Partial<TestFormData>
}
+ submitTestEvaluation: () => {
+ value: true
+ }
testAllDistinctIds: ({
flagId,
distinctIds,
@@ -397,6 +404,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
setSelectedResultDistinctId: (distinctId: string | null) => ({ distinctId }),
clearBatchEvaluations: true,
clearTestForm: true,
+ submitTestEvaluation: true,
}),
loaders(({ values }) => ({
resolvedPersonDistinctIds: [
@@ -434,8 +442,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
distinctIds: string[]
formData: TestFormData
}) => {
- // Parse groups/timestamp once up front. A malformed form throws here and
- // fails the whole batch loudly (one testError) rather than N identical times.
+ // Parse groups/timestamp once up front, not once per distinct ID.
const baseData = buildEvaluationRequest(formData, '')
return await Promise.all(
@@ -484,8 +491,7 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
clearTestForm: () => null,
testFlagEvaluationFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) =>
evaluationErrorMessage(error, errorObject),
- // A batch failure means the shared form (groups/timestamp) was invalid — the
- // per-ID API errors are caught inside the loader and shown in the table.
+ // The loader catches per-ID API errors and shows them in the table.
testAllDistinctIdsFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) =>
evaluationErrorMessage(error, errorObject),
},
@@ -539,7 +545,22 @@ export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, props }) => ({
+ submitTestEvaluation: () => {
+ const formData = values.testFormData
+ const formError = testFormValidationError(formData)
+ if (formError) {
+ actions.setTestError(formError)
+ return
+ }
+ if (values.hasMultipleDistinctIds) {
+ // Evaluate every merged distinct ID in one go so their variants can be
+ // compared side by side, rather than re-running the tool per ID.
+ actions.testAllDistinctIds({ flagId: props.flagId, distinctIds: values.personDistinctIds, formData })
+ } else {
+ actions.testFlagEvaluation({ flagId: props.flagId, formData })
+ }
+ },
setSelectedPerson: ({ person, distinctId }) => {
// A different person invalidates any batch table from the previous one.
actions.clearBatchEvaluations()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 504a322e94aa..6a7fead922cc 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -3270,6 +3270,11 @@ class FeatureFlagTestEvaluationRequestSerializer(serializers.Serializer):
help_text="Groups for feature flag evaluation (JSON object, defaults to empty dict)",
)
+ def validate_groups(self, value: Any) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("groups must be a JSON object")
+ return value
+
def validate(self, attrs):
distinct_id = attrs.get("distinct_id")
person_id = attrs.get("person_id")
@@ -3315,7 +3320,11 @@ class FeatureFlagConditionAnalysisSerializer(serializers.Serializer):
rollout_excluded = serializers.BooleanField(
help_text="Whether this condition matched properties but was excluded due to rollout"
)
- variant = serializers.CharField(allow_null=True, help_text="Variant associated with this condition")
+ variant = serializers.CharField(
+ allow_null=True,
+ allow_blank=True,
+ help_text="Variant associated with this condition. Empty or null when the condition has no variant override.",
+ )
properties = FeatureFlagConditionPropertyAnalysisSerializer(
many=True, help_text="Analysis of each property in this condition"
)
@@ -5853,6 +5862,9 @@ class FeatureFlagViewSet(
flag_keys=[feature_flag.key],
internal_request_token=internal_token,
override_flags_definitions=override_definitions,
+ # A pooled connection that the service closed fails once with a reset, so retry it.
+ # The retry also covers a timeout, which doubles the worst-case wait to about 2x the proxy timeout.
+ max_retries=1,
)
# Extract the flag result from the Rust response
@@ -5947,9 +5959,75 @@ class FeatureFlagViewSet(
}
response_serializer = FeatureFlagTestEvaluationResponseSerializer(data=response_data)
- response_serializer.is_valid(raise_exception=True)
+ if not response_serializer.is_valid():
+ logger.error(
+ "Flag evaluation service response failed validation in test_evaluation",
+ extra={**log_context, "flag_key": feature_flag.key, "errors": response_serializer.errors},
+ )
+ capture_exception(serializers.ValidationError(response_serializer.errors))
+ return Response(
+ {"error": "Unexpected response format from flag evaluation service"},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
return Response(response_serializer.data)
+ except RETRYABLE_FLAGS_SERVICE_EXCEPTIONS as e:
+ logger.warning(
+ "Flag evaluation service unreachable for flag %s: %s", feature_flag.key, e, extra=log_context
+ )
+ return Response(
+ {"error": "Flag evaluation service temporarily unavailable. Please retry."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ except requests.exceptions.HTTPError as e:
+ service_status = e.response.status_code if e.response is not None else None
+ if service_status in (
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ status.HTTP_504_GATEWAY_TIMEOUT,
+ ):
+ # The service sends these statuses when it is overloaded or a dependency is down.
+ # They clear on retry like a connection error, so they are not captured as exceptions.
+ logger.warning(
+ "Flag evaluation service busy for flag %s: HTTP %s",
+ feature_flag.key,
+ service_status,
+ extra=log_context,
+ )
+ return Response(
+ {"error": "Flag evaluation service temporarily unavailable. Please retry."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ # Django builds the request body and the request serializer validates the user input,
+ # so any other error status, a 400 included, is a fault on our side or in the service.
+ logger.exception(
+ "Flag evaluation service returned an error for flag %s", feature_flag.key, extra=log_context
+ )
+ capture_exception(e)
+ return Response(
+ {"error": f"Flag evaluation service returned HTTP {service_status}. Please retry."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ except requests.exceptions.JSONDecodeError as e:
+ logger.exception(
+ "Flag evaluation service returned a body that is not JSON for flag %s",
+ feature_flag.key,
+ extra=log_context,
+ )
+ capture_exception(e)
+ return Response(
+ {"error": "Unexpected response format from flag evaluation service"},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ except requests.exceptions.RequestException as e:
+ logger.warning(
+ "Flag evaluation service call failed for flag %s: %s", feature_flag.key, e, extra=log_context
+ )
+ capture_exception(e)
+ return Response(
+ {"error": "Flag evaluation service temporarily unavailable. Please retry."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
except Exception as e:
logger.exception(
"Error evaluating flag '%s' for distinct_id='%s' person_id='%s' timestamp='%s': %s",
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 71847f821a6b..82d1c5fa3397 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -14871,6 +14871,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
# Caller-provided distinct_id resolves to the person → it must drive bucketing.
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)
@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")
@@ -15278,6 +15279,143 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
self.assertEqual(response.json()["error"], "Unexpected response format from flag evaluation service")
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
+ def test_test_evaluation_accepts_blank_condition_variant(self, mock_get_flags):
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ create_person(team=self.team, distinct_ids=["test-user"])
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": True,
+ "variant": None,
+ "reason": {"code": "condition_match", "condition_index": 0},
+ "metadata": {"payload": None},
+ "conditions": [
+ {
+ "index": 0,
+ "matched": True,
+ "explanation": "Condition matched",
+ "rollout_percentage": 100.0,
+ "rollout_excluded": False,
+ "variant": "",
+ "properties": [],
+ }
+ ],
+ }
+ }
+ }
+
+ 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)
+ self.assertEqual(response.json()["conditions"][0]["variant"], "")
+
+ @patch("products.feature_flags.backend.api.feature_flag.capture_exception")
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
+ def test_test_evaluation_invalid_condition_shape_returns_502(self, mock_get_flags, mock_capture_exception):
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ create_person(team=self.team, distinct_ids=["test-user"])
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": True,
+ "variant": None,
+ "reason": {"code": "condition_match", "condition_index": 0},
+ "metadata": {"payload": None},
+ "conditions": [{"index": 0, "explanation": "Condition matched", "properties": []}],
+ }
+ }
+ }
+
+ 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_502_BAD_GATEWAY)
+ self.assertEqual(response.json()["error"], "Unexpected response format from flag evaluation service")
+ mock_capture_exception.assert_called_once()
+
+ @parameterized.expand(
+ [
+ (
+ "connection_error",
+ requests.exceptions.ConnectionError("Connection reset by peer"),
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "Flag evaluation service temporarily unavailable. Please retry.",
+ False,
+ ),
+ (
+ "timeout",
+ requests.exceptions.Timeout("Read timed out"),
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "Flag evaluation service temporarily unavailable. Please retry.",
+ False,
+ ),
+ (
+ "service_unavailable",
+ requests.exceptions.HTTPError(response=MagicMock(status_code=503)),
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "Flag evaluation service temporarily unavailable. Please retry.",
+ False,
+ ),
+ (
+ "service_bad_request",
+ requests.exceptions.HTTPError(response=MagicMock(status_code=400)),
+ status.HTTP_502_BAD_GATEWAY,
+ "Flag evaluation service returned HTTP 400. Please retry.",
+ True,
+ ),
+ (
+ "service_server_error",
+ requests.exceptions.HTTPError(response=MagicMock(status_code=500)),
+ status.HTTP_502_BAD_GATEWAY,
+ "Flag evaluation service returned HTTP 500. Please retry.",
+ True,
+ ),
+ (
+ "malformed_json",
+ requests.exceptions.JSONDecodeError("Expecting value", "", 0),
+ status.HTTP_502_BAD_GATEWAY,
+ "Unexpected response format from flag evaluation service",
+ True,
+ ),
+ (
+ "chunked_encoding_error",
+ requests.exceptions.ChunkedEncodingError("Connection broken: incomplete read"),
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "Flag evaluation service temporarily unavailable. Please retry.",
+ True,
+ ),
+ ]
+ )
+ @patch("products.feature_flags.backend.api.feature_flag.capture_exception")
+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")
+ def test_test_evaluation_flags_service_failure(
+ self, _name, failure, expected_status, expected_error, expected_captured, mock_get_flags, mock_capture_exception
+ ):
+ mock_get_flags.side_effect = failure
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ create_person(team=self.team, distinct_ids=["test-user"])
+
+ 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, expected_status)
+ self.assertEqual(response.json()["error"], expected_error)
+ self.assertEqual(mock_capture_exception.called, expected_captured)
+
def test_test_evaluation_missing_distinct_id(self):
"""Test validation error when distinct_id is missing."""
flag = FeatureFlag.objects.create(
@@ -15295,8 +15433,14 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, 400)
- def test_test_evaluation_invalid_timestamp(self):
- """Test validation error with invalid timestamp format."""
+ @parameterized.expand(
+ [
+ ("invalid_timestamp", {"timestamp": "invalid"}, "timestamp"),
+ ("groups_as_string", {"groups": '{"company": "acme"}'}, "groups"),
+ ("groups_as_list", {"groups": ["acme"]}, "groups"),
+ ]
+ )
+ def test_test_evaluation_invalid_input(self, _name, payload, expected_attr):
flag = FeatureFlag.objects.create(
team=self.team,
name="Test Flag",
@@ -15306,11 +15450,12 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/{flag.id}/test_evaluation/",
- data={"distinct_id": "user123", "flag_key": "test-flag", "timestamp": "invalid"},
+ data={"distinct_id": "user123", **payload},
format="json",
)
self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], expected_attr)
@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")
@override_settings(INTERNAL_REQUEST_TOKEN="test-token")
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index f74dd729756e..ceb7bdb81f13 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1479,7 +1479,7 @@ export interface FeatureFlagConditionAnalysisApi {
/** Whether this condition matched properties but was excluded due to rollout */
rollout_excluded: boolean
/**
- * Variant associated with this condition
+ * Variant associated with this condition. Empty or null when the condition has no variant override.
* @nullable
*/
variant: string | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 275a60903ee1..c72e7b9b0123 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -48512,7 +48512,7 @@ export namespace Schemas {
/** Whether this condition matched properties but was excluded due to rollout */
rollout_excluded: boolean;
/**
- * Variant associated with this condition
+ * Variant associated with this condition. Empty or null when the condition has no variant override.
* @nullable
*/
variant: string | null;