: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): Add bucketing change safeguards for v2 UI (#57338)
Gustavo H. Strassburger788f6d467ba8
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex cd8e26e1b1da..34bc649a2d0f 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -178,7 +178,6 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {setShowImplementation,setOpenVariants,setPayloadExpanded,- setBucketingIdentifier,resetEncryptedPayload,} = useActions(featureFlagLogic)const { tags: availableTags } = useValues(tagsModel)@@ -661,37 +660,42 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {/></LemonField>- <LemonDivider className="my-1" />+ {/* Persistence - hide when device ID bucketing is selected */}+ {featureFlag.bucketing_identifier !==+ FeatureFlagBucketingIdentifier.DEVICE_ID && (+ <>+ <LemonDivider className="my-1" />- {/* Persistence */}- <LemonField- name="ensure_experience_continuity"- label="Persistence"- labelClassName="text-sm font-medium"- info={- <>- Keep flag values consistent before and after login. Requires- anonymous user profiles.{' '}- <Link- to="https://posthog.com/docs/feature-flags/creating-feature-flags#persisting-feature-flags-across-authentication-steps"- target="_blank"- >- Learn more- </Link>- </>- }- >- {({ value, onChange }) => (- <LemonSwitch- checked={value}- onChange={onChange}- bordered- fullWidth- label="Persist flag across authentication steps"- data-attr="feature-flag-persist-across-auth"- />- )}- </LemonField>+ <LemonField+ name="ensure_experience_continuity"+ label="Persistence"+ labelClassName="text-sm font-medium"+ info={+ <>+ Keep flag values consistent before and after login.+ Requires anonymous user profiles.{' '}+ <Link+ to="https://posthog.com/docs/feature-flags/creating-feature-flags#persisting-feature-flags-across-authentication-steps"+ target="_blank"+ >+ Learn more+ </Link>+ </>+ }+ >+ {({ value, onChange }) => (+ <LemonSwitch+ checked={value}+ onChange={onChange}+ bordered+ fullWidth+ label="Persist flag across authentication steps"+ data-attr="feature-flag-persist-across-auth"+ />+ )}+ </LemonField>+ </>+ )}</div>),},@@ -1066,9 +1070,23 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {variants={nonEmptyVariants}isDisabled={!featureFlag.active}bucketingIdentifier={featureFlag.bucketing_identifier}- onBucketingIdentifierChange={(value: FeatureFlagBucketingIdentifier | null) =>- setBucketingIdentifier(value)- }+ onBucketingIdentifierChange={(value: FeatureFlagBucketingIdentifier | null) => {+ // Always go through setFeatureFlag so this caller and+ // FeatureFlagReleaseConditions use the same shape — listeners on+ // setBucketingIdentifier (variant reset, telemetry, autosave) won't+ // silently fire on one path and not the other. Switching to device+ // bucketing also disables persist across auth, since the two are+ // incompatible.+ const ensureContinuity =+ value === FeatureFlagBucketingIdentifier.DEVICE_ID+ ? false+ : featureFlag.ensure_experience_continuity+ setFeatureFlag({+ ...featureFlag,+ bucketing_identifier: value,+ ensure_experience_continuity: ensureContinuity,+ })+ }}evaluationRuntime={featureFlag.evaluation_runtime}/></div>diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsxindex f8e553f923bf..5f6ef90c1e19 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx@@ -20,6 +20,7 @@ import { GroupsIntroductionOption } from 'lib/introductions/GroupsIntroductionOpimport { IconArrowDown, IconArrowUp, IconErrorOutline, IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'@@ -143,7 +144,7 @@ export function FeatureFlagReleaseConditions({const { showGroupsOptions, groupTypes, aggregationLabel } = useValues(groupsModel)const { earlyAccessFeaturesList, hasEarlyAccessFeatures, featureFlagKey, nonEmptyVariants, featureFlag } =useValues(featureFlagLogic)- const { setBucketingIdentifier } = useActions(featureFlagLogic)+ const { setBucketingIdentifier, setFeatureFlag } = useActions(featureFlagLogic)const { groupsAccessStatus } = useValues(groupsAccessLogic)@@ -660,19 +661,59 @@ export function FeatureFlagReleaseConditions({: 'user'}onChange={(value) => {- if (value === 'user') {- setAggregationGroupTypeIndex(null)- setBucketingIdentifier(FeatureFlagBucketingIdentifier.DISTINCT_ID)- } else if (value === 'device') {- setAggregationGroupTypeIndex(null)- setBucketingIdentifier(FeatureFlagBucketingIdentifier.DEVICE_ID)- } else if (value === 'group') {- // Default to first group type when selecting Group- const firstGroupType = Array.from(groupTypes.values())[0]- if (firstGroupType) {- setAggregationGroupTypeIndex(firstGroupType.group_type_index)+ const currentValue =+ filters.aggregation_group_type_index != null+ ? 'group'+ : featureFlag.bucketing_identifier === FeatureFlagBucketingIdentifier.DEVICE_ID+ ? 'device'+ : 'user'++ const applyChange = (targetValue: string): void => {+ if (targetValue === 'user') {+ setAggregationGroupTypeIndex(null)+ setBucketingIdentifier(FeatureFlagBucketingIdentifier.DISTINCT_ID)+ } else if (targetValue === 'device') {+ setAggregationGroupTypeIndex(null)+ // Atomically switch to device bucketing and disable persist across auth —+ // these are incompatible, so applying both in one setFeatureFlag avoids any+ // window where the closure-captured featureFlag could overwrite the new+ // bucketing identifier.+ setFeatureFlag({+ ...featureFlag,+ bucketing_identifier: FeatureFlagBucketingIdentifier.DEVICE_ID,+ ensure_experience_continuity: false,+ })+ } else if (targetValue === 'group') {+ // Default to first group type when selecting Group+ const firstGroupType = Array.from(groupTypes.values())[0]+ if (firstGroupType) {+ setAggregationGroupTypeIndex(firstGroupType.group_type_index)+ }+ setBucketingIdentifier(null)}- setBucketingIdentifier(null)+ }++ // Only confirm when changing bucketing on an existing flag+ const isExistingFlag = id !== 'new'+ const isChangingValue = value !== currentValue+ if (isExistingFlag && isChangingValue) {+ LemonDialog.open({+ title: 'Change bucketing option?',+ description:+ 'Changing the bucketing option will cause users to re-evaluate the flag and may cause changes in the evaluation results. Are you sure you want to continue?',+ primaryButton: {+ children: 'Continue',+ onClick: () => applyChange(value),+ size: 'small',+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'tertiary',+ size: 'small',+ },+ })+ } else {+ applyChange(value)}}}options={[diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsxindex 82ddfd75a2b2..f66d9f73a973 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx@@ -48,6 +48,7 @@ import { TaxonomicFilterGroupType, TaxonomicFilterProps } from 'lib/components/Timport { FEATURE_FLAGS } from 'lib/constants'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'import { Link } from 'lib/lemon-ui/Link'@@ -927,24 +928,49 @@ export function FeatureFlagReleaseConditionsCollapsible({// Handler for option selection logic (shared by click and keyboard events)const selectMatchByOption = (value: string): void => {- if (value === 'user') {- setIsMixedTargeting(false)- setAggregationGroupTypeIndex(null)- onBucketingIdentifierChange?.(FeatureFlagBucketingIdentifier.DISTINCT_ID)- } else if (value === 'device') {- setIsMixedTargeting(false)- setAggregationGroupTypeIndex(null)- onBucketingIdentifierChange?.(FeatureFlagBucketingIdentifier.DEVICE_ID)- } else if (value === 'group') {- setIsMixedTargeting(false)- const firstGroupType = groupTypeValues[0]- if (firstGroupType) {- setAggregationGroupTypeIndex(firstGroupType.group_type_index)+ const applyChange = (targetValue: string): void => {+ if (targetValue === 'user') {+ setIsMixedTargeting(false)+ setAggregationGroupTypeIndex(null)+ onBucketingIdentifierChange?.(FeatureFlagBucketingIdentifier.DISTINCT_ID)+ } else if (targetValue === 'device') {+ setIsMixedTargeting(false)+ setAggregationGroupTypeIndex(null)+ onBucketingIdentifierChange?.(FeatureFlagBucketingIdentifier.DEVICE_ID)+ } else if (targetValue === 'group') {+ setIsMixedTargeting(false)+ const firstGroupType = groupTypeValues[0]+ if (firstGroupType) {+ setAggregationGroupTypeIndex(firstGroupType.group_type_index)+ }+ onBucketingIdentifierChange?.(null)+ } else if (targetValue === 'mixed') {+ switchToMixedTargeting()+ onBucketingIdentifierChange?.(null)}- onBucketingIdentifierChange?.(null)- } else if (value === 'mixed') {- switchToMixedTargeting()- onBucketingIdentifierChange?.(null)+ }++ // Only confirm when changing bucketing on an existing flag+ const isExistingFlag = flagId !== 'new'+ const isChangingValue = value !== currentSelected+ if (isExistingFlag && isChangingValue) {+ LemonDialog.open({+ title: 'Change bucketing option?',+ description:+ 'Changing the bucketing option will cause users to re-evaluate the flag and may cause changes in the evaluation results. Are you sure you want to continue?',+ primaryButton: {+ children: 'Continue',+ onClick: () => applyChange(value),+ size: 'small',+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'tertiary',+ size: 'small',+ },+ })+ } else {+ applyChange(value)}}diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.pyindex e85f79338ca3..18a9ac54cc50 100644--- a/posthog/api/feature_flag.py+++ b/posthog/api/feature_flag.py@@ -822,10 +822,10 @@ class FeatureFlagSerializer("""Validate feature flag creation/update including evaluation tag requirements."""attrs = super().validate(attrs)+ # Run universal validations before any early returns so they always apply,+ # regardless of creation_context (surveys, etc.) or evaluation contexts.+ self._validate_device_bucketing_with_persist_auth(attrs)self._validate_encrypted_payloads_require_remote_config(attrs)-- # Validate team-wide flag count limit before any early returns, since it- # applies to all creates regardless of creation context (surveys, etc.)self._validate_flag_limits()request = self.context.get("request")@@ -879,6 +879,37 @@ class FeatureFlagSerializer(return attrs+ def _validate_device_bucketing_with_persist_auth(self, attrs):+ """Validate that persist across auth is not enabled with device ID bucketing"""+ # bucketing_identifier is nullable (CharField(null=True)), so we use a sentinel to+ # distinguish "field absent from PATCH" from "field explicitly set to null". A bare+ # `attrs.get(...) is None` fallback would otherwise treat an explicit null as missing+ # and validate against the stale instance value.+ _MISSING: Any = object()+ bucketing_identifier = attrs.get("bucketing_identifier", _MISSING)+ ensure_experience_continuity = attrs.get("ensure_experience_continuity", _MISSING)++ if self.instance:+ if bucketing_identifier is _MISSING:+ bucketing_identifier = self.instance.bucketing_identifier+ if ensure_experience_continuity is _MISSING:+ ensure_experience_continuity = self.instance.ensure_experience_continuity++ # Prevent new combinations of device_id + ensure_experience_continuity=True+ if bucketing_identifier == "device_id" and ensure_experience_continuity is True:+ # Allow if this combination already existed (no change)+ if (+ self.instance+ and self.instance.bucketing_identifier == "device_id"+ and self.instance.ensure_experience_continuity is True+ ):+ pass # Allow existing combination to be saved without changes+ else:+ raise serializers.ValidationError(+ "Cannot enable 'persist across authentication steps' when using device ID bucketing. "+ "These features are incompatible."+ )+def _validate_encrypted_payloads_require_remote_config(self, attrs: dict) -> None:"""Encrypted payloads are only valid on remote configuration flags."""# Resolve effective values: use incoming attrs, falling back to instance for updatesdiff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.pyindex 1ddf39482adb..87b4a7af1364 100644--- a/posthog/api/test/test_feature_flag.py+++ b/posthog/api/test/test_feature_flag.py@@ -5862,6 +5862,89 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):# Should succeed since it's an update, not creationself.assertEqual(response.status_code, status.HTTP_200_OK)+ @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",+ )+ 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('_', '-')}",+ team=self.team,+ created_by=self.user,+ bucketing_identifier="device_id",+ ensure_experience_continuity=initial_persist,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ 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}]},+ },+ format="json",+ )+ 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,diff --git a/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.py b/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.pynew file mode 100644index 000000000000..d4c8fa93dc88--- /dev/null+++ b/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.py@@ -0,0 +1,105 @@+# Generated by Django 5.2.13 on 2026-05-01 22:14++import functools++from django.conf import settings+from django.db import migrations, transaction++BULK_BATCH_SIZE = 500+++def fix_device_bucketing_persist_across_auth(apps, schema_editor):+ """+ Fix existing feature flags that have the invalid combination of+ device_id bucketing with ensure_experience_continuity=True.++ This combination is now incompatible and validation prevents it,+ so we disable persist across auth for these flags.++ The dataset is small in practice (only flags created before validation+ was added that ended up in the invalid combination), so we run inside the+ default migration transaction (atomic=True) using a single bulk UPDATE plus+ a single bulk_create for activity logs. bulk_update bypasses post_save+ signals, so we dispatch cache invalidation explicitly per affected team+ after the outer transaction commits.+ """+ FeatureFlag = apps.get_model("posthog", "FeatureFlag")+ ActivityLog = apps.get_model("posthog", "ActivityLog")++ invalid_flags = list(+ FeatureFlag.objects.filter(bucketing_identifier="device_id", ensure_experience_continuity=True).select_related(+ "team__organization"+ )+ )++ if not invalid_flags:+ return++ flag_ids = [flag.id for flag in invalid_flags]+ affected_team_ids = {flag.team_id for flag in invalid_flags}++ activity_logs = [+ ActivityLog(+ team_id=flag.team_id,+ organization_id=flag.team.organization_id,+ user=None,+ is_system=True,+ scope="FeatureFlag",+ item_id=str(flag.id),+ activity="updated",+ detail={+ "name": flag.key,+ "changes": [+ {+ "type": "FeatureFlag",+ "action": "changed",+ "field": "ensure_experience_continuity",+ "before": True,+ "after": False,+ }+ ],+ # Use the documented `trigger` shape so DetailSerializer surfaces this+ # in the activity log UI; a top-level `reason` would be silently dropped.+ "trigger": {+ "job_type": "migration",+ "job_id": "1152_fix_device_bucketing_persist_across_auth",+ "payload": {+ "reason": "Auto-disabled persist across auth due to incompatibility with device ID bucketing",+ },+ },+ },+ )+ for flag in invalid_flags+ ]++ FeatureFlag.objects.filter(id__in=flag_ids).update(ensure_experience_continuity=False)+ ActivityLog.objects.bulk_create(activity_logs, batch_size=BULK_BATCH_SIZE)+ transaction.on_commit(functools.partial(_invalidate_flag_caches, affected_team_ids))+++def _invalidate_flag_caches(team_ids):+ """Mirror the post_save receivers in flags_cache.py and local_evaluation.py+ so flag evaluation services pick up the new state — bulk_update bypasses+ those signals."""+ from posthog.tasks.feature_flags import update_team_flags_cache, update_team_service_flags_cache++ for team_id in team_ids:+ update_team_flags_cache.delay(team_id)+ if settings.FLAGS_REDIS_URL:+ update_team_service_flags_cache.delay(team_id)+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1151_cimd_followup_hardening"),+ ]++ operations = [+ migrations.RunPython(+ fix_device_bucketing_persist_across_auth,+ # Intentionally not reversible: rolling back would re-enable an invalid+ # (device_id, ensure_experience_continuity=True) combination. Pre-fix+ # values are recoverable from the ActivityLog rows this migration writes.+ migrations.RunPython.noop,+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 88eca70d6152..d9eb0d0664a7 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1151_cimd_followup_hardening+1152_fix_device_bucketing_persist_across_auth