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.

feat(flags): return the field path of rules v2 write errors as attr (#109452)

Andersbc5cbb4ccbcd
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.md
index 410890391a81..c0af382ff5d3 100644
--- a/docs/internal/feature-flags/api-writes.md
+++ b/docs/internal/feature-flags/api-writes.md
@@ -84,6 +84,7 @@ A stored version 2 row that is not remote-configured and carries no encrypted pa
- `FeatureFlag.version` is required on every update and must equal the locked row's value. Unlike v1 there is no `original_flag` merge: a stale token is a conflict even when no individual field clashes. The token applies to disabling and deleting too.
- Identity resolution, validation and the enable check run against the locked row inside the existing update transaction. A stored document with an unsupported shape or semantics is rejected rather than replaced or enabled. Configuration and metadata byte limits apply to a replacement, so an oversized stored document can be edited back under a lowered limit; enabling requires the stored document to fit the current limits.
- Request bytes that repeat a JSON key are rejected before normalization can hide the duplicate. Non-finite numbers and percentages with more than two decimal places are rejected by the validator itself.
+- A rejected document returns the validator's first error: its path in `attr`, with nested keys joined by `__` as for nested serializer errors (for example `filters__rules__0__value` for `filters.rules[0].value`, or `filters` for the whole document), the bare message in `detail`, and its `code` (the handler renders `invalid` as `invalid_input`). An unknown field returns `attr: filters` with its path in `detail`, because the path ends in the client's key name and could read as another field's path. A repeated JSON key returns `attr: null`, because the key can be anywhere in the request body.
- An enabled flag-write approval policy (`feature_flag.enable`, `feature_flag.disable` or `feature_flag.update`, on the team or its organization) denies every version 2 write, disable and delete included, and an approved change cannot be applied to a version 2 row: PH-WRITE-APPROVAL owns that path. Nothing here creates a pending change request; to disable a version 2 flag under such a policy, disable the policy first.
The final policy lookup and flag mutation share an organization-scoped transaction lock with policy creation and updates, so a policy cannot be enabled between that lookup and commit.
Flag writes take the lock in shared mode so different flags can update concurrently; policy writes take it in exclusive mode.
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
index 2528d35942d6..ec303a61a993 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
@@ -116,20 +116,45 @@ describe('featureFlagRulesV2EditorLogic', () => {
'There is already a feature flag with this key.',
],
[
- { detail: 'filters.rules[1].rollout_percentage: Must be at most 100.' },
+ { attr: 'filters__rules__1__rollout_percentage', detail: 'Must be at most 100.' },
'filters.rules[1].rollout_percentage',
'Must be at most 100.',
],
[
- { detail: 'filters.rules[0].targeting.properties[0].value: Must be a string.' },
+ { attr: 'filters__rules__0__targeting__properties__0__value', detail: 'Must be a string.' },
'filters.rules[0].targeting',
'filters.rules[0].targeting.properties[0].value: Must be a string.',
],
[
- { detail: 'filters.rules[2].id: Rule ids are server-assigned.' },
+ { attr: 'filters__rules__2__id', detail: 'Rule ids are server-assigned.' },
'filters.rules[2]',
'filters.rules[2].id: Rule ids are server-assigned.',
],
+ [
+ { attr: 'filters__default_value', detail: 'Must be true or false.' },
+ 'filters.default_value',
+ 'Must be true or false.',
+ ],
+ [
+ { attr: 'filters__rules', detail: 'At most 100 rules are allowed.' },
+ null,
+ 'filters.rules: At most 100 rules are allowed.',
+ ],
+ [
+ { attr: 'filters__version', detail: 'This field is required.' },
+ null,
+ 'filters.version: This field is required.',
+ ],
+ [
+ { attr: 'filters', code: 'unknown_field', detail: 'filters.rules__0__value: Unknown field.' },
+ null,
+ 'filters.rules__0__value: Unknown field.',
+ ],
+ [
+ { attr: 'filters', code: 'unknown_field', detail: 'filters.rules[2].foo: Unknown field.' },
+ 'filters.rules[2]',
+ 'filters.rules[2].foo: Unknown field.',
+ ],
[
{ attr: 'tags', detail: 'Add at least one tag. This project requires new feature flags to be tagged.' },
'tags',
@@ -362,7 +387,8 @@ describe('featureFlagRulesV2EditorLogic', () => {
const toastError = jest.spyOn(lemonToast, 'error')
jest.spyOn(api, 'update').mockRejectedValue({
status: 400,
- detail: 'filters.rules[1].rollout_percentage: Must be at most 100.',
+ attr: 'filters__rules__1__rollout_percentage',
+ detail: 'Must be at most 100.',
})
await expectLogic(logic, () => logic.actions.saveRulesV2Flag())
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
index 5e029860b515..21fb51d0282f 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
@@ -181,15 +181,18 @@ function editorField(path: string): string | null {
return rule[2] && RULE_FIELDS.has(rule[2]) ? `filters.rules[${rule[1]}].${rule[2]}` : `filters.rules[${rule[1]}]`
}
-/** Field errors arrive with `attr`; document errors arrive as `detail` prefixed with their `filters…` path. */
+/** `attr` joins nested keys with `__`; a document path that is not the input's own stays in the message. */
export function rulesV2SaveError(error: any): RulesV2SaveError {
const detail = readableErrorMessage(error) ?? 'This flag could not be saved.'
- const prefixed = error?.attr ? null : /^(filters(?:\.\w+|\[\d+\])*): (.+)$/s.exec(detail)
- const path: string | null = error?.attr || prefixed?.[1] || null
+ if (error?.code === 'unknown_field') {
+ // The server keeps client key names out of `attr`, but this editor sends only its own keys.
+ return { field: editorField(detail.split(': ', 1)[0]), message: detail }
+ }
+ const attr: string | null = error?.attr || null
+ const path = attr ? attr.replace(/__(\d+)(?=__|$)/g, '[$1]').replace(/__/g, '.') : null
const field = path ? editorField(path) : null
- // Only an exact field match drops the path; everything else is shown verbatim.
- const exact = field !== null && field === path
- return { field, message: exact && prefixed ? prefixed[2] : detail }
+ const named = path !== null && path !== field && (field !== null || path.startsWith('filters.'))
+ return { field, message: named ? `${path}: ${detail}` : detail }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 72d71cad3d18..fff9c5cfe466 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -35,6 +35,7 @@ from rest_framework import exceptions, request, serializers, status, viewsets
from rest_framework.exceptions import ErrorDetail
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
+from rest_framework.settings import api_settings
from posthog.schema import ProductKey
@@ -1928,13 +1929,24 @@ class FeatureFlagSerializer(
def _v2_validation_error(exc: ConfigValidationError) -> serializers.ValidationError:
"""Translate pure validation errors into this endpoint's error envelope.
- Same shape as the v1 structural tier: one detail per field error, prefixed with its
- `filters....` path and carrying the validator's code. The validator's details never
- echo config values, seeds or metadata.
+ Keyed by each error's path in the handler's nested-key form (`filters.rules[0].value`
+ becomes `filters__rules__0__value`, as for nested serializer errors), so the response's
+ `attr` is that path and its `detail` the bare message, with the validator's code. The
+ handler renders the first key, which is the validator's first error. The details never echo
+ config values, seeds or metadata. An unknown field's path ends in the client's key name, which
+ can itself read as a real field's path, so that error is keyed by `filters` and its path goes
+ in the detail. An error with no path, such as a repeated key, renders with `attr: null`.
"""
- return serializers.ValidationError(
- [ErrorDetail(f"{error.attr}: {error.detail}", code=error.code) for error in exc.errors]
- )
+ errors: dict[str, list[ErrorDetail]] = {}
+ for error in exc.errors:
+ if error.attr is None:
+ attr, detail = api_settings.NON_FIELD_ERRORS_KEY, error.detail
+ elif error.code == "unknown_field":
+ attr, detail = "filters", f"{error.attr}: {error.detail}"
+ else:
+ attr, detail = re.sub(r"\[(\d+)\]", r"__\1", error.attr).replace(".", "__"), error.detail
+ errors.setdefault(attr, []).append(ErrorDetail(detail, code=error.code))
+ return serializers.ValidationError(errors)
def _apply_v2_update(self, locked_instance: FeatureFlag, validated_data: dict, locked_version: int) -> None:
"""Enforce the v2 row-version token and resolve the final document under the lock.
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
index beb3345729f4..25479951a2ff 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
@@ -261,12 +261,12 @@ class TestAdmittedV2Creation(AdmittedV2TestCase):
@parameterized.expand(
[
- ("string_bool_default", "string", True, "compact", "filters.default_value"),
- ("string_empty_value", "string", None, "", "filters.rules[0].value"),
- ("number_string_value", "number", 0, "1", "filters.rules[0].value"),
- ("number_unsafe_integer", "number", 2**53, 1, "filters.default_value"),
- ("object_array_value", "object", None, [1], "filters.rules[0].value"),
- ("object_too_deep", "object", None, {"a": nested_list(20)}, "filters.rules[0].value"),
+ ("string_bool_default", "string", True, "compact", "filters__default_value"),
+ ("string_empty_value", "string", None, "", "filters__rules__0__value"),
+ ("number_string_value", "number", 0, "1", "filters__rules__0__value"),
+ ("number_unsafe_integer", "number", 2**53, 1, "filters__default_value"),
+ ("object_array_value", "object", None, [1], "filters__rules__0__value"),
+ ("object_too_deep", "object", None, {"a": nested_list(20)}, "filters__rules__0__value"),
]
)
def test_values_that_do_not_match_the_return_type_are_rejected(
@@ -276,7 +276,7 @@ class TestAdmittedV2Creation(AdmittedV2TestCase):
submitted["default_value"] = default
response = self.post_flag({"key": "typed-v2", "filters": submitted})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"].startswith(f"{attr}: "), response.json()
+ assert response.json()["attr"] == attr, response.json()
assert not FeatureFlag.objects.filter(team=self.team, key="typed-v2").exists()
def test_active_on_create_is_rejected_not_downgraded(self) -> None:
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
index cf04b000895c..b970577134e0 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
@@ -351,7 +351,10 @@ class TestAdmittedV2Updates(AdmittedV2TestCase):
stored = copy.deepcopy(flag.filters)
response = self.patch_flag(flag, {"version": 3, "filters": document})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == "filters.return_type: Cannot be changed after the flag is created."
+ assert (response.json()["attr"], response.json()["detail"]) == (
+ "filters__return_type",
+ "Cannot be changed after the flag is created.",
+ )
flag.refresh_from_db()
assert (flag.filters, flag.version) == (stored, 3)
@@ -730,12 +733,19 @@ def string_config(value: str, default: str | None, rule_id: str | None = RULE_A)
RESERVED_STRING_VALUES = [
- ("rule_value", "$false", None, "filters.rules[0].value: Must be a non-empty string other than $false or $true."),
+ (
+ "rule_value",
+ "$false",
+ None,
+ "filters__rules__0__value",
+ "Must be a non-empty string other than $false or $true.",
+ ),
(
"default_value",
"compact",
"$true",
- "filters.default_value: Must be a non-empty string other than $false or $true, or null.",
+ "filters__default_value",
+ "Must be a non-empty string other than $false or $true, or null.",
),
]
@@ -744,19 +754,25 @@ class TestWriterOnlyRules(AdmittedV2TestCase):
"""The writer reserves `$false` and `$true` as string values; the caches accept them, so a stored one stays replaceable."""
@parameterized.expand(RESERVED_STRING_VALUES)
- def test_create_rejects_a_reserved_value(self, _name: str, value: str, default: str | None, detail: str) -> None:
+ def test_create_rejects_a_reserved_value(
+ self, _name: str, value: str, default: str | None, attr: str, detail: str
+ ) -> None:
with admit_v2(self.team.id, creation=True):
response = self.post_flag({"key": "new-v2", "filters": string_config(value, default, rule_id=None)})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert (response.json()["code"], response.json()["detail"]) == ("invalid_input", detail)
+ body = response.json()
+ assert (body["code"], body["attr"], body["detail"]) == ("invalid_input", attr, detail)
assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
@parameterized.expand(RESERVED_STRING_VALUES)
- def test_update_rejects_a_reserved_value(self, _name: str, value: str, default: str | None, detail: str) -> None:
+ def test_update_rejects_a_reserved_value(
+ self, _name: str, value: str, default: str | None, attr: str, detail: str
+ ) -> None:
flag = self.flag(string_config("compact", None))
response = self.patch_flag(flag, {"version": 3, "filters": string_config(value, default)})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert (response.json()["code"], response.json()["detail"]) == ("invalid_input", detail)
+ body = response.json()
+ assert (body["code"], body["attr"], body["detail"]) == ("invalid_input", attr, detail)
flag.refresh_from_db()
assert (flag.filters, flag.version) == (string_config("compact", None), 3)
@@ -765,8 +781,9 @@ class TestWriterOnlyRules(AdmittedV2TestCase):
flag = self.flag(stored, active=False)
response = self.patch_flag(flag, {"version": 3, "active": True})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == (
- "filters: This flag's stored configuration cannot be enabled through this API."
+ assert (response.json()["attr"], response.json()["detail"]) == (
+ "filters",
+ "This flag's stored configuration cannot be enabled through this API.",
)
flag.refresh_from_db()
assert (flag.active, flag.filters, flag.version) == (False, stored, 3)
@@ -808,9 +825,10 @@ class TestWriterRegexPatterns(AdmittedV2TestCase):
filters = regex_config(COMPILABLE, (operator, pattern), rule_id=None)
response = self.post_flag({"key": "new-v2", "filters": filters})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert (response.json()["code"], response.json()["detail"]) == (
+ assert (response.json()["code"], response.json()["attr"], response.json()["detail"]) == (
"invalid_input",
- "filters.rules[0].targeting.properties[1].value: Must be a valid regular expression.",
+ "filters__rules__0__targeting__properties__1__value",
+ "Must be a valid regular expression.",
)
assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
@@ -819,8 +837,9 @@ class TestWriterRegexPatterns(AdmittedV2TestCase):
flag = self.flag(regex_config(COMPILABLE))
response = self.patch_flag(flag, {"version": 3, "filters": regex_config(COMPILABLE, (operator, pattern))})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == (
- "filters.rules[0].targeting.properties[1].value: Must be a valid regular expression."
+ assert (response.json()["attr"], response.json()["detail"]) == (
+ "filters__rules__0__targeting__properties__1__value",
+ "Must be a valid regular expression.",
)
flag.refresh_from_db()
assert (flag.filters, flag.version) == (regex_config(COMPILABLE), 3)
@@ -831,8 +850,9 @@ class TestWriterRegexPatterns(AdmittedV2TestCase):
flag = self.flag(regex_config(*held))
response = self.patch_flag(flag, {"version": 3, "filters": regex_config(*held, ("regex", "("))})
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == (
- "filters.rules[0].targeting.properties[2].value: Must be a valid regular expression."
+ assert (response.json()["attr"], response.json()["detail"]) == (
+ "filters__rules__0__targeting__properties__2__value",
+ "Must be a valid regular expression.",
)
replacement = regex_config(*held, description="Reviewed")
@@ -873,6 +893,7 @@ class TestV2RequestBytes(AdmittedV2TestCase):
stored = copy.deepcopy(flag.filters)
response = self.post_bytes(flag, body)
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert (response.json()["code"], response.json()["attr"]) == ("invalid_input", None)
assert f'"{key}"' in response.json()["detail"]
flag.refresh_from_db()
assert flag.filters == stored
@@ -937,3 +958,45 @@ class TestV2RequestBytes(AdmittedV2TestCase):
assert response.status_code == status.HTTP_400_BAD_REQUEST
flag.refresh_from_db()
assert flag.version == 3
+
+
+class TestV2ValidationErrors(AdmittedV2TestCase):
+ @parameterized.expand(
+ [
+ # Create fails in validate() and update in update(); DRF wraps the two differently.
+ ("create", "invalid_input", "filters__rules__0__value", "Must be true or false."),
+ ("update", "invalid_input", "filters__rules__0__value", "Must be true or false."),
+ (
+ "enable",
+ "unsupported",
+ "filters",
+ "This flag's stored configuration cannot be enabled through this API.",
+ ),
+ ]
+ )
+ def test_the_response_names_the_first_invalid_field_in_attr(
+ self, operation: str, code: str, attr: str, detail: str
+ ) -> None:
+ if operation == "create":
+ filters = config(rollout(rule_id=None, seed=None, value="yes", rollout_percentage=150))
+ with admit_v2(self.team.id, creation=True):
+ response = self.post_flag({"key": "new-v2", "filters": filters})
+ elif operation == "update":
+ filters = config(rollout(value="yes", rollout_percentage=150))
+ response = self.patch_flag(self.flag(), {"version": 3, "filters": filters})
+ else:
+ response = self.patch_flag(
+ self.flag({"version": 2, "rules": "broken"}, active=False), {"version": 3, "active": True}
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json() == {"type": "validation_error", "code": code, "detail": detail, "attr": attr}
+
+ def test_an_unknown_field_keeps_its_name_out_of_attr(self) -> None:
+ response = self.patch_flag(self.flag(), {"version": 3, "filters": config(rollout(), rules__0__value=True)})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json() == {
+ "type": "validation_error",
+ "code": "unknown_field",
+ "detail": "filters.rules__0__value: Unknown field.",
+ "attr": "filters",
+ }
diff --git a/products/feature_flags/backend/facade/config_validation.py b/products/feature_flags/backend/facade/config_validation.py
index 5ec97f7c216d..56755b0fa1ca 100644
--- a/products/feature_flags/backend/facade/config_validation.py
+++ b/products/feature_flags/backend/facade/config_validation.py
@@ -147,13 +147,14 @@ class ConfigError:
# Presentation text. Never carries property values, seeds or metadata: the path in
# ``attr`` identifies the field and the code identifies the problem.
detail: str
- # Dotted path from the flag's ``filters`` field, e.g. ``filters.rules[2].seed``.
- attr: str
+ # Dotted path from the flag's ``filters`` field, e.g. ``filters.rules[2].seed``; None for a repeated key.
+ attr: str | None
class ConfigValidationError(ValueError):
def __init__(self, errors: list[ConfigError]) -> None:
- super().__init__(f"{errors[0].attr}: {errors[0].detail}")
+ first = errors[0]
+ super().__init__(first.detail if first.attr is None else f"{first.attr}: {first.detail}")
self.errors = tuple(errors)
diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.py
index 86d2a066a282..718ff49086fc 100644
--- a/products/feature_flags/backend/facade/config_writes.py
+++ b/products/feature_flags/backend/facade/config_writes.py
@@ -112,7 +112,7 @@ def reject_duplicate_json_keys(body: bytes) -> None:
for key, value in pairs:
if key in result:
raise ConfigValidationError(
- [ConfigError(code="invalid", detail=f"Must not repeat the key {json.dumps(key)}.", attr="filters")]
+ [ConfigError(code="invalid", detail=f"Must not repeat the key {json.dumps(key)}.", attr=None)]
)
result[key] = value
return result
@@ -122,9 +122,7 @@ def reject_duplicate_json_keys(body: bytes) -> None:
except ConfigValidationError:
raise
except ValueError as exc:
- raise ConfigValidationError(
- [ConfigError(code="invalid", detail="Must not repeat a key.", attr="filters")]
- ) from exc
+ raise ConfigValidationError([ConfigError(code="invalid", detail="Must not repeat a key.", attr=None)]) from exc
def resolve_identity(submitted: object, *, stored: Mapping[str, Any]) -> dict[str, Any]:
diff --git a/products/feature_flags/backend/test/test_facade_config_validation.py b/products/feature_flags/backend/test/test_facade_config_validation.py
index 5d6a2a192f76..5aa3e34115f3 100644
--- a/products/feature_flags/backend/test/test_facade_config_validation.py
+++ b/products/feature_flags/backend/test/test_facade_config_validation.py
@@ -96,7 +96,7 @@ def without(document: dict[str, Any], key: str) -> dict[str, Any]:
return {name: value for name, value in document.items() if name != key}
-def errors_of(document: object, limits: ValidationLimits = LIMITS) -> list[tuple[str, str]]:
+def errors_of(document: object, limits: ValidationLimits = LIMITS) -> list[tuple[str, str | None]]:
with pytest.raises(ConfigValidationError) as exc_info:
validate_config(document, limits=limits)
return [(error.code, error.attr) for error in exc_info.value.errors]