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(early-access-features): fix flag selector feedback and slug-collision error (#76020)

posthog[bot]e00e9238585e
diff --git a/frontend/src/lib/components/FlagSelector.test.tsx b/frontend/src/lib/components/FlagSelector.test.tsx
new file mode 100644
index 000000000000..36c824b95afe
--- /dev/null
+++ b/frontend/src/lib/components/FlagSelector.test.tsx
@@ -0,0 +1,30 @@
+import { flagSelectorButtonLabel } from './FlagSelector'
+
+describe('flagSelectorButtonLabel', () => {
+ // The picker strips `key` off recently-used flags, so a pick from the Recent tab labels itself
+ // with `name`, which on a flag holds a description like "Feature Flag for Early Access Feature
+ // Foo". The resolved key has to win over that.
+ const RECENT_PICK = { id: 7, label: 'Feature Flag for Early Access Feature Foo' }
+
+ test.each([
+ ['resolved key wins over a recent pick', 'foo', 7, RECENT_PICK, 'Fallback', 'foo'],
+ ['pick stands in while the key is still loading', '', 7, RECENT_PICK, 'Fallback', RECENT_PICK.label],
+ ['pick stands in when the key lookup fails', '', 7, { id: 7, label: 'foo' }, 'Fallback', 'foo'],
+ ['pick the caller never stored is dropped', '', undefined, RECENT_PICK, 'Fallback', 'Fallback'],
+ ['pick for a different flag is dropped', '', 9, RECENT_PICK, 'Fallback', 'Fallback'],
+ ['falls back to the initial label with nothing picked', '', undefined, undefined, 'Fallback', 'Fallback'],
+ ['falls back to the default with no initial label', '', undefined, undefined, undefined, 'Select flag'],
+ ])(
+ '%s',
+ (
+ _name: string,
+ flagKey: string,
+ value: number | undefined,
+ pickedFlag: { id: number; label: string } | undefined,
+ initialButtonLabel: string | undefined,
+ expected: string
+ ) => {
+ expect(flagSelectorButtonLabel({ flagKey, value, pickedFlag, initialButtonLabel })).toBe(expected)
+ }
+ )
+})
diff --git a/frontend/src/lib/components/FlagSelector.tsx b/frontend/src/lib/components/FlagSelector.tsx
index 3ebe4dd04cc0..cd4ab4477b87 100644
--- a/frontend/src/lib/components/FlagSelector.tsx
+++ b/frontend/src/lib/components/FlagSelector.tsx
@@ -17,6 +17,31 @@ interface FlagSelectorProps {
initialButtonLabel?: string
}
+interface PickedFlag {
+ id: number
+ label: string
+}
+
+export function flagSelectorButtonLabel({
+ flagKey,
+ value,
+ pickedFlag,
+ initialButtonLabel,
+}: {
+ flagKey: string
+ value: number | undefined
+ pickedFlag: PickedFlag | undefined
+ initialButtonLabel: string | undefined
+}): string {
+ // A pick only labels the button while it still agrees with `value`, so a pick the caller never
+ // stored can't linger. It ranks below `flagKey` because a pick from the recents list carries no
+ // key and falls back to `name`, which on a flag holds the description rather than a title.
+ // `flagKey` is '' both while the lookup is in flight and when it fails, which is the gap the
+ // pick covers.
+ const pickedLabel = pickedFlag && pickedFlag.id === value ? pickedFlag.label : undefined
+ return flagKey || pickedLabel || (initialButtonLabel ?? 'Select flag')
+}
+
export function FlagSelector({
value,
onChange,
@@ -25,6 +50,10 @@ export function FlagSelector({
initialButtonLabel,
}: FlagSelectorProps): JSX.Element {
const [visible, setVisible] = useState(false)
+ // Recently-used flags are persisted with just `{ name, id }` (no `key`), so a pick from the
+ // recents list has nothing to label the button with until the live lookup resolves. Hold
+ // whatever the picker handed us to cover that gap.
+ const [selectedFlag, setSelectedFlag] = useState<PickedFlag | undefined>(undefined)
const { featureFlag } = useValues(featureFlagLogic({ id: value || 'link' }))
@@ -32,8 +61,12 @@ export function FlagSelector({
groupType: TaxonomicFilterGroupType.FeatureFlags,
value: value,
onChange: (_, __, item) => {
- 'id' in item && item.id && onChange(item.id, item.key, item)
- setVisible(false)
+ // The picker can hand back an item with no flag id; that isn't a selection.
+ if ('id' in item && item.id) {
+ setSelectedFlag({ id: item.id, label: item.key || item.name })
+ onChange(item.id, item.key, item)
+ setVisible(false)
+ }
},
taxonomicGroupTypes: [TaxonomicFilterGroupType.FeatureFlags],
optionsFromProp: undefined,
@@ -43,6 +76,13 @@ export function FlagSelector({
selectingKeyOnly: true,
}
+ const buttonLabel = flagSelectorButtonLabel({
+ flagKey: featureFlag.key,
+ value,
+ pickedFlag: selectedFlag,
+ initialButtonLabel,
+ })
+
return (
<Popover
overlay={<TaxonomicFilter {...taxonomicFilterLogicProps} />}
@@ -56,7 +96,7 @@ export function FlagSelector({
onClick={() => setVisible(!visible)}
disabledReason={readOnly && (disabledReason || "I'm read-only")}
>
- {featureFlag.key ? featureFlag.key : (initialButtonLabel ?? 'Select flag')}
+ {buttonLabel}
</LemonButton>
</Popover>
)
diff --git a/products/early_access_features/backend/api.py b/products/early_access_features/backend/api.py
index 5a3c499383fc..40ff60cee052 100644
--- a/products/early_access_features/backend/api.py
+++ b/products/early_access_features/backend/api.py
@@ -64,6 +64,16 @@ def assert_feature_flag_rbac_access(
raise PermissionDenied("You don't have sufficient permissions to modify the linked feature flag.")
+def derive_feature_flag_key(feature_name: str) -> str:
+ """Key of the flag auto-created for a feature of this name.
+
+ The collision pre-check in validate() and the actual creation in create() must derive the key
+ identically. If they drift, the pre-check clears a key create() never uses and the collision
+ resurfaces as an error on "key", the field the form doesn't have.
+ """
+ return slugify(feature_name)
+
+
def clear_feature_enrollment(feature_flag: FeatureFlag, *, team: Team) -> None:
"""Clear the enrollment marker on a feature's linked flag (feature demoted or deleted).
@@ -429,6 +439,33 @@ class EarlyAccessFeatureSerializerCreateOnly(EarlyAccessFeatureSerializer):
raise serializers.ValidationError(
"Multivariate feature flags are not supported for Early Access Features."
)
+ elif data.get("name"):
+ # No flag was chosen, so create() derives one from the name below. Checking the derived
+ # key here attaches the error to "name", the field this form actually has, instead of
+ # letting the nested FeatureFlagSerializer raise it on "key", which the form never shows.
+ feature_flag_key = derive_feature_flag_key(data["name"])
+ if not feature_flag_key:
+ # slugify() strips a name with no ASCII alphanumerics down to "", which the flag
+ # serializer's key regex then rejects.
+ raise serializers.ValidationError(
+ {
+ "name": "A feature flag key can't be built from this name. Rename this feature using letters (a-z) or numbers, or link an existing flag instead."
+ }
+ )
+ existing_flag = FeatureFlag.objects.filter(
+ key=feature_flag_key, team__project_id=self.context["get_team"]().project_id
+ ).first()
+ if existing_flag is not None:
+ # Linking is only advice worth giving when the flag is actually linkable; the check
+ # above rejects a flag that already has a feature attached.
+ remedy = (
+ "Rename this feature."
+ if existing_flag.features.exists()
+ else "Rename this feature, or link the existing flag instead."
+ )
+ raise serializers.ValidationError(
+ {"name": f"A feature flag with the key '{feature_flag_key}' already exists. {remedy}"}
+ )
return data
@@ -479,7 +516,7 @@ class EarlyAccessFeatureSerializerCreateOnly(EarlyAccessFeatureSerializer):
team_id=self.context["team_id"],
)
assert_feature_flag_rbac_access(self.user_access_control)
- feature_flag_key = slugify(validated_data["name"])
+ feature_flag_key = derive_feature_flag_key(validated_data["name"])
filters: dict[str, Any] = {
"groups": default_condition,
diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.py
index 2fbdf2b53ce6..eda09bb7ece5 100644
--- a/products/early_access_features/backend/test/test_early_access_feature.py
+++ b/products/early_access_features/backend/test/test_early_access_feature.py
@@ -421,13 +421,27 @@ class TestEarlyAccessFeature(APIBaseTest):
},
)
- def test_cant_create_early_access_feature_with_duplicate_key(self):
- FeatureFlag.objects.create(
+ @parameterized.expand(
+ [
+ ("linkable_flag", False, "Rename this feature, or link the existing flag instead."),
+ ("flag_already_attached", True, "Rename this feature."),
+ ]
+ )
+ def test_cant_create_early_access_feature_with_duplicate_key(self, _name, attach_existing_feature, remedy):
+ flag = FeatureFlag.objects.create(
team=self.team,
filters={"groups": [{"properties": [], "rollout_percentage": None}]},
key="hick-bondoogling",
created_by=self.user,
)
+ if attach_existing_feature:
+ EarlyAccessFeature.objects.create(
+ team=self.team,
+ name="Hick bondoogling (original)",
+ description="The one that got there first.",
+ stage="beta",
+ feature_flag=flag,
+ )
response = self.client.post(
f"/api/projects/{self.team.id}/early_access_feature/",
@@ -442,9 +456,37 @@ class TestEarlyAccessFeature(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response_data
+ self.assertEqual(response_data["attr"], "name")
+ self.assertEqual(
+ response_data["detail"],
+ f"A feature flag with the key 'hick-bondoogling' already exists. {remedy}",
+ )
+
+ @parameterized.expand(
+ [
+ ("non_latin_script", "功能名称"),
+ ("emoji_only", "🎉🎉🎉"),
+ ("punctuation_only", "!!!"),
+ ]
+ )
+ def test_cant_create_early_access_feature_whose_name_yields_no_flag_key(self, _name, feature_name):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/early_access_feature/",
+ data={
+ "name": feature_name,
+ "description": "A feature whose name slugifies to nothing.",
+ "stage": "beta",
+ },
+ format="json",
+ )
+ response_data = response.json()
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response_data
+
+ self.assertEqual(response_data["attr"], "name")
self.assertEqual(
response_data["detail"],
- "There is already a feature flag with this key.",
+ "A feature flag key can't be built from this name. Rename this feature using letters (a-z) or numbers, or link an existing flag instead.",
)
def test_can_create_new_early_access_feature_with_soft_deleted_flag(self):