: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
fix(flags): sync toggle state and persistence (#68314)
posthog[bot]0ef64daeb7de
diff --git a/frontend/src/scenes/feature-flags/ConfirmationModal.tsx b/frontend/src/scenes/feature-flags/ConfirmationModal.tsxindex 9fddb494c545..8e1c0b4516f5 100644--- a/frontend/src/scenes/feature-flags/ConfirmationModal.tsx+++ b/frontend/src/scenes/feature-flags/ConfirmationModal.tsx@@ -147,6 +147,7 @@ export function openConfirmationModal({: type === 'rollout'? 'Update conditions': 'Save changes',+ status: type === 'flag-status' && !activeNewValue ? 'danger' : 'default',onClick: hasBlockingDependentFlags ? undefined : onConfirm,disabled: hasBlockingDependentFlags,},diff --git a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsxindex 2dfc26295aca..d376336428d1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx@@ -3,7 +3,7 @@ import './FeatureFlag.scss'import { useActions, useValues } from 'kea'import { IconCode, IconFlag, IconGlobe, IconLaptop, IconList, IconServer } from '@posthog/icons'-import { LemonCollapse, LemonDialog, LemonSwitch, LemonTag } from '@posthog/lemon-ui'+import { LemonCollapse, LemonSwitch, LemonTag } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'@@ -66,23 +66,6 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):const variants = featureFlag.filters?.multivariate?.variants || []const hasPayload = !!featureFlag.filters?.payloads?.['true']- const handleToggleClick = (): void => {- LemonDialog.open({- title: featureFlag.active ? 'Disable feature flag?' : 'Enable feature flag?',- description: featureFlag.active- ? 'This will immediately disable the flag for all users. Are you sure?'- : 'This will immediately enable the flag according to its release conditions. Are you sure?',- primaryButton: {- children: featureFlag.active ? 'Disable' : 'Enable',- status: featureFlag.active ? 'danger' : 'default',- onClick: () => toggleFeatureFlagActive(!featureFlag.active),- },- secondaryButton: {- children: 'Cancel',- },- })- }-const getFlagTypeDisplay = (): { icon: JSX.Element; label: string; description: string } => {if (featureFlag.is_remote_configuration) {return {@@ -165,7 +148,7 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):><LemonSwitchchecked={featureFlag.active}- onChange={handleToggleClick}+ onChange={toggleFeatureFlagActive}loading={featureFlagActiveUpdateLoading}disabledReason={!featureFlag.can_editdiff --git a/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts b/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.tsindex 8cda6e8d4f91..740c98b8e09b 100644--- a/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts@@ -112,7 +112,8 @@ export function checkFeatureFlagConfirmation(featureFlagConfirmationEnabled: boolean,onConfirm: () => void,dependentFlags?: DependentFlag[],- isBeingDisabled?: boolean+ isBeingDisabled?: boolean,+ requireStatusConfirmation = false): boolean {// Check if confirmation is neededconst needsConfirmation = !!updatedFlag.id && shouldDisplayConfirmation@@ -136,6 +137,16 @@ export function checkFeatureFlagConfirmation(}}+ if (requireStatusConfirmation && originalFlag?.active !== updatedFlag.active) {+ openConfirmationModal({+ featureFlag: updatedFlag,+ type: 'flag-status',+ activeNewValue: updatedFlag.active,+ onConfirm,+ })+ return true+ }+return false // No confirmation needed, proceed with save}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 2804de8e7fae..f17d767c3966 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -4,6 +4,7 @@ import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { urls } from 'scenes/urls'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'@@ -42,6 +43,7 @@ import {slugifyFeatureFlagKey,validateFeatureFlagKey,} from './featureFlagLogic'+import { featureFlagsLogic } from './featureFlagsLogic'const MOCK_FEATURE_FLAG = {...NEW_FLAG,@@ -200,6 +202,46 @@ describe('featureFlagLogic', () => {jest.useRealTimers()})+ describe('stale list-cache reconciliation on mount', () => {+ it('refreshes a cache-painted flag so active reflects the server, not the stale list cache', async () => {+ logic.unmount()++ useMocks({+ get: {+ '/api/projects/:projectId/feature_flags/': () => [+ 200,+ { results: [{ ...MOCK_FEATURE_FLAG, active: false }], count: 1 },+ ],+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 200,+ { ...MOCK_FEATURE_FLAG, active: true },+ ],+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/status`]: () => [+ 200,+ MOCK_FEATURE_FLAG_STATUS,+ ],+ },+ })++ featureFlagsLogic.mount()+ featureFlagsLogic.actions.loadFeatureFlags()+ await expectLogic(featureFlagsLogic).toFinishAllListeners()+ expect(featureFlagsLogic.values.featureFlags.results[0].active).toBe(false)++ logic = featureFlagLogic({ id: 1 })+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['setFeatureFlag', 'refreshFeatureFlag', 'refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureFlag.active).toBe(true)+ expect(featureFlagsLogic.values.featureFlags.results[0].active).toBe(true)++ featureFlagsLogic.unmount()+ })+ })+describe('setMultivariateEnabled functionality', () => {it('adds default variants when enabling multivariate', async () => {await expectLogic(logic).toMatchValues({@@ -1278,6 +1320,21 @@ describe('featureFlagLogic', () => {expect(logic.values.projectFlagsToggling).toEqual({})})})++ describe('toggleFeatureFlagActive', () => {+ it('opens one confirmation with matching disable copy', async () => {+ const dialogOpenSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ logic.actions.setFeatureFlag({ ...MOCK_FEATURE_FLAG, active: true })++ await expectLogic(logic, () => logic.actions.toggleFeatureFlagActive(false)).toFinishAllListeners()++ expect(dialogOpenSpy).toHaveBeenCalledTimes(1)+ const dialogProps = dialogOpenSpy.mock.calls[0][0]+ expect(dialogProps.title).toBe('Disable feature flag "test-flag"?')+ expect(dialogProps.primaryButton?.children).toBe('Disable flag')+ dialogOpenSpy.mockRestore()+ })+ })})const createFilters = (overrides: Partial<FeatureFlagFilters> = {}): FeatureFlagFilters => ({diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 5e3468800318..2e9b2d707af3 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -659,6 +659,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([onConfirm: () => voiddependentFlags: DependentFlag[]isBeingDisabled?: boolean+ requireStatusConfirmation?: boolean}) => payload,saveDescriptionInline: (name: string) => ({ name }),saveTagsInline: (tags: string[]) => ({ tags }),@@ -1178,8 +1179,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([originalFlag: FeatureFlagType | nullupdatedFlag: Partial<FeatureFlagType>onConfirm: () => void+ requireStatusConfirmation?: boolean}) => {- const { originalFlag, updatedFlag, onConfirm } = payload+ const { originalFlag, updatedFlag, onConfirm, requireStatusConfirmation = false } = payloadconst isBeingDisabled = !!updatedFlag.id && originalFlag?.active === true && updatedFlag.active === falselet dependentFlagsForConfirmation: DependentFlag[] = []@@ -1205,6 +1207,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([onConfirm,isBeingDisabled,dependentFlags: dependentFlagsForConfirmation,+ requireStatusConfirmation,})},showDependentFlagsConfirmation: (payload: {@@ -1213,8 +1216,16 @@ export const featureFlagLogic = kea<featureFlagLogicType>([onConfirm: () => voiddependentFlags: DependentFlag[]isBeingDisabled?: boolean+ requireStatusConfirmation?: boolean}) => {- const { originalFlag, updatedFlag, onConfirm, dependentFlags, isBeingDisabled = false } = payload+ const {+ originalFlag,+ updatedFlag,+ onConfirm,+ dependentFlags,+ isBeingDisabled = false,+ requireStatusConfirmation = false,+ } = payloadconst featureFlagConfirmationEnabled = !!values.currentTeam?.feature_flag_confirmation_enabledlet customConfirmationMessage: string | undefined@@ -1232,7 +1243,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([featureFlagConfirmationEnabled,onConfirm,dependentFlags,- isBeingDisabled+ isBeingDisabled,+ requireStatusConfirmation)// If no confirmation was shown, proceed immediately@@ -1504,6 +1516,29 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},},],+ // Silent background refresh used when the overview paints instantly from the list+ // cache on mount. Has its own loading key so it never triggers the page skeleton,+ // while reconciling the flag (notably `active`) with the server — otherwise a stale+ // cached `active` can make the toggle and its confirmation dialog contradict the+ // flag's real state.+ featureFlagRefresh: [+ null as FeatureFlagType | null,+ {+ refreshFeatureFlag: async () => {+ if (!props.id || props.id === 'new' || props.id === 'link') {+ return null+ }+ try {+ const retrievedFlag: FeatureFlagType = await api.featureFlags.get(props.id)+ return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)+ } catch {+ // Swallow errors — this is a silent background reconciliation, so a+ // transient failure shouldn't surface a toast or get reported.+ return null+ }+ },+ },+ ],relatedInsights: [[] as QueryBasedInsightModel[],{@@ -1997,6 +2032,14 @@ export const featureFlagLogic = kea<featureFlagLogicType>([refreshTreeItem('feature_flag', String(flagId))}},+ refreshFeatureFlagSuccess: ({ featureFlagRefresh }) => {+ // Reconcile the cache-painted flag with the freshly fetched server state, and keep+ // the list cache in sync so the two views agree.+ if (featureFlagRefresh) {+ actions.setFeatureFlag(featureFlagRefresh)+ actions.updateFlag(featureFlagRefresh)+ }+ },updateFeatureFlagArchivedSuccess: ({ featureFlagActiveUpdate }) => {if (featureFlagActiveUpdate) {lemonToast.success(`Feature flag ${featureFlagActiveUpdate.archived ? 'archived' : 'unarchived'}`)@@ -2416,6 +2459,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([onConfirm: () => {actions.updateFeatureFlagActive(active)},+ requireStatusConfirmation: true,},breakpoint,action as any,@@ -2875,6 +2919,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.loadRelatedInsights()actions.loadFeatureFlagStatus()actions.loadDependentFlags()+ // Paint instantly from the list cache above, then silently reconcile with the+ // server: the cached `active` can be stale (toggled elsewhere since the list+ // loaded), which otherwise leaves the overview toggle and its confirmation+ // dialog reflecting the wrong state.+ actions.refreshFeatureFlag()} else if (props.id !== 'new') {actions.loadFeatureFlag()actions.loadFeatureFlagStatus()diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex cee49b3874de..1d66100dfd11 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1941,15 +1941,17 @@ class FeatureFlagSerializer(# NOW check for conflicts after all transformationsif version != -1 and version != locked_version:+ original_flag = request.data.get("original_flag", {})conflicting_changes = self._get_conflicting_changes(locked_instance,validated_data,- request.data.get("original_flag", {}),+ original_flag,)if len(conflicting_changes) > 0:raise Conflict(f"The feature flag was updated by {locked_instance.last_modified_by.email if locked_instance.last_modified_by else 'another user'} since you started editing it. Please refresh and try again.")+ validated_data = self._discard_unchanged_stale_fields(validated_data, original_flag)# Continue with the updatevalidated_data["version"] = locked_version + 1@@ -2005,6 +2007,16 @@ class FeatureFlagSerializer(return instance+ def _discard_unchanged_stale_fields(self, validated_data: dict, original_flag: dict | None) -> dict:+ if not original_flag:+ return validated_data++ return {+ field: new_value+ for field, new_value in validated_data.items()+ if field not in original_flag or new_value != original_flag[field]+ }+def _get_conflicting_changes(self,current_instance: FeatureFlag,diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 7838b66513ce..bbd05c84b53f 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -1866,7 +1866,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):# Successfully update the feature flag with the different user. This will increment the versionresponse = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag_id}",- {"name": "Updated name", "version": original_version},+ {"name": "Updated name", "active": False, "version": original_version},format="json",)@@ -1968,7 +1968,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):# Successfully update the feature flag with the different user. This will increment the versionresponse = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag_id}",- {"name": "Updated name", "version": original_version},+ {"name": "Updated name", "active": False, "version": original_version},format="json",)@@ -1982,6 +1982,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):f"/api/projects/{self.team.id}/feature_flags/{flag_id}",data={"name": "Updated name",+ "active": True,"filters": {"groups": [{@@ -2002,6 +2003,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):},"original_flag": {"name": "original name", # This is the same as the name (though not the current name)+ "active": True,"filters": {"groups": [{@@ -2031,6 +2033,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_200_OK)feature_flag = FeatureFlag.objects.get(id=flag_id)self.assertEqual(feature_flag.name, "Updated name")+ self.assertFalse(feature_flag.active)self.assertEqual(feature_flag.last_modified_by, original_user)self.assertEqual(response.json()["filters"]["groups"][0]["rollout_percentage"], 45)