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): add archived state and flag list UX improvements (#63338)

Gustavo H. Strassburger0543593d95b0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b61132d6b582..7f7e5d05d91e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5255,9 +5255,9 @@ snapshots:
scenes-app-feature-flags--feature-flag-not-found--light:
hash: v1.k794b7964.e784cb2f06f9bfcbc6743df7815cbf7c815da053481b08baecb4a088910f3afa.9OxM372yUO63hbW3CfWOXwnUJD3dTv8EKpc-J3i9HOo
scenes-app-feature-flags--feature-flags-list--dark:
- hash: v1.k794b7964.2730a9e4846c16869c821c34dcf59d7fb86ee63a3fc91857cf19b72face208b3.OgQAw3la22Mh824WdrYvhRwGI-FayVzs61pVUwE6obo
+ hash: v1.k794b7964.3f23a54039cdade8c62080218d291b47f344bc764d2dd7bcf5c3d26f5ed51b9f.j68vdWeofv2VyAvWB3LzVuHs9-rVBMODGn23jOiZ-lM
scenes-app-feature-flags--feature-flags-list--light:
- hash: v1.k794b7964.9f31458f9371ccf1f6ba09cd3728a71c1b1d496b951cc942d6a173d10fa5786d.KAGRvF0AJDFLtof4mRa3aEXUcIc_B0eHSqpDoTHvKws
+ hash: v1.k794b7964.64c7a3e171d6cf048477a6326b3a4fe4576e41fb57f1ee7e8b7f73a4ee5e8539.q1bL9l-RlDIBQL-O-aT_mmhBCAj28y5AgUSHt3ZG62I
scenes-app-feature-flags--new-feature-flag--dark:
hash: v1.k794b7964.fbe1869305bc7cb75866454247654b1bec61b46ca26ac6376e9052d32b6008d9.kQNTnuUjC2fI5L50CuYD4L-pvJjmSa5J3sIlkPGj8F4
scenes-app-feature-flags--new-feature-flag--light:
diff --git a/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.test.tsx
index d5051af7b5cd..f6ef1a135b56 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.test.tsx
@@ -43,6 +43,7 @@ describe('SelectExistingFeatureFlagModal', () => {
created_by: null,
is_remote_configuration: false,
deleted: false,
+ archived: false,
active: true,
experiment_set: null,
experiment_set_metadata: null,
diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx
index 73eb93a84254..669c0ef39965 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx
@@ -42,6 +42,7 @@ describe('VariantsPanelLinkFeatureFlag', () => {
created_by: null,
is_remote_configuration: false,
deleted: false,
+ archived: false,
active: true,
experiment_set: null,
experiment_set_metadata: null,
diff --git a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
index ebe39f8a53da..171a21e02e71 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
@@ -36,6 +36,7 @@ describe('selectExistingFeatureFlagModalLogic', () => {
created_by: null,
is_remote_configuration: false,
deleted: false,
+ archived: false,
active: true,
experiment_set: null,
experiment_set_metadata: null,
@@ -73,6 +74,7 @@ describe('selectExistingFeatureFlagModalLogic', () => {
created_by: null,
is_remote_configuration: false,
deleted: false,
+ archived: false,
active: true,
experiment_set: null,
experiment_set_metadata: null,
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx
index 161c5fa6b0f7..0344b84f62af 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx
@@ -98,7 +98,8 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {
const showRunningState = isExperimentRunning && !isExperimentStopped && !!experiment.feature_flag
const paused = isExperimentPaused(experiment)
- const handleArchive = (): void => confirmArchiveExperiment(() => archiveExperiment())
+ const handleArchive = (): void =>
+ confirmArchiveExperiment(experiment, (disableFlag) => archiveExperiment(disableFlag))
const handleDelete = (): void =>
confirmDeleteExperiment({
projectId: currentProjectId,
diff --git a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx
index a67bc7d505c6..51aa00045f18 100644
--- a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx
@@ -86,7 +86,8 @@ export function PageHeaderCustom(): JSX.Element {
const canArchive = canEdit && canArchiveExperiment(experiment)
const canDelete = canEdit
- const handleArchive = (): void => confirmArchiveExperiment(() => archiveExperiment())
+ const handleArchive = (): void =>
+ confirmArchiveExperiment(experiment, (disableFlag) => archiveExperiment(disableFlag))
const handleDelete = (): void =>
confirmDeleteExperiment({
projectId: currentProjectId,
diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsx
index 8e66b4765164..81f023989419 100644
--- a/frontend/src/scenes/experiments/Experiments.tsx
+++ b/frontend/src/scenes/experiments/Experiments.tsx
@@ -426,8 +426,11 @@ const ExperimentsTable = ({
>
<LemonButton
onClick={() =>
- confirmArchiveExperiment(() =>
- archiveExperiment(experiment.id as number)
+ confirmArchiveExperiment(experiment, (disableFlag) =>
+ archiveExperiment({
+ id: experiment.id as number,
+ disableFeatureFlag: disableFlag,
+ })
)
}
data-attr={`experiment-${experiment.id}-dropdown-archive`}
diff --git a/frontend/src/scenes/experiments/experimentActions.tsx b/frontend/src/scenes/experiments/experimentActions.tsx
index 6bfac5e93c57..1924c80350ce 100644
--- a/frontend/src/scenes/experiments/experimentActions.tsx
+++ b/frontend/src/scenes/experiments/experimentActions.tsx
@@ -1,4 +1,4 @@
-import { LemonDialog } from '@posthog/lemon-ui'
+import { LemonCheckbox, LemonDialog } from '@posthog/lemon-ui'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
@@ -13,18 +13,43 @@ export function canArchiveExperiment(
return !experiment.archived && hasEnded(experiment)
}
-export function confirmArchiveExperiment(onConfirm: () => void): void {
+export function confirmArchiveExperiment(
+ experiment: Pick<Experiment, 'feature_flag'>,
+ onConfirm: (disableFeatureFlag: boolean) => void
+): void {
+ // Only an enabled flag needs a decision — a disabled flag is archived automatically.
+ const flagIsEnabled = !!experiment.feature_flag?.active
+ let disableFeatureFlag = false
+
LemonDialog.open({
title: 'Archive this experiment?',
content: (
- <div className="text-sm text-secondary">
- This action will hide the experiment from the list by default. It can be restored at any time.
+ <div className="flex flex-col gap-3">
+ <div className="text-sm text-secondary">
+ This action will hide the experiment from the list by default. It can be restored at any time.
+ </div>
+ {flagIsEnabled && (
+ <LemonCheckbox
+ defaultChecked={false}
+ onChange={(checked) => {
+ disableFeatureFlag = checked
+ }}
+ label={
+ <span>
+ Also disable and archive the linked feature flag{' '}
+ <code>{experiment.feature_flag?.key}</code>. It's still enabled — if your code still
+ references it, users will fall back to the default. Only do this after removing it from
+ your codebase.
+ </span>
+ }
+ />
+ )}
</div>
),
primaryButton: {
children: 'Archive',
type: 'primary',
- onClick: onConfirm,
+ onClick: () => onConfirm(disableFeatureFlag),
size: 'small',
},
secondaryButton: {
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 5b284a855bb7..131fc6659cb1 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -1114,7 +1114,9 @@ describe('experimentLogic', () => {
.toDispatchActions(['archiveExperiment', 'setExperiment'])
.toFinishAllListeners()
- expect(createSpy).toHaveBeenCalledWith(expect.stringContaining(`/experiments/${experiment.id}/archive`))
+ expect(createSpy).toHaveBeenCalledWith(expect.stringContaining(`/experiments/${experiment.id}/archive`), {
+ disable_feature_flag: false,
+ })
createSpy.mockRestore()
keyed.unmount()
})
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index a981f53966c3..03fad3c2c41e 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -714,7 +714,7 @@ export const experimentLogic = kea<experimentLogicType>([
}) => ({ selectedVariantKey, releaseToEveryone }),
pauseExperiment: true,
resumeExperiment: true,
- archiveExperiment: true,
+ archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),
unarchiveExperiment: true,
resetRunningExperiment: true,
updateExperimentVariantImages: (variantPreviewMediaIds: Record<string, string[]>) => ({
@@ -1560,10 +1560,11 @@ export const experimentLogic = kea<experimentLogicType>([
lemonToast.error(error.detail || 'Failed to resume experiment')
}
},
- archiveExperiment: async () => {
+ archiveExperiment: async ({ disableFeatureFlag }) => {
try {
const response: Experiment = await api.create(
- `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/archive`
+ `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/archive`,
+ { disable_feature_flag: disableFeatureFlag }
)
actions.setExperiment(response)
refreshTreeItem('experiment', String(values.experimentId))
diff --git a/frontend/src/scenes/experiments/experimentsLogic.test.ts b/frontend/src/scenes/experiments/experimentsLogic.test.ts
index cfcc035c8b7b..1b6de6f87b70 100644
--- a/frontend/src/scenes/experiments/experimentsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentsLogic.test.ts
@@ -332,7 +332,7 @@ describe('experimentsLogic', () => {
api.create.mockResolvedValue({})
await expectLogic(logic, () => {
- logic.actions.archiveExperiment(mockExperiment.id as number)
+ logic.actions.archiveExperiment({ id: mockExperiment.id as number, disableFeatureFlag: false })
})
.toFinishAllListeners()
.toMatchValues({
@@ -343,7 +343,8 @@ describe('experimentsLogic', () => {
})
expect(api.create).toHaveBeenCalledWith(
- expect.stringContaining(`/experiments/${mockExperiment.id}/archive`)
+ expect.stringContaining(`/experiments/${mockExperiment.id}/archive`),
+ { disable_feature_flag: false }
)
})
diff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.ts
index ed9f5db87bb6..15a42e0caa7f 100644
--- a/frontend/src/scenes/experiments/experimentsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentsLogic.ts
@@ -281,8 +281,10 @@ export const experimentsLogic = kea<experimentsLogicType>([
offset: values.paramsFromFilters.offset,
}
},
- archiveExperiment: async (id: number) => {
- await api.create(`api/projects/${values.currentProjectId}/experiments/${id}/archive`)
+ archiveExperiment: async ({ id, disableFeatureFlag }: { id: number; disableFeatureFlag: boolean }) => {
+ await api.create(`api/projects/${values.currentProjectId}/experiments/${id}/archive`, {
+ disable_feature_flag: disableFeatureFlag,
+ })
lemonToast.info('Experiment archived')
return {
...values.experiments,
diff --git a/frontend/src/scenes/experiments/legacy/components/LegacyPageHeader.tsx b/frontend/src/scenes/experiments/legacy/components/LegacyPageHeader.tsx
index 0f9bb3bd8964..d79e0fa63459 100644
--- a/frontend/src/scenes/experiments/legacy/components/LegacyPageHeader.tsx
+++ b/frontend/src/scenes/experiments/legacy/components/LegacyPageHeader.tsx
@@ -50,7 +50,8 @@ export function LegacyPageHeader(): JSX.Element {
const canArchive = canEdit && canArchiveExperiment(experiment)
const canDelete = canEdit
- const handleArchive = (): void => confirmArchiveExperiment(() => archiveExperiment())
+ const handleArchive = (): void =>
+ confirmArchiveExperiment(experiment, (disableFlag) => archiveExperiment(disableFlag))
const handleDelete = (): void =>
confirmDeleteExperiment({
projectId: currentProjectId,
diff --git a/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx b/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
index 804bec004fdb..fb2b1acb52d8 100644
--- a/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
+++ b/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
@@ -336,7 +336,7 @@ export const legacyExperimentLogic = kea<legacyExperimentLogicType>([
})),
actions({
// Experiment mutations
- archiveExperiment: true,
+ archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),
endExperiment: true,
endExperimentWithoutShipping: true,
finishExperiment: ({ selectedVariantKey }: { selectedVariantKey: string }) => ({ selectedVariantKey }),
@@ -451,10 +451,11 @@ export const legacyExperimentLogic = kea<legacyExperimentLogicType>([
return
}
},
- archiveExperiment: async () => {
+ archiveExperiment: async ({ disableFeatureFlag }) => {
try {
const response: Experiment = await api.create(
- `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/archive`
+ `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/archive`,
+ { disable_feature_flag: disableFeatureFlag }
)
actions.setExperiment(response)
refreshTreeItem('experiment', String(values.experimentId))
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index 18fe3a19c97b..9d49ea8947fd 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -552,6 +552,7 @@ describe('checkFeatureFlagEligibility', () => {
multivariate: null,
},
deleted: false,
+ archived: false,
active: true,
experiment_set: null,
experiment_set_metadata: null,
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
index f79cc4eb374c..41d688b9adab 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
@@ -4,8 +4,8 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { useEffect, useState } from 'react'
-import { IconCopy, IconPlusSmall, IconRewind, IconTrash } from '@posthog/icons'
-import { LemonDialog, LemonSkeleton } from '@posthog/lemon-ui'
+import { IconArchive, IconCopy, IconPlusSmall, IconRewind, IconTrash } from '@posthog/icons'
+import { LemonSkeleton } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { AccessDenied } from 'lib/components/AccessDenied'
@@ -78,6 +78,8 @@ import {
QueryBasedInsightModel,
} from '~/types'
+import { openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'
+import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'
import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'
import { ExperimentsTab } from './FeatureFlagExperimentsTab'
import { FeedbackTab } from './FeatureFlagFeedbackTab'
@@ -109,6 +111,8 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
activeTab,
accessDeniedToFeatureFlag,
earlyAccessFeaturesList,
+ featureFlagActiveUpdateLoading,
+ dependentFlags,
} = useValues(featureFlagLogic)
const { featureFlags } = useValues(enabledFeaturesLogic)
const {
@@ -121,6 +125,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
saveFeatureFlag,
saveDescriptionInline,
saveTagsInline,
+ updateFeatureFlagArchived,
} = useActions(featureFlagLogic)
const { tags } = useValues(tagsModel)
@@ -342,6 +347,39 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
</ScenePanelActionsSection>
<ScenePanelDivider />
<ScenePanelActionsSection>
+ {!featureFlag.deleted && (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.FeatureFlag}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ {({ disabledReason }) => (
+ <ButtonPrimitive
+ menuItem
+ disabled={!!disabledReason || featureFlagActiveUpdateLoading}
+ {...(disabledReason && { tooltip: disabledReason })}
+ data-attr={
+ featureFlag.archived ? 'unarchive-feature-flag' : 'archive-feature-flag'
+ }
+ onClick={() => {
+ if (featureFlag.archived) {
+ updateFeatureFlagArchived(false)
+ } else {
+ openFeatureFlagArchiveDialog(featureFlag, () =>
+ updateFeatureFlagArchived(true)
+ )
+ }
+ }}
+ disabledReasons={{
+ "You have only 'View' access for this feature flag. To make changes, please contact the flag's creator.":
+ !featureFlag.can_edit,
+ }}
+ >
+ {featureFlag.archived ? <IconRewind /> : <IconArchive />}
+ {featureFlag.archived ? 'Unarchive' : 'Archive'} feature flag
+ </ButtonPrimitive>
+ )}
+ </AccessControlAction>
+ )}
<AccessControlAction
resourceType={AccessControlResourceType.FeatureFlag}
minAccessLevel={AccessControlLevel.Editor}
@@ -357,34 +395,16 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
if (featureFlag.deleted) {
restoreFeatureFlag(featureFlag)
} else {
- LemonDialog.open({
- title: 'Delete feature flag?',
- description: `Are you sure you want to delete "${featureFlag.key}"?`,
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => deleteFeatureFlag(featureFlag),
- size: 'small',
- },
- secondaryButton: {
- children: 'Cancel',
- type: 'tertiary',
- size: 'small',
- },
- })
+ openFeatureFlagDeleteDialog(
+ featureFlag,
+ () => deleteFeatureFlag(featureFlag),
+ dependentFlags
+ )
}
}}
disabledReasons={{
"You have only 'View' access for this feature flag. To make changes, please contact the flag's creator.":
!featureFlag.can_edit,
- 'This feature flag is in use with an early access feature. Delete the early access feature to delete this flag':
- (featureFlag.features?.length || 0) > 0,
- 'This feature flag is linked to a running experiment. Stop the experiment to delete this flag':
- featureFlag.experiment_set_metadata?.some((exp) => exp.is_running) || false,
- 'This feature flag is linked to a survey. Delete the survey to delete this flag':
- (featureFlag.surveys?.length || 0) > 0,
- 'This feature flag is used in session replay settings for recording conditions. Remove it from replay settings to delete this flag':
- featureFlag.is_used_in_replay_settings || false,
}}
>
{featureFlag.deleted ? <IconRewind /> : <IconTrash />}
@@ -399,6 +419,23 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
<PendingChangeRequestBanner resourceType="feature_flag" resourceId={featureFlag.id} />
)}
+ {featureFlag.archived && (
+ <LemonBanner
+ type="warning"
+ action={
+ featureFlag.can_edit
+ ? {
+ children: 'Unarchive',
+ onClick: () => updateFeatureFlagArchived(false),
+ disabledReason: featureFlagActiveUpdateLoading ? 'Updating…' : undefined,
+ }
+ : undefined
+ }
+ >
+ This feature flag is archived. It's hidden from the flag list and can't be enabled — linked
+ experiments and surveys keep their data.
+ </LemonBanner>
+ )}
{earlyAccessFeature && earlyAccessFeature.stage === EarlyAccessFeatureStage.Concept && (
<LemonBanner type="info">
This feature flag is assigned to an early access feature in the{' '}
@@ -463,21 +500,11 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
if (featureFlag.deleted) {
restoreFeatureFlag(featureFlag)
} else {
- LemonDialog.open({
- title: 'Delete feature flag?',
- description: `Are you sure you want to delete "${featureFlag.key}"?`,
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => deleteFeatureFlag(featureFlag),
- size: 'small',
- },
- secondaryButton: {
- children: 'Cancel',
- type: 'tertiary',
- size: 'small',
- },
- })
+ openFeatureFlagDeleteDialog(
+ featureFlag,
+ () => deleteFeatureFlag(featureFlag),
+ dependentFlags
+ )
}
}}
>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagCodeInstructions.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlagCodeInstructions.stories.tsx
index 13af4fdc8afb..3877321160de 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagCodeInstructions.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagCodeInstructions.stories.tsx
@@ -26,6 +26,7 @@ const REGULAR_FEATURE_FLAG: FeatureFlagType = {
features: [],
active: true,
deleted: false,
+ archived: false,
created_at: '2021-05-05T12:00:00Z',
updated_at: '2021-05-05T12:00:00Z',
created_by: null,
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
index 0c4a03d41831..3285bb458e50 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
@@ -104,9 +104,11 @@ export function FeatureFlagFiltersSection({
dropdownMatchSelectWidth={false}
size="small"
onChange={(status) => {
- const { active, ...restFilters } = filters || {}
+ const { active, archived, ...restFilters } = filters || {}
if (status === 'all') {
setFeatureFlagsFilters({ ...restFilters, page: 1 }, true)
+ } else if (status === 'ARCHIVED') {
+ setFeatureFlagsFilters({ ...restFilters, archived: 'true', page: 1 }, true)
} else {
setFeatureFlagsFilters({ ...restFilters, active: status, page: 1 }, true)
}
@@ -124,8 +126,13 @@ export function FeatureFlagFiltersSection({
value: 'STALE',
'data-attr': 'feature-flag-select-status-stale',
},
+ {
+ label: 'Archived',
+ value: 'ARCHIVED',
+ 'data-attr': 'feature-flag-select-status-archived',
+ },
]}
- value={filters.active ?? 'all'}
+ value={filters.archived === 'true' ? 'ARCHIVED' : (filters.active ?? 'all')}
data-attr="feature-flag-select-status"
/>
</>
@@ -163,6 +170,20 @@ export function FeatureFlagFiltersSection({
}}
data-attr="feature-flag-select-tags"
/>
+ <span className="ml-1">
+ <b>Exclude tags</b>
+ </span>
+ <TagSelect
+ defaultLabel="No tags"
+ value={filters.excluded_tags || []}
+ onChange={(excludedTags) => {
+ setFeatureFlagsFilters({
+ excluded_tags: excludedTags.length > 0 ? excludedTags : undefined,
+ page: 1,
+ })
+ }}
+ data-attr="feature-flag-select-excluded-tags"
+ />
</>
)}
{config.runtime && (
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
index d4e1e8ad16e8..4411728d2014 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
@@ -58,6 +58,8 @@ import {
import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'
import { BulkDeleteResultsModal } from './BulkDeleteResultsModal'
+import { openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'
+import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'
import { FeatureFlagFiltersSection } from './FeatureFlagFilters'
import { FLAGS_PER_PAGE, FeatureFlagsTab, featureFlagsLogic, flagMatchesType } from './featureFlagsLogic'
import { flagSelectionLogic } from './flagSelectionLogic'
@@ -99,6 +101,14 @@ function FeatureFlagStatusCell({ featureFlag }: { featureFlag: FeatureFlagType }
Updating
</span>
</LemonTag>
+ ) : featureFlag.archived ? (
+ <Tooltip title="This flag is done for good. It's hidden from the flag list by default, but linked experiments and surveys keep their data.">
+ <span>
+ <LemonTag type="muted" className="uppercase cursor-default">
+ Archived
+ </LemonTag>
+ </span>
+ </Tooltip>
) : featureFlag.active ? (
<LemonTag type="success" className="uppercase">
Enabled
@@ -221,7 +231,13 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }
id={`feature-flag-${featureFlag.id}-switch`}
fullWidth
loading={isUpdating}
- disabledReason={isUpdating ? 'Updating…' : undefined}
+ disabledReason={
+ isUpdating
+ ? 'Updating…'
+ : featureFlag.archived
+ ? 'Unarchive this flag before enabling it.'
+ : undefined
+ }
>
{featureFlag.active ? 'Disable' : 'Enable'} feature flag
</LemonButton>
@@ -269,6 +285,40 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }
<LemonDivider />
+ {featureFlag.id && (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.FeatureFlag}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={featureFlag.user_access_level}
+ >
+ <LemonButton
+ data-attr={`feature-flag-${featureFlag.key}-${featureFlag.archived ? 'unarchive' : 'archive'}`}
+ onClick={() => {
+ if (featureFlag.archived) {
+ featureFlag.id &&
+ updateFeatureFlag({
+ id: featureFlag.id,
+ payload: { archived: false },
+ })
+ return
+ }
+ openFeatureFlagArchiveDialog(featureFlag, () => {
+ featureFlag.id &&
+ updateFeatureFlag({
+ id: featureFlag.id,
+ payload: { archived: true, active: false },
+ })
+ })
+ }}
+ fullWidth
+ loading={isUpdating}
+ disabledReason={isUpdating ? 'Updating…' : undefined}
+ >
+ {featureFlag.archived ? 'Unarchive' : 'Archive'} feature flag
+ </LemonButton>
+ </AccessControlAction>
+ )}
+
{featureFlag.id && (
<AccessControlAction
resourceType={AccessControlResourceType.FeatureFlag}
@@ -278,40 +328,20 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }
<LemonButton
status="danger"
onClick={() => {
- LemonDialog.open({
- title: 'Delete feature flag?',
- description: `Are you sure you want to delete "${featureFlag.key}"?`,
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => {
- void deleteWithUndo({
- endpoint: `projects/${currentProjectId}/feature_flags`,
- object: { name: featureFlag.key, id: featureFlag.id },
- callback: loadFeatureFlags,
- }).catch((e) => {
- lemonToast.error(`Failed to delete feature flag: ${e.detail}`)
- })
- },
- size: 'small',
- },
- secondaryButton: {
- children: 'Cancel',
- type: 'tertiary',
- size: 'small',
- },
+ openFeatureFlagDeleteDialog(featureFlag, () => {
+ void deleteWithUndo({
+ endpoint: `projects/${currentProjectId}/feature_flags`,
+ object: { name: featureFlag.key, id: featureFlag.id },
+ callback: loadFeatureFlags,
+ }).catch((e) => {
+ lemonToast.error(`Failed to delete feature flag: ${e.detail}`)
+ })
})
}}
disabledReason={
!featureFlag.can_edit
? "You have only 'View' access for this feature flag. To make changes, please contact the flag's creator."
- : (featureFlag.features?.length || 0) > 0
- ? 'This feature flag is in use with an early access feature. Delete the early access feature to delete this flag'
- : featureFlag.experiment_set_metadata?.some((exp) => exp.is_running)
- ? 'This feature flag is linked to a running experiment. Stop the experiment to delete this flag.'
- : (featureFlag.surveys?.length || 0) > 0
- ? 'This feature flag is linked to a survey. Delete the survey to delete this flag.'
- : null
+ : null
}
fullWidth
>
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
index 518dd2cd0d03..3e123531001d 100644
--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx
+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
@@ -266,6 +266,13 @@ const featureFlagActionsMapping: Record<
suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
}
},
+ archived: function onArchived(change, logItem) {
+ const isArchived = detectBoolean(change?.after)
+ return {
+ description: [<>{isArchived ? 'archived' : 'unarchived'}</>],
+ suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
+ }
+ },
key: function onKey(change, logItem) {
const changeBefore = change?.before as string
const changeAfter = change?.after as string
diff --git a/frontend/src/scenes/feature-flags/featureFlagArchiveDialog.tsx b/frontend/src/scenes/feature-flags/featureFlagArchiveDialog.tsx
new file mode 100644
index 000000000000..0f5115d49d02
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagArchiveDialog.tsx
@@ -0,0 +1,31 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { FeatureFlagType } from '~/types'
+
+/**
+ * Opens the archive confirmation dialog for a feature flag. The warning copy lives here so the
+ * detail page and the list share one source of truth — only the confirm callback differs.
+ * Unarchiving is immediate at the call site, so it doesn't go through this dialog.
+ */
+export function openFeatureFlagArchiveDialog(
+ featureFlag: Pick<FeatureFlagType, 'active'>,
+ onArchive: () => void
+): void {
+ LemonDialog.open({
+ title: 'Archive this flag?',
+ description: featureFlag.active
+ ? 'This flag is currently enabled — archiving will disable it and immediately roll it back from users matching the release conditions. Archived flags are hidden from the flag list, but linked experiments and surveys keep their data.'
+ : 'Archived flags are hidden from the flag list, but linked experiments and surveys keep their data. You can unarchive it at any time.',
+ primaryButton: {
+ children: 'Archive',
+ type: 'primary',
+ onClick: onArchive,
+ size: 'small',
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ type: 'tertiary',
+ size: 'small',
+ },
+ })
+}
diff --git a/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.test.ts b/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.test.ts
new file mode 100644
index 000000000000..982d74bf21fa
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.test.ts
@@ -0,0 +1,75 @@
+import { FeatureFlagType } from '~/types'
+
+import { getFeatureFlagDeleteBlockers } from './featureFlagDeleteDialog'
+
+const base: Partial<FeatureFlagType> = {
+ key: 'my-flag',
+ features: [],
+ experiment_set_metadata: [],
+ surveys: [],
+ is_used_in_replay_settings: false,
+}
+
+describe('getFeatureFlagDeleteBlockers', () => {
+ it('returns empty array when nothing blocks deletion', () => {
+ expect(getFeatureFlagDeleteBlockers(base)).toEqual([])
+ })
+
+ it('blocks on an early access feature', () => {
+ const flag = { ...base, features: [{ id: '1', name: 'My Feature' }] } as Partial<FeatureFlagType>
+ const blockers = getFeatureFlagDeleteBlockers(flag)
+ expect(blockers).toHaveLength(1)
+ expect(blockers[0].kind).toBe('Early access feature')
+ expect(blockers[0].name).toBe('My Feature')
+ })
+
+ it('blocks on a running experiment', () => {
+ const flag = {
+ ...base,
+ experiment_set_metadata: [{ id: 1, name: 'My Experiment', is_running: true }],
+ } as Partial<FeatureFlagType>
+ const blockers = getFeatureFlagDeleteBlockers(flag)
+ expect(blockers).toHaveLength(1)
+ expect(blockers[0].kind).toBe('Running experiment')
+ expect(blockers[0].name).toBe('My Experiment')
+ })
+
+ it('does not block on a stopped experiment', () => {
+ const flag = {
+ ...base,
+ experiment_set_metadata: [{ id: 1, name: 'My Experiment', is_running: false }],
+ } as Partial<FeatureFlagType>
+ expect(getFeatureFlagDeleteBlockers(flag)).toEqual([])
+ })
+
+ it('blocks on a survey', () => {
+ const flag = { ...base, surveys: [{ id: '1', name: 'My Survey' }] } as Partial<FeatureFlagType>
+ const blockers = getFeatureFlagDeleteBlockers(flag)
+ expect(blockers).toHaveLength(1)
+ expect(blockers[0].kind).toBe('Survey')
+ expect(blockers[0].name).toBe('My Survey')
+ })
+
+ it('blocks when used in replay settings', () => {
+ const flag = { ...base, is_used_in_replay_settings: true } as Partial<FeatureFlagType>
+ const blockers = getFeatureFlagDeleteBlockers(flag)
+ expect(blockers).toHaveLength(1)
+ expect(blockers[0].kind).toBe('Session replay')
+ })
+
+ it('accumulates multiple blockers', () => {
+ const flag = {
+ ...base,
+ features: [{ id: '1', name: 'Feature A' }],
+ experiment_set_metadata: [{ id: 1, name: 'Exp A', is_running: true }],
+ surveys: [{ id: '1', name: 'Survey A' }],
+ is_used_in_replay_settings: true,
+ } as Partial<FeatureFlagType>
+ expect(getFeatureFlagDeleteBlockers(flag).map((b) => b.kind)).toEqual([
+ 'Early access feature',
+ 'Running experiment',
+ 'Survey',
+ 'Session replay',
+ ])
+ })
+})
diff --git a/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.tsx b/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.tsx
new file mode 100644
index 000000000000..05a8a15de2a2
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagDeleteDialog.tsx
@@ -0,0 +1,111 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { FeatureFlagType } from '~/types'
+
+import { DependentFlag } from './featureFlagLogic'
+
+interface FeatureFlagDeleteBlocker {
+ kind: string
+ name: string
+ url?: string
+}
+
+export function getFeatureFlagDeleteBlockers(
+ featureFlag: Partial<FeatureFlagType>,
+ dependentFlags: DependentFlag[] = []
+): FeatureFlagDeleteBlocker[] {
+ const blockers: FeatureFlagDeleteBlocker[] = []
+ for (const feature of featureFlag.features || []) {
+ blockers.push({
+ kind: 'Early access feature',
+ name: feature.name,
+ url: urls.earlyAccessFeature(feature.id),
+ })
+ }
+ for (const experiment of featureFlag.experiment_set_metadata || []) {
+ if (experiment.is_running) {
+ blockers.push({ kind: 'Running experiment', name: experiment.name, url: urls.experiment(experiment.id) })
+ }
+ }
+ for (const survey of featureFlag.surveys || []) {
+ blockers.push({ kind: 'Survey', name: survey.name, url: urls.survey(survey.id) })
+ }
+ if (featureFlag.is_used_in_replay_settings) {
+ blockers.push({
+ kind: 'Session replay',
+ name: 'Recording conditions in replay settings',
+ url: urls.settings('project-replay'),
+ })
+ }
+ for (const flag of dependentFlags) {
+ blockers.push({
+ kind: 'Feature flag',
+ name: flag.name || flag.key,
+ url: urls.featureFlag(flag.id),
+ })
+ }
+ return blockers
+}
+
+/**
+ * Opens the delete confirmation dialog for a feature flag. If linked resources block deletion,
+ * shows what's blocking it — with direct links — instead of the confirmation.
+ */
+export function openFeatureFlagDeleteDialog(
+ featureFlag: Partial<FeatureFlagType>,
+ onDelete: () => void,
+ dependentFlags: DependentFlag[] = []
+): void {
+ const blockers = getFeatureFlagDeleteBlockers(featureFlag, dependentFlags)
+
+ if (blockers.length > 0) {
+ LemonDialog.open({
+ title: "This feature flag can't be deleted yet",
+ description: (
+ <div className="deprecated-space-y-2">
+ <div>
+ <code>{featureFlag.key}</code> is still in use. Unlink or delete the following before deleting
+ this flag:
+ </div>
+ <ul className="list-disc pl-5">
+ {blockers.map((blocker, index) => (
+ <li key={index}>
+ {blocker.kind}:{' '}
+ {blocker.url ? (
+ <Link to={blocker.url}>{blocker.name || 'Untitled'}</Link>
+ ) : (
+ blocker.name
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ),
+ primaryButton: {
+ children: 'Close',
+ type: 'secondary',
+ size: 'small',
+ },
+ })
+ return
+ }
+
+ LemonDialog.open({
+ title: 'Delete feature flag?',
+ description: `Are you sure you want to delete "${featureFlag.key}"?`,
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: onDelete,
+ size: 'small',
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ type: 'tertiary',
+ size: 'small',
+ },
+ })
+}
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index b89701be06d9..f5401a5fbd98 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -248,6 +248,7 @@ export const NEW_FLAG: FeatureFlagType = {
},
deleted: false,
active: true,
+ archived: false,
created_by: null,
ensure_experience_continuity: false,
experiment_set: null,
@@ -1449,6 +1450,19 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
savedFlag.id && refreshTreeItem('feature_flag', String(savedFlag.id))
return variantKeyToIndexFeatureFlagPayloads(savedFlag)
},
+ // Shares the featureFlagActiveUpdate loader key (and its loading/success state)
+ updateFeatureFlagArchived: async (archived: boolean) => {
+ if (!values.featureFlag.id) {
+ throw new Error('Cannot archive an unsaved flag')
+ }
+ // Archiving also disables the flag — the backend rejects archived+enabled flags
+ const savedFlag = await api.update(
+ `api/projects/${values.currentProjectId}/feature_flags/${values.featureFlag.id}`,
+ archived ? { archived: true, active: false } : { archived: false }
+ )
+ savedFlag.id && refreshTreeItem('feature_flag', String(savedFlag.id))
+ return variantKeyToIndexFeatureFlagPayloads(savedFlag)
+ },
},
],
relatedInsights: [
@@ -1913,6 +1927,21 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
actions.updateFlag(featureFlagActiveUpdate)
}
},
+ updateFeatureFlagArchivedSuccess: ({ featureFlagActiveUpdate }) => {
+ if (featureFlagActiveUpdate) {
+ lemonToast.success(`Feature flag ${featureFlagActiveUpdate.archived ? 'archived' : 'unarchived'}`)
+ actions.setFeatureFlag(featureFlagActiveUpdate)
+ actions.updateFlag(featureFlagActiveUpdate)
+ }
+ },
+ updateFeatureFlagArchivedFailure: ({ errorObject }) => {
+ // Archiving an enabled flag also disables it, which can trip the approval gate (409).
+ // Surface the change-request flow instead of silently doing nothing.
+ if (values.featureFlag.id && handleApprovalRequired(errorObject, 'feature_flag', values.featureFlag.id)) {
+ return
+ }
+ // For non-approval errors, let the global error handler show the toast to avoid duplicates
+ },
saveSidebarExperimentFeatureFlagSuccess: ({ featureFlag }) => {
lemonToast.success('Release conditions updated')
actions.updateFlag(featureFlag)
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
index 169e2b08713b..d706f30f00d1 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
@@ -5,6 +5,7 @@ import api from 'lib/api'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { NEW_FLAG } from 'scenes/feature-flags/featureFlagLogic'
import {
+ FeatureFlagsFilters,
FeatureFlagsTab,
featureFlagsLogic,
flagMatchesFilters,
@@ -157,25 +158,73 @@ describe('flagMatchesType', () => {
})
})
-describe('flagMatchesFilters creator filter', () => {
- const flagByUser = (id: number | null): FeatureFlagType =>
- ({
- ...NEW_FLAG,
- id: 1,
- key: 'test',
- created_by: id == null ? null : ({ id } as FeatureFlagType['created_by']),
- }) as FeatureFlagType
-
- it.each<[string, number | null, number[] | undefined, boolean]>([
- ['no filter set matches any flag', 7, undefined, true],
- ['no filter set matches a creatorless flag', null, undefined, true],
- ['no filter set matches a creatorless flag with empty list', null, [], true],
- ['author in the list matches', 7, [7], true],
- ['author in a multi-id list matches', 7, [3, 7], true],
- ['author absent from the list does not match', 7, [3, 5], false],
- ['creatorless flag is excluded once a filter is set', null, [7], false],
- ])('%s', (_name, createdById, createdByIdFilter, expected) => {
- expect(flagMatchesFilters(flagByUser(createdById), { created_by_id: createdByIdFilter })).toBe(expected)
+describe('flagMatchesFilters', () => {
+ const base = { ...NEW_FLAG, id: 1, key: 'test', active: true } as FeatureFlagType
+
+ describe('archived filter', () => {
+ const liveFlag = { ...base, archived: false } as FeatureFlagType
+ const archivedFlag = { ...base, archived: true } as FeatureFlagType
+
+ it.each<[string, FeatureFlagType, Partial<FeatureFlagsFilters>, boolean]>([
+ ['hides archived by default', archivedFlag, {}, false],
+ ['shows live flags by default', liveFlag, {}, true],
+ ['shows archived when archived=true', archivedFlag, { archived: 'true' }, true],
+ ['hides live when archived=true', liveFlag, { archived: 'true' }, false],
+ ])('%s', (_label, flag, filters, expected) => {
+ expect(flagMatchesFilters(flag, filters as FeatureFlagsFilters)).toBe(expected)
+ })
+ })
+
+ describe('excluded_tags filter', () => {
+ const flagWithTag = { ...base, archived: false, tags: ['beta', 'internal'] } as FeatureFlagType
+ const flagWithoutTag = { ...base, archived: false, tags: ['beta'] } as FeatureFlagType
+
+ it.each<[string, FeatureFlagType, Partial<FeatureFlagsFilters>, boolean]>([
+ ['excludes a flag whose tag matches excluded_tags', flagWithTag, { excluded_tags: ['internal'] }, false],
+ [
+ 'keeps a flag whose tags do not match excluded_tags',
+ flagWithoutTag,
+ { excluded_tags: ['internal'] },
+ true,
+ ],
+ ['keeps a flag when excluded_tags is empty', flagWithTag, { excluded_tags: [] }, true],
+ [
+ 'keeps an untagged flag when excluded_tags is set',
+ // Deliberately undefined tags to exercise the optional-chaining guard in flagMatchesFilters.
+ { ...base, tags: undefined } as unknown as FeatureFlagType,
+ { excluded_tags: ['internal'] },
+ true,
+ ],
+ [
+ 'excluded_tags wins over tags when both match',
+ flagWithTag,
+ { tags: ['beta'], excluded_tags: ['beta'] },
+ false,
+ ],
+ ])('%s', (_label, flag, filters, expected) => {
+ expect(flagMatchesFilters(flag, filters as FeatureFlagsFilters)).toBe(expected)
+ })
+ })
+
+ describe('creator filter', () => {
+ const flagByUser = (id: number | null): FeatureFlagType =>
+ ({
+ ...base,
+ archived: false,
+ created_by: id == null ? null : ({ id } as FeatureFlagType['created_by']),
+ }) as FeatureFlagType
+
+ it.each<[string, number | null, number[] | undefined, boolean]>([
+ ['no filter set matches any flag', 7, undefined, true],
+ ['no filter set matches a creatorless flag', null, undefined, true],
+ ['no filter set matches a creatorless flag with empty list', null, [], true],
+ ['author in the list matches', 7, [7], true],
+ ['author in a multi-id list matches', 7, [3, 7], true],
+ ['author absent from the list does not match', 7, [3, 5], false],
+ ['creatorless flag is excluded once a filter is set', null, [7], false],
+ ])('%s', (_name, createdById, createdByIdFilter, expected) => {
+ expect(flagMatchesFilters(flagByUser(createdById), { created_by_id: createdByIdFilter })).toBe(expected)
+ })
})
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
index aa222ed3d996..c9ac4885feb5 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
@@ -96,9 +96,13 @@ export function flagMatchesFilters(flag: FeatureFlagType, filters: FeatureFlagsF
flagMatchesSearch(flag, filters.search) &&
flagMatchesStatus(flag, filters.active) &&
flagMatchesType(flag, filters.type) &&
+ // Archived flags are hidden unless explicitly filtered for, mirroring the API default
+ (filters.archived === 'true' ? !!flag.archived : !flag.archived) &&
(!filters.created_by_id?.length ||
(flag.created_by != null && filters.created_by_id.includes(flag.created_by.id))) &&
(!filters.tags?.length || filters.tags.some((tag) => flag.tags?.includes(tag))) &&
+ // excluded_tags wins over tags on conflict (AND semantics)
+ (!filters.excluded_tags?.length || !filters.excluded_tags.some((tag) => flag.tags?.includes(tag))) &&
(!filters.evaluation_runtime || flag.evaluation_runtime === filters.evaluation_runtime)
)
}
@@ -126,6 +130,8 @@ export interface FeatureFlagsResult extends CountedPaginatedResponse<FeatureFlag
export interface FeatureFlagsFilters {
active?: string
+ /** 'true' shows only archived flags; when unset, archived flags are excluded */
+ archived?: string
created_by_id?: number[]
type?: string
search?: string
@@ -133,10 +139,12 @@ export interface FeatureFlagsFilters {
page?: number
evaluation_runtime?: string
tags?: string[]
+ excluded_tags?: string[]
}
const DEFAULT_FILTERS: FeatureFlagsFilters = {
active: undefined,
+ archived: undefined,
created_by_id: undefined,
type: undefined,
search: undefined,
@@ -144,6 +152,7 @@ const DEFAULT_FILTERS: FeatureFlagsFilters = {
page: 1,
evaluation_runtime: undefined,
tags: undefined,
+ excluded_tags: undefined,
}
export interface FlagLogicProps {
@@ -419,16 +428,19 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
actions.setActiveTab(tabInURL)
}
- const { page, created_by_id, active, type, search, order, evaluation_runtime, tags } = searchParams
+ const { page, created_by_id, active, archived, type, search, order, evaluation_runtime, tags } =
+ searchParams
const pageFiltersFromUrl: Partial<FeatureFlagsFilters> = {
created_by_id: parseNumericArrayFilter(created_by_id),
type,
order,
evaluation_runtime,
tags: parseTagsFilter(tags),
+ excluded_tags: parseTagsFilter(searchParams['excluded_tags']),
}
pageFiltersFromUrl.active = active !== undefined ? String(active) : undefined
+ pageFiltersFromUrl.archived = archived !== undefined ? String(archived) : undefined
pageFiltersFromUrl.page = page !== undefined ? parseInt(page) : undefined
pageFiltersFromUrl.search = search !== undefined ? String(search) : undefined
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index b2f3994e4e1f..b2f8e6bb3593 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4234,6 +4234,8 @@ export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'team
experiment_set_metadata: { id: number; name: string; is_running: boolean }[] | null
features: MinimalEarlyAccessFeatureType[] | null
surveys: Survey[] | null
+ /** Archived flags are hidden from the flag list by default and must be disabled. */
+ archived: boolean
can_edit: boolean
tags: string[]
evaluation_contexts: string[]
@@ -4241,7 +4243,7 @@ export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'team
has_enriched_analytics?: boolean
is_remote_configuration: boolean
has_encrypted_payloads: boolean
- status: 'ACTIVE' | 'STALE' | 'DELETED' | 'UNKNOWN'
+ status: 'ACTIVE' | 'STALE' | 'ARCHIVED' | 'DELETED' | 'UNKNOWN'
_create_in_folder?: string | null
evaluation_runtime: FeatureFlagEvaluationRuntime
bucketing_identifier?: FeatureFlagBucketingIdentifier | null
@@ -4277,6 +4279,7 @@ export type OrganizationFeatureFlags = {
export enum FeatureFlagStatus {
ACTIVE = 'active',
STALE = 'stale',
+ ARCHIVED = 'archived',
DELETED = 'deleted',
UNKNOWN = 'unknown',
}
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 110b844f5e25..9f4a0e85b135 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -420,6 +420,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {
],
"Experiment": [
"feature_flag",
+ "feature_flag_auto_archived",
"exposure_cohort",
"holdout",
"saved_metrics",
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 0d41e8df1146..e7ad8d2b923d 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -206,6 +206,7 @@
list([
'description',
'exposure_criteria',
+ 'feature_flag_auto_archived',
'filters',
'metrics',
'metrics_secondary',
@@ -245,6 +246,7 @@
# name: TestVisitorFieldSnapshots.test_primitive_fields_FeatureFlag
list([
'active',
+ 'archived',
'bucketing_identifier',
'created_at',
'ensure_experience_continuity',
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index e22e147c5d79..ddbf210004fa 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -327,6 +327,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
@@ -509,6 +510,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -702,6 +704,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -733,6 +736,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1073,6 +1077,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
@@ -1104,6 +1109,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1393,6 +1399,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1578,6 +1585,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1609,6 +1617,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
diff --git a/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr b/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
index c9d5ef7e05aa..980e2e5b89d6 100644
--- a/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
+++ b/products/early_access_features/backend/test/__snapshots__/test_early_access_feature.ambr
@@ -166,6 +166,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -628,6 +629,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -909,6 +911,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1088,6 +1091,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index aa87a521b9b8..f6ec446d1e3d 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -16,7 +16,7 @@ from django.utils import timezone
import pydantic
import structlog
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from posthog.schema import (
ActionsNode,
@@ -27,11 +27,14 @@ from posthog.schema import (
)
from posthog.api.cohort import CohortSerializer
+from posthog.approvals.policies import PolicyEngine
from posthog.event_usage import EventSource, report_user_action
from posthog.models.filters.filter import Filter
from posthog.models.signals import mute_selected_signals
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.rbac.user_access_control import UserAccessControl
from posthog.utils import str_to_bool
from products.actions.backend.models.action import Action
@@ -53,7 +56,11 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.result_serialization import strip_step_sessions
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, parse_created_by_ids
+from products.feature_flags.backend.api.feature_flag import (
+ FeatureFlagSerializer,
+ parse_created_by_ids,
+ raise_if_flag_has_dependents,
+)
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notifications.backend.facade.api import (
@@ -1326,8 +1333,24 @@ class ExperimentService:
# ------------------------------------------------------------------
@transaction.atomic
- def archive_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
- """Archive an ended experiment: validate it has ended, set archived=True."""
+ def archive_experiment(
+ self,
+ experiment: Experiment,
+ *,
+ disable_feature_flag: bool = False,
+ can_write_feature_flag: bool = True,
+ request: Any | None = None,
+ ) -> Experiment:
+ """Archive an ended experiment: validate it has ended, set archived=True.
+
+ When the linked flag is still enabled, it is only disabled and archived if
+ ``disable_feature_flag`` is set — an enabled flag may still be serving traffic
+ (e.g. rolling out the winning variant), so archiving it is an explicit choice.
+ An already-disabled flag is archived regardless.
+
+ ``can_write_feature_flag`` reflects whether the caller's token carries
+ ``feature_flag:write`` — touching the linked flag is skipped when it doesn't.
+ """
if experiment.archived:
raise ValidationError("Experiment is already archived.")
if not experiment.is_stopped:
@@ -1336,10 +1359,93 @@ class ExperimentService:
experiment.archived = True
experiment.save()
+ self._archive_linked_feature_flag(
+ experiment, disable_if_active=disable_feature_flag, can_write_feature_flag=can_write_feature_flag
+ )
+
self._report_experiment_archived(experiment, request=request)
return experiment
+ def _user_can_edit_flag(self, feature_flag: FeatureFlag) -> bool:
+ """Whether self.user has editor access to this flag — the same check the feature flag API enforces."""
+ user = self.user
+ if not isinstance(user, User) or user.is_anonymous:
+ return False
+ return UserAccessControl(user=user, team=self.team).check_access_level_for_object(feature_flag, "editor")
+
+ def _flag_disable_requires_approval(self) -> bool:
+ """Whether an enabled approval policy gates disabling a flag for this team/org."""
+ policy = PolicyEngine().get_policy(
+ action_key="feature_flag.disable", team=self.team, organization=self.team.organization
+ )
+ return policy is not None
+
+ def _archive_linked_feature_flag(
+ self, experiment: Experiment, *, disable_if_active: bool = False, can_write_feature_flag: bool = True
+ ) -> None:
+ """Archive the experiment's flag along with it, so it stops cluttering the flag list.
+
+ An already-disabled flag is archived. An enabled flag is left untouched unless
+ ``disable_if_active`` is set, in which case it is disabled and archived together —
+ an enabled flag may still be serving traffic (e.g. rolling out the winning variant).
+ Never touches a flag still used by another live experiment.
+
+ Mutating the linked flag is gated by the same authorization the flag API enforces:
+ the caller's token must carry ``feature_flag:write`` (``can_write_feature_flag``)
+ and the user must have editor access to the flag, and disabling an active flag is
+ refused when an approval policy would gate it (a side-effect mutation can't be
+ routed through the change-request flow). The implicit archive-only cleanup is
+ skipped silently when the caller lacks access — the experiment still archives.
+ """
+ # Lock the row so a concurrent enable can't slip in between the check and the save,
+ # which would produce an archived flag that is still active.
+ feature_flag = (
+ FeatureFlag.objects.select_for_update()
+ .filter(pk=experiment.feature_flag_id, team_id=experiment.team_id)
+ .first()
+ )
+ if feature_flag is None or feature_flag.deleted or feature_flag.archived:
+ return
+ if feature_flag.experiment_set.filter(deleted=False, archived=False).exclude(id=experiment.id).exists():
+ return
+
+ can_edit = self._user_can_edit_flag(feature_flag)
+
+ if feature_flag.active:
+ if not disable_if_active:
+ return
+ # Explicit, user-requested flag change: enforce the same gates the flag API does.
+ if not can_write_feature_flag:
+ raise PermissionDenied(
+ "You don't have feature flag write access, so this experiment's feature flag can't be disabled."
+ )
+ if not can_edit:
+ raise PermissionDenied(
+ "You don't have editor access to this experiment's feature flag, so it can't be disabled. "
+ "Archive the experiment without disabling the flag, or ask someone with flag access."
+ )
+ if self._flag_disable_requires_approval():
+ raise PermissionDenied(
+ "Disabling this feature flag requires approval. Disable it from the feature flag page "
+ "to go through the approval flow, then archive the experiment."
+ )
+ # Mirror the feature flag API's check: don't disable a flag other active flags depend on.
+ raise_if_flag_has_dependents(feature_flag)
+ feature_flag.active = False
+ elif not can_edit or not can_write_feature_flag:
+ # Implicit cleanup of an already-disabled flag — skip silently when the caller
+ # lacks flag editor access or feature_flag:write scope; the experiment still archives.
+ return
+
+ feature_flag.archived = True
+ feature_flag.save(update_fields=["archived", "active"])
+
+ # Remember that this experiment archived the flag, so unarchiving the experiment
+ # only undoes its own archive — never one the user performed manually.
+ experiment.feature_flag_auto_archived = True
+ experiment.save(update_fields=["feature_flag_auto_archived"])
+
def _report_experiment_archived(
self,
experiment: Experiment,
@@ -1361,18 +1467,59 @@ class ExperimentService:
# Unarchive
# ------------------------------------------------------------------
- def unarchive_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
- """Unarchive an archived experiment: validate it is archived, set archived=False."""
+ @transaction.atomic
+ def unarchive_experiment(
+ self, experiment: Experiment, *, can_write_feature_flag: bool = True, request: Any | None = None
+ ) -> Experiment:
+ """Unarchive an archived experiment: validate it is archived, set archived=False.
+
+ ``can_write_feature_flag`` reflects whether the caller's token carries
+ ``feature_flag:write`` — un-archiving the linked flag is skipped when it doesn't.
+ """
if not experiment.archived:
raise ValidationError("Experiment is not archived.")
experiment.archived = False
experiment.save()
+ self._unarchive_linked_feature_flag(experiment, can_write_feature_flag=can_write_feature_flag)
+
self._report_experiment_unarchived(experiment, request=request)
return experiment
+ def _unarchive_linked_feature_flag(self, experiment: Experiment, *, can_write_feature_flag: bool = True) -> None:
+ """Mirror of _archive_linked_feature_flag: bring the flag back with the experiment.
+
+ Only undoes an archive this experiment performed — a flag the user archived
+ manually stays archived. The flag stays disabled either way; re-enabling it is
+ an explicit user decision. Un-archiving the flag is a feature_flag write, so it's
+ skipped (leaving the flag archived and the bookkeeping intact, recoverable later)
+ when the caller lacks feature_flag:write scope or editor access to the flag.
+ """
+ if not experiment.feature_flag_auto_archived:
+ return
+
+ feature_flag = (
+ FeatureFlag.objects.select_for_update()
+ .filter(pk=experiment.feature_flag_id, team_id=experiment.team_id)
+ .first()
+ )
+ if feature_flag is None or feature_flag.deleted or not feature_flag.archived:
+ # Flag is gone or already un-archived — clear the now-stale bookkeeping.
+ experiment.feature_flag_auto_archived = False
+ experiment.save(update_fields=["feature_flag_auto_archived"])
+ return
+
+ if not can_write_feature_flag or not self._user_can_edit_flag(feature_flag):
+ return
+
+ feature_flag.archived = False
+ feature_flag.save(update_fields=["archived"])
+
+ experiment.feature_flag_auto_archived = False
+ experiment.save(update_fields=["feature_flag_auto_archived"])
+
def _report_experiment_unarchived(
self,
experiment: Experiment,
diff --git a/products/experiments/backend/migrations/0022_experiment_feature_flag_auto_archived.py b/products/experiments/backend/migrations/0022_experiment_feature_flag_auto_archived.py
new file mode 100644
index 000000000000..b8830f9452ac
--- /dev/null
+++ b/products/experiments/backend/migrations/0022_experiment_feature_flag_auto_archived.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("experiments", "0021_alter_experimentmetricsrecalculation_trigger"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="experiment",
+ name="feature_flag_auto_archived",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txt
index ad0827618d38..e733f13a713a 100644
--- a/products/experiments/backend/migrations/max_migration.txt
+++ b/products/experiments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0021_alter_experimentmetricsrecalculation_trigger
+0022_experiment_feature_flag_auto_archived
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 2a744a3ce37f..4cd016842585 100644
--- a/products/experiments/backend/models/experiment.py
+++ b/products/experiments/backend/models/experiment.py
@@ -53,6 +53,9 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
archived = models.BooleanField(default=False)
+ # Whether archiving this experiment also auto-archived its linked feature flag,
+ # so unarchiving only undoes an archive the experiment itself performed.
+ feature_flag_auto_archived = models.BooleanField(default=False, db_default=False)
deleted = models.BooleanField(default=False, null=True)
type = models.CharField(max_length=40, choices=ExperimentType, null=True, blank=True, default="product")
variants = models.JSONField(default=dict, null=True, blank=True)
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index b054e83a6cb4..d12fdfe3c462 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -626,6 +626,16 @@ class EndExperimentSerializer(serializers.Serializer):
)
+class ArchiveExperimentSerializer(serializers.Serializer):
+ disable_feature_flag = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "When the linked feature flag is still enabled, also disable and archive it along with "
+ "the experiment. Has no effect if the flag is already disabled (it is archived either way)."
+ ),
+ )
+
+
class ShipVariantSerializer(EndExperimentSerializer):
variant_key = serializers.CharField(help_text="The key of the variant to ship.")
release_to_everyone = serializers.BooleanField(
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 4ebf6e40f0ff..254c4bdb1884 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -19,7 +19,7 @@ from django.utils.text import slugify
import posthoganalytics
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from opentelemetry import trace
-from rest_framework import viewsets
+from rest_framework import serializers, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -30,6 +30,7 @@ from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.approvals.mixins import ApprovalHandlingMixin
+from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.models.filters.filter import Filter
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
@@ -52,6 +53,7 @@ from products.experiments.backend.models.experiment import (
experiment_has_legacy_metrics,
)
from products.experiments.backend.presentation.serializers import (
+ ArchiveExperimentSerializer,
CopyExperimentToProjectSerializer,
CreateFromPromptInputSerializer,
EndExperimentSerializer,
@@ -107,6 +109,11 @@ LIST_DEFERRED_FIELDS = (
"secondary_metrics_ordered_uuids",
)
+# The viewset's `list` method shadows the builtin `list` in the class namespace, so a
+# `list[str]` annotation there resolves to that method (a runtime crash, and a mypy error).
+# Reference this module-level alias instead.
+RequiredScopes = list[str]
+
def flag_evaluation_contexts_prefetch() -> Prefetch:
return Prefetch(
@@ -360,6 +367,37 @@ class EnterpriseExperimentsViewSet(
request_data=getattr(request, "data", None),
)
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> RequiredScopes | None:
+ # Archiving with disable_feature_flag=true also disables and archives the linked flag,
+ # which is a feature_flag write — require feature_flag:write on the token, not just
+ # experiment:write. Other actions fall back to their own scopes.
+ if self.action == "archive":
+ scopes = ["experiment:write"]
+ # Use DRF's own truthy set so this matches how ArchiveExperimentSerializer parses the field.
+ if request.data.get("disable_feature_flag", False) in serializers.BooleanField.TRUE_VALUES:
+ scopes.append("feature_flag:write")
+ return scopes
+ return None
+
+ def _token_can_write_feature_flag(self, request: Request) -> bool:
+ """Whether the request's token carries feature_flag:write.
+
+ Archiving/unarchiving an experiment can touch the linked flag's archived/active
+ state as a side effect; that is a feature_flag write and must not be reachable with
+ only experiment:write. Session and other non-token auth aren't scope-limited (gated by
+ access control instead), mirroring APIScopePermission.
+ """
+ authenticator = request.successful_authenticator
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ scopes = authenticator.personal_api_key.scopes or []
+ elif isinstance(authenticator, OAuthAccessTokenAuthentication):
+ scopes = (authenticator.access_token.scope or "").split()
+ elif isinstance(authenticator, IDJagAccessTokenAuthentication):
+ scopes = list(authenticator.scopes or [])
+ else:
+ return True
+ return "*" in scopes or "feature_flag:write" in scopes
+
# ******************************************
# /projects/:id/experiments/requires_flag_implementation
#
@@ -395,21 +433,32 @@ class EnterpriseExperimentsViewSet(
return Response(ExperimentSerializer(launched_experiment, context=self.get_serializer_context()).data)
@extend_schema(
- request=None,
+ request=ArchiveExperimentSerializer,
responses=ExperimentSerializer,
)
- @action(methods=["POST"], detail=True, required_scopes=["experiment:write"])
+ # required_scopes is computed by dangerously_get_required_scopes — disabling the linked
+ # flag additionally requires feature_flag:write.
+ @action(methods=["POST"], detail=True)
def archive(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""
Archive an ended experiment.
Hides the experiment from the default list view. The experiment can be
- restored at any time by updating archived=false. Returns 400 if the
- experiment is already archived or has not ended yet.
+ restored at any time by updating archived=false. When the linked feature
+ flag is still enabled, pass disable_feature_flag=true to also disable and
+ archive it. Returns 400 if the experiment is already archived or has not
+ ended yet.
"""
experiment: Experiment = self.get_object()
+ request_serializer = ArchiveExperimentSerializer(data=request.data)
+ request_serializer.is_valid(raise_exception=True)
service = ExperimentService(team=self.team, user=request.user)
- archived_experiment = service.archive_experiment(experiment, request=request)
+ archived_experiment = service.archive_experiment(
+ experiment,
+ disable_feature_flag=request_serializer.validated_data["disable_feature_flag"],
+ can_write_feature_flag=self._token_can_write_feature_flag(request),
+ request=request,
+ )
return Response(ExperimentSerializer(archived_experiment, context=self.get_serializer_context()).data)
@extend_schema(
@@ -426,7 +475,11 @@ class EnterpriseExperimentsViewSet(
"""
experiment: Experiment = self.get_object()
service = ExperimentService(team=self.team, user=request.user)
- unarchived_experiment = service.unarchive_experiment(experiment, request=request)
+ unarchived_experiment = service.unarchive_experiment(
+ experiment,
+ can_write_feature_flag=self._token_can_write_feature_flag(request),
+ request=request,
+ )
return Response(ExperimentSerializer(unarchived_experiment, context=self.get_serializer_context()).data)
@extend_schema(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 2e239855f1cc..306f7fb0f3c9 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -13,12 +13,12 @@ from django.utils import timezone
import pydantic
from parameterized import parameterized
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.test import APIRequestFactory
from posthog.schema import EventsNode, ExperimentMetric
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.models.team.extensions import get_or_create_team_extension
from products.actions.backend.models.action import Action
@@ -2152,6 +2152,258 @@ class TestExperimentService(APIBaseTest):
assert archived.archived is True
assert archived.status == Experiment.Status.STOPPED
+ def test_archive_experiment_archives_disabled_flag(self):
+ experiment = self._create_ended_experiment(name="Archive Flag", feature_flag_key="archive-linked-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+
+ self._service().archive_experiment(experiment)
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is True
+
+ def test_archive_experiment_keeps_enabled_flag_unarchived(self):
+ # An enabled flag may still be serving traffic (e.g. rolling out the winning
+ # variant), so archiving the experiment must not archive it.
+ experiment = self._create_ended_experiment(name="Archive Active Flag", feature_flag_key="still-active-flag")
+ assert experiment.feature_flag.active is True
+
+ self._service().archive_experiment(experiment)
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is False
+
+ def test_archive_experiment_disables_and_archives_enabled_flag_when_opted_in(self):
+ experiment = self._create_ended_experiment(name="Disable On Archive", feature_flag_key="disable-on-archive")
+ assert experiment.feature_flag.active is True
+
+ self._service().archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.refresh_from_db()
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is False
+ assert flag.archived is True
+ assert experiment.feature_flag_auto_archived is True
+
+ def test_archive_experiment_denies_disabling_flag_without_editor_access(self):
+ # A user who can archive the experiment but lacks editor access to the flag must not
+ # be able to disable it via disable_feature_flag — and the experiment archive rolls back.
+ experiment = self._create_ended_experiment(name="No Flag Access", feature_flag_key="no-flag-access")
+ service = self._service()
+
+ with patch.object(service, "_user_can_edit_flag", return_value=False):
+ with self.assertRaises(PermissionDenied):
+ service.archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is True
+ assert flag.archived is False
+
+ def test_archive_experiment_denies_disabling_flag_for_user_without_real_access(self):
+ # Exercises the real _user_can_edit_flag check (no patching): a user with no access to
+ # the flag is refused, so an inverted/broken access check would fail this test.
+ experiment = self._create_ended_experiment(name="Real No Access", feature_flag_key="real-no-access-flag")
+ outsider = User.objects.create_user("[email protected]", None, "Outsider")
+ service = ExperimentService(team=self.team, user=outsider)
+
+ with self.assertRaises(PermissionDenied):
+ service.archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is True
+ assert flag.archived is False
+
+ def test_archive_experiment_denies_disabling_active_flag_without_feature_flag_write_scope(self):
+ # An experiment-only token must not be able to disable an active flag via disable_feature_flag.
+ experiment = self._create_ended_experiment(
+ name="No FF Scope Active", feature_flag_key="no-ff-scope-active-flag"
+ )
+
+ with self.assertRaises(PermissionDenied):
+ self._service().archive_experiment(experiment, disable_feature_flag=True, can_write_feature_flag=False)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is True
+ assert flag.archived is False
+
+ def test_archive_experiment_skips_flag_cleanup_without_feature_flag_write_scope(self):
+ # A token scoped only to experiments must not archive the linked flag as a side effect.
+ experiment = self._create_ended_experiment(name="No FF Scope", feature_flag_key="no-ff-scope-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+
+ self._service().archive_experiment(experiment, can_write_feature_flag=False)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is True
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.archived is False
+ assert experiment.feature_flag_auto_archived is False
+
+ def test_unarchive_experiment_skips_flag_without_feature_flag_write_scope(self):
+ # Unarchiving the flag is a feature_flag write — skipped (flag stays archived, bookkeeping
+ # intact) for an experiment-only token, recoverable on a later unarchive with the scope.
+ experiment = self._create_ended_experiment(name="Unarchive No Scope", feature_flag_key="unarchive-no-scope")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+ service = self._service()
+ service.archive_experiment(experiment)
+ experiment.refresh_from_db()
+ assert experiment.feature_flag_auto_archived is True
+
+ service.unarchive_experiment(experiment, can_write_feature_flag=False)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.archived is True
+ assert experiment.feature_flag_auto_archived is True
+
+ def test_archive_experiment_denies_disabling_flag_when_approval_required(self):
+ experiment = self._create_ended_experiment(name="Approval Gated", feature_flag_key="approval-gated-flag")
+ service = self._service()
+
+ with (
+ patch.object(service, "_user_can_edit_flag", return_value=True),
+ patch.object(service, "_flag_disable_requires_approval", return_value=True),
+ ):
+ with self.assertRaises(PermissionDenied):
+ service.archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is True
+ assert flag.archived is False
+
+ def test_archive_experiment_denies_disabling_flag_with_dependents(self):
+ # Mirror the feature flag API: disabling a flag other active flags depend on is rejected.
+ experiment = self._create_ended_experiment(name="Has Dependents", feature_flag_key="depended-on-flag")
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="dependent-flag",
+ active=True,
+ filters={
+ "groups": [{"properties": [{"type": "flag", "key": str(experiment.feature_flag_id), "value": "true"}]}]
+ },
+ )
+
+ with self.assertRaises(ValidationError):
+ self._service().archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is False
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.active is True
+ assert flag.archived is False
+
+ def test_archive_experiment_skips_flag_cleanup_without_editor_access(self):
+ # The implicit archive-only cleanup of an already-disabled flag is skipped (not an error)
+ # when the caller can't edit the flag — the experiment still archives.
+ experiment = self._create_ended_experiment(name="Skip Cleanup", feature_flag_key="skip-cleanup-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+ service = self._service()
+
+ with patch.object(service, "_user_can_edit_flag", return_value=False):
+ service.archive_experiment(experiment)
+
+ experiment.refresh_from_db()
+ assert experiment.archived is True
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.archived is False
+ assert experiment.feature_flag_auto_archived is False
+
+ def test_archive_experiment_keeps_flag_shared_with_live_experiment(self):
+ experiment = self._create_ended_experiment(name="Shared Flag", feature_flag_key="shared-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+ Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Other experiment on same flag",
+ feature_flag=experiment.feature_flag,
+ )
+
+ self._service().archive_experiment(experiment)
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is False
+
+ def test_archive_experiment_keeps_shared_flag_even_when_opted_in(self):
+ # Opting in to disable the flag must still never touch a flag a live experiment relies on.
+ experiment = self._create_ended_experiment(name="Shared Opt In", feature_flag_key="shared-opt-in-flag")
+ Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Other experiment on same flag",
+ feature_flag=experiment.feature_flag,
+ )
+
+ self._service().archive_experiment(experiment, disable_feature_flag=True)
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is True
+ assert experiment.feature_flag.archived is False
+
+ def test_unarchive_experiment_keeps_opted_in_flag_disabled(self):
+ # When archiving disabled an enabled flag, unarchiving un-archives it but leaves it
+ # disabled — re-enabling stays an explicit user decision.
+ experiment = self._create_ended_experiment(name="Unarchive Opt In", feature_flag_key="unarchive-opt-in-flag")
+ service = self._service()
+ service.archive_experiment(experiment, disable_feature_flag=True)
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is True
+
+ service.unarchive_experiment(experiment)
+
+ experiment.refresh_from_db()
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.archived is False
+ assert flag.active is False
+ assert experiment.feature_flag_auto_archived is False
+
+ def test_unarchive_experiment_unarchives_flag(self):
+ experiment = self._create_ended_experiment(name="Unarchive Flag", feature_flag_key="unarchive-linked-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+ service = self._service()
+ service.archive_experiment(experiment)
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is True
+ assert experiment.feature_flag_auto_archived is True
+
+ service.unarchive_experiment(experiment)
+
+ refreshed = Experiment.objects.get(pk=experiment.id)
+ flag = FeatureFlag.objects.get(pk=experiment.feature_flag_id)
+ assert flag.archived is False
+ assert refreshed.feature_flag_auto_archived is False
+ # The flag stays disabled — re-enabling is an explicit user decision
+ assert flag.active is False
+
+ def test_unarchive_experiment_keeps_manually_archived_flag(self):
+ # The user archived the flag themselves, so unarchiving the experiment must not undo it.
+ experiment = self._create_ended_experiment(name="Manual Archive", feature_flag_key="manually-archived-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.archived = True
+ experiment.feature_flag.save()
+ service = self._service()
+ service.archive_experiment(experiment)
+ assert experiment.feature_flag_auto_archived is False
+
+ service.unarchive_experiment(experiment)
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is True
+
def test_archive_experiment_already_archived_raises(self):
experiment = self._create_ended_experiment(name="Already Archived", feature_flag_key="already-archived-flag")
service = self._service()
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 806d547e4e12..e6ac698ca3fb 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -1,4 +1,5 @@
from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
from typing import Any, cast
import unittest
@@ -14,10 +15,13 @@ from dateutil import parser
from parameterized import parameterized
from rest_framework import status
+from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.models import Organization, Team
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.test_journeys import journeys_for
from products.actions.backend.models.action import Action
@@ -31,7 +35,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.models.web_experiment import WebExperiment
-from products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS
+from products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS, EnterpriseExperimentsViewSet
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cache
@@ -39,6 +43,14 @@ from ee.api.test.base import APILicensedTest
from ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer
+def _make(cls, **attrs):
+ """Build an auth instance without running __init__, setting only the attributes the test needs."""
+ instance = cls.__new__(cls)
+ for key, value in attrs.items():
+ setattr(instance, key, value)
+ return instance
+
+
class TestExperimentCRUD(APILicensedTest):
# List experiments
def test_can_list_experiments(self):
@@ -4461,6 +4473,161 @@ class TestExperimentCRUD(APILicensedTest):
self.assertEqual(archive_response.status_code, status.HTTP_200_OK)
self.assertTrue(archive_response.json()["archived"])
+ def test_archive_experiment_endpoint_disables_feature_flag(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "allow_unknown_events": True,
+ "name": "Archive And Disable Flag",
+ "feature_flag_key": "archive-disable-flag",
+ "start_date": "2024-01-01T10:00",
+ "end_date": "2024-01-15T10:00",
+ "metrics": [
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ }
+ ],
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ experiment_id = response.json()["id"]
+ feature_flag_id = response.json()["feature_flag"]["id"]
+
+ archive_response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/archive/",
+ {"disable_feature_flag": True},
+ format="json",
+ )
+ self.assertEqual(archive_response.status_code, status.HTTP_200_OK)
+
+ feature_flag = FeatureFlag.objects.get(id=feature_flag_id)
+ self.assertFalse(feature_flag.active)
+ self.assertTrue(feature_flag.archived)
+
+ def test_archive_endpoint_disable_requires_feature_flag_write_scope(self):
+ def _make_experiment(name: str, key: str) -> tuple[int, int]:
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "allow_unknown_events": True,
+ "name": name,
+ "feature_flag_key": key,
+ "start_date": "2024-01-01T10:00",
+ "end_date": "2024-01-15T10:00",
+ "metrics": [
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ }
+ ],
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
+ return resp.json()["id"], resp.json()["feature_flag"]["id"]
+
+ def _pat(scopes: list[str]) -> str:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(user=self.user, label="t", secure_value=hash_key_value(token), scopes=scopes)
+ return token
+
+ exp_deny, _ = _make_experiment("Scope Deny", "scope-deny-flag")
+ exp_no_disable, _ = _make_experiment("Scope No Disable", "scope-no-disable-flag")
+ exp_allow, flag_allow = _make_experiment("Scope Allow", "scope-allow-flag")
+
+ self.client.logout()
+
+ # experiment:write alone can't disable the linked flag — that needs feature_flag:write.
+ token = _pat(["experiment:write"])
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_deny}/archive/",
+ {"disable_feature_flag": True},
+ format="json",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+
+ # experiment:write alone still archives when not disabling the flag.
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_no_disable}/archive/",
+ {"disable_feature_flag": False},
+ format="json",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
+ # With feature_flag:write, disabling the linked flag is allowed.
+ token = _pat(["experiment:write", "feature_flag:write"])
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_allow}/archive/",
+ {"disable_feature_flag": True},
+ format="json",
+ headers={"authorization": f"Bearer {token}"},
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ flag = FeatureFlag.objects.get(id=flag_allow)
+ self.assertFalse(flag.active)
+ self.assertTrue(flag.archived)
+
+ @parameterized.expand(
+ [
+ # Personal API key: scopes come off the key.
+ (
+ "pak_denied",
+ _make(PersonalAPIKeyAuthentication, personal_api_key=SimpleNamespace(scopes=["experiment:write"])),
+ False,
+ ),
+ (
+ "pak_allowed",
+ _make(
+ PersonalAPIKeyAuthentication,
+ personal_api_key=SimpleNamespace(scopes=["experiment:write", "feature_flag:write"]),
+ ),
+ True,
+ ),
+ ("pak_wildcard", _make(PersonalAPIKeyAuthentication, personal_api_key=SimpleNamespace(scopes=["*"])), True),
+ # OAuth: scope is a space-separated string that must be split.
+ (
+ "oauth_denied",
+ _make(OAuthAccessTokenAuthentication, access_token=SimpleNamespace(scope="experiment:write")),
+ False,
+ ),
+ (
+ "oauth_allowed",
+ _make(
+ OAuthAccessTokenAuthentication,
+ access_token=SimpleNamespace(scope="experiment:write feature_flag:write"),
+ ),
+ True,
+ ),
+ ("oauth_wildcard", _make(OAuthAccessTokenAuthentication, access_token=SimpleNamespace(scope="*")), True),
+ (
+ "oauth_empty_scope",
+ _make(OAuthAccessTokenAuthentication, access_token=SimpleNamespace(scope=None)),
+ False,
+ ),
+ # ID-JAG: scopes are already a list.
+ ("id_jag_denied", _make(IDJagAccessTokenAuthentication, scopes=["experiment:write"]), False),
+ (
+ "id_jag_allowed",
+ _make(IDJagAccessTokenAuthentication, scopes=["experiment:write", "feature_flag:write"]),
+ True,
+ ),
+ ("id_jag_wildcard", _make(IDJagAccessTokenAuthentication, scopes=["*"]), True),
+ # Session and other non-token auth aren't scope-limited.
+ ("session_auth", None, True),
+ ("other_auth", object(), True),
+ ]
+ )
+ def test_token_can_write_feature_flag_per_token_type(self, _name, authenticator, expected):
+ request = cast(Any, SimpleNamespace(successful_authenticator=authenticator))
+ viewset = EnterpriseExperimentsViewSet()
+ self.assertEqual(viewset._token_can_write_feature_flag(request), expected)
+
def test_archive_experiment_endpoint_not_ended(self):
response = self.client.post(
f"/api/projects/{self.team.id}/experiments/",
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 673c6f9c47a7..b9000d763a41 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -827,6 +827,11 @@ export interface PatchedExperimentApi {
readonly user_access_level?: string | null
}
+export interface ArchiveExperimentApi {
+ /** When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way). */
+ disable_feature_flag?: boolean
+}
+
export interface CopyExperimentToProjectApi {
/** The team ID to copy the experiment to. */
target_team_id: number
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index dcc6beb9e82b..9dba1977298e 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ ArchiveExperimentApi,
CopyExperimentToProjectApi,
CreateFromPromptInputApi,
EndExperimentApi,
@@ -406,17 +407,22 @@ export const getExperimentsArchiveCreateUrl = (projectId: string, id: number) =>
* Archive an ended experiment.
*
* Hides the experiment from the default list view. The experiment can be
- * restored at any time by updating archived=false. Returns 400 if the
- * experiment is already archived or has not ended yet.
+ * restored at any time by updating archived=false. When the linked feature
+ * flag is still enabled, pass disable_feature_flag=true to also disable and
+ * archive it. Returns 400 if the experiment is already archived or has not
+ * ended yet.
*/
export const experimentsArchiveCreate = async (
projectId: string,
id: number,
+ archiveExperimentApi?: ArchiveExperimentApi,
options?: RequestInit
): Promise<ExperimentApi> => {
return apiMutator<ExperimentApi>(getExperimentsArchiveCreateUrl(projectId, id), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(archiveExperimentApi),
})
}
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index b0d5a320468c..09922c78362e 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -138,6 +138,26 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+/**
+ * Archive an ended experiment.
+ *
+ * Hides the experiment from the default list view. The experiment can be
+ * restored at any time by updating archived=false. When the linked feature
+ * flag is still enabled, pass disable_feature_flag=true to also disable and
+ * archive it. Returns 400 if the experiment is already archived or has not
+ * ended yet.
+ */
+export const experimentsArchiveCreateBodyDisableFeatureFlagDefault = false
+
+export const ExperimentsArchiveCreateBody = /* @__PURE__ */ zod.object({
+ disable_feature_flag: zod
+ .boolean()
+ .default(experimentsArchiveCreateBodyDisableFeatureFlagDefault)
+ .describe(
+ 'When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way).'
+ ),
+})
+
/**
* Copy an experiment into another project in the same organization as a new draft.
*/
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index c2f02c15d1f8..3f733aa2c6a2 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -78,7 +78,11 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
get_decrypted_flag_payloads_protected,
)
from products.feature_flags.backend.flag_analytics import increment_request_count
-from products.feature_flags.backend.flag_status import FeatureFlagStatusChecker, filter_flags_by_active_param
+from products.feature_flags.backend.flag_status import (
+ FeatureFlagStatusChecker,
+ exclude_archived_unless_requested,
+ filter_flags_by_active_param,
+)
from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filters
from products.feature_flags.backend.models.evaluation_context import normalize_context_name
from products.feature_flags.backend.models.feature_flag import (
@@ -372,6 +376,24 @@ def find_dependent_flags(flag_to_check: FeatureFlag) -> list[FeatureFlag]:
)
+def raise_if_flag_has_dependents(flag: FeatureFlag, action: str = "disable") -> None:
+ """Raise ValidationError if any active flags depend on *flag*.
+
+ Centralises the format-and-raise logic so every caller (flag serializer,
+ experiment service, bulk-delete) stays in sync automatically.
+ """
+ dependent_flags = find_dependent_flags(flag)
+ if not dependent_flags:
+ return
+ names = ", ".join(f"{f.key} (ID: {f.id})" for f in dependent_flags[:5])
+ if len(dependent_flags) > 5:
+ names += f", and {len(dependent_flags) - 5} more"
+ raise exceptions.ValidationError(
+ f"Cannot {action} this feature flag because other flags depend on it: {names}. "
+ "Please update or disable the dependent flags first."
+ )
+
+
def find_dependent_flags_batch(
flags_to_check: list[FeatureFlag],
) -> dict[int, list[FeatureFlag]]:
@@ -716,6 +738,10 @@ class FeatureFlagCreateRequestSchemaSerializer(serializers.Serializer):
)
filters = FeatureFlagFiltersSchemaSerializer(required=False, help_text="Feature flag targeting configuration.")
active = serializers.BooleanField(required=False, help_text="Whether the feature flag is active.")
+ archived = serializers.BooleanField(
+ required=False,
+ help_text="Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).",
+ )
tags = serializers.ListField(
child=serializers.CharField(),
required=False,
@@ -762,6 +788,10 @@ class FeatureFlagPartialUpdateRequestSchemaSerializer(serializers.Serializer):
)
filters = FeatureFlagFiltersSchemaSerializer(required=False, help_text="Feature flag targeting configuration.")
active = serializers.BooleanField(required=False, help_text="Whether the feature flag is active.")
+ archived = serializers.BooleanField(
+ required=False,
+ help_text="Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).",
+ )
tags = serializers.ListField(
child=serializers.CharField(),
required=False,
@@ -825,6 +855,11 @@ class FeatureFlagSerializer(
ensure_experience_continuity = ClassicBehaviorBooleanFieldSerializer()
has_enriched_analytics = ClassicBehaviorBooleanFieldSerializer()
+ archived = serializers.BooleanField(
+ required=False,
+ help_text="Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).",
+ )
+
experiment_set = serializers.SerializerMethodField()
experiment_set_metadata = serializers.SerializerMethodField()
surveys: serializers.SerializerMethodField = serializers.SerializerMethodField()
@@ -863,6 +898,7 @@ class FeatureFlagSerializer(
"filters",
"deleted",
"active",
+ "archived",
"created_by",
"created_at",
"updated_at",
@@ -940,6 +976,7 @@ class FeatureFlagSerializer(
# 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)
+ self._validate_archived_flags_are_disabled(attrs)
self._validate_flag_limits()
request = self.context.get("request")
@@ -1024,6 +1061,24 @@ class FeatureFlagSerializer(
"These features are incompatible."
)
+ def _validate_archived_flags_are_disabled(self, attrs: dict) -> None:
+ """An archived flag must be disabled — archived means "done for good", not paused."""
+ # Resolve effective values: use incoming attrs, falling back to instance for updates
+ archived = attrs.get("archived", getattr(self.instance, "archived", False) if self.instance else False)
+ # On create, fall back to the model default (active=True)
+ active = attrs.get("active", getattr(self.instance, "active", True) if self.instance else True)
+
+ if not (archived and active):
+ return
+
+ # If this request set archived=True, the user is archiving an enabled flag;
+ # otherwise they're enabling an already-archived flag.
+ if attrs.get("archived"):
+ raise serializers.ValidationError(
+ "Cannot archive an enabled feature flag. Disable it first, or send active: false in the same request."
+ )
+ raise serializers.ValidationError("Cannot enable an archived feature flag. Unarchive it first.")
+
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 updates
@@ -1674,21 +1729,13 @@ class FeatureFlagSerializer(
# only a currently running experiment blocks deletion.
running_experiments = [exp for exp in instance.experiment_set.filter(deleted=False) if exp.is_running]
if running_experiments:
- experiment_ids = [exp.id for exp in running_experiments]
+ experiment_names = ", ".join(f'"{exp.name}" (ID: {exp.id})' for exp in running_experiments)
raise exceptions.ValidationError(
- f"Cannot delete a feature flag that is linked to running experiment(s) with ID(s): {', '.join(map(str, experiment_ids))}. Please stop the experiment(s) before deleting the flag."
+ f"Cannot delete a feature flag that is linked to running experiment(s): {experiment_names}. Please stop the experiment(s) before deleting the flag."
)
# Check for other flags that depend on this flag
- dependent_flags = self._find_dependent_flags(instance)
- if dependent_flags:
- dependent_flag_names = [f"{flag.key} (ID: {flag.id})" for flag in dependent_flags[:5]]
- if len(dependent_flags) > 5:
- dependent_flag_names.append(f"and {len(dependent_flags) - 5} more")
- raise exceptions.ValidationError(
- f"Cannot delete this feature flag because other flags depend on it: {', '.join(dependent_flag_names)}. "
- f"Please update or delete the dependent flags first."
- )
+ raise_if_flag_has_dependents(instance, action="delete")
# Check if flag is used in session replay settings
if Team.objects.filter(
@@ -1726,16 +1773,7 @@ class FeatureFlagSerializer(
# Check for dependency conflicts when disabling a flag
if "active" in validated_data and validated_data["active"] is False and instance.active is True:
- # Check for other flags that depend on this flag
- dependent_flags = self._find_dependent_flags(instance)
- if dependent_flags:
- dependent_flag_names = [f"{flag.key} (ID: {flag.id})" for flag in dependent_flags[:5]]
- if len(dependent_flags) > 5:
- dependent_flag_names.append(f"and {len(dependent_flags) - 5} more")
- raise exceptions.ValidationError(
- f"Cannot disable this feature flag because other flags depend on it: {', '.join(dependent_flag_names)}. "
- f"Please update or disable the dependent flags first."
- )
+ raise_if_flag_has_dependents(instance)
# Check for dependency conflicts when enabling a flag
if "active" in validated_data and validated_data["active"] is True and instance.active is False:
@@ -1942,10 +1980,6 @@ class FeatureFlagSerializer(
and validated_data[field] != getattr(current_instance, field)
]
- def _find_dependent_flags(self, flag_to_check: FeatureFlag) -> list[FeatureFlag]:
- """Find all active flags that depend on the given flag."""
- return find_dependent_flags(flag_to_check)
-
def _find_disabled_dependencies(self, flag_to_check: FeatureFlag) -> list[FeatureFlag]:
"""Find all disabled flags that the given flag depends on."""
dependency_ids = []
@@ -2193,7 +2227,7 @@ class FeatureFlagRolloutSummarySerializer(serializers.Serializer):
class FeatureFlagStatusResponseSerializer(serializers.Serializer):
status = serializers.CharField(
help_text=(
- "Flag staleness/evaluation status: active, stale, deleted, or unknown. 'active' means the flag "
+ "Flag staleness/evaluation status: active, stale, archived, deleted, or unknown. 'active' means the flag "
"was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled "
"out. Use the `rollout` object to determine rollout completeness."
)
@@ -2486,10 +2520,19 @@ class BulkDeleteFiltersSerializer(serializers.Serializer):
required=False,
help_text="Tag names to filter by. Flags carrying at least one of these tags match.",
)
+ excluded_tags = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text="Tag names to exclude. Flags carrying any of these tags are filtered out.",
+ )
has_evaluation_contexts = serializers.BooleanField(
required=False,
help_text="When true, only matches flags with at least one evaluation context.",
)
+ archived = serializers.BooleanField(
+ required=False,
+ help_text="Filter by archived state. When omitted, archived flags are excluded.",
+ )
class BulkDeleteRequestSerializer(serializers.Serializer):
@@ -2660,6 +2703,8 @@ class FeatureFlagViewSet(
Q(id__in=product_tour_internal_targeting_flags)
)
+ queryset = exclude_archived_unless_requested(queryset, requested="archived" in self.request.GET)
+
# add additional filters provided by the client
queryset = self._filter_request(self.request, queryset)
@@ -2726,6 +2771,21 @@ class FeatureFlagViewSet(
required=False,
description="JSON-encoded list of tag names to filter feature flags by.",
),
+ OpenApiParameter(
+ "excluded_tags",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="JSON-encoded list of tag names to exclude. Flags carrying any of these tags are filtered out.",
+ ),
+ OpenApiParameter(
+ "archived",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=["true", "false"],
+ description="Filter by archived state. When omitted, archived flags are excluded.",
+ ),
OpenApiParameter(
"has_evaluation_contexts",
OpenApiTypes.STR,
@@ -3062,6 +3122,8 @@ class FeatureFlagViewSet(
).values_list("internal_targeting_flag_id", flat=True)
queryset = queryset.exclude(Q(id__in=survey_flag_ids)).exclude(Q(id__in=product_tour_internal_targeting_flags))
+ queryset = exclude_archived_unless_requested(queryset, requested="archived" in self.request.GET)
+
# Apply client filters (same filtering as list endpoint)
queryset = self._filter_request(self.request, queryset)
@@ -3160,6 +3222,9 @@ class FeatureFlagViewSet(
queryset = queryset.exclude(Q(id__in=survey_flag_ids)).exclude(Q(id__in=product_tour_internal_targeting_flags))
if filters:
+ # Match the list endpoint's semantics: archived flags are not deleted by
+ # filter-based bulk deletion unless explicitly requested.
+ queryset = exclude_archived_unless_requested(queryset, requested="archived" in filters)
# Apply filters from request body (same logic as _filter_request but from dict)
queryset = self._apply_filters(filters, queryset)
else:
@@ -3249,12 +3314,12 @@ class FeatureFlagViewSet(
# currently running experiment blocks deletion.
running_experiments = [exp for exp in flag.experiment_set.all() if not exp.deleted and exp.is_running]
if running_experiments:
- experiment_ids = [exp.id for exp in running_experiments]
+ experiment_names = ", ".join(f'"{exp.name}" (ID: {exp.id})' for exp in running_experiments)
errors.append(
{
"id": flag_id,
"key": flag.key,
- "reason": f"Cannot delete a feature flag linked to running experiment(s): {', '.join(map(str, experiment_ids))}",
+ "reason": f"Cannot delete a feature flag linked to running experiment(s): {experiment_names}",
}
)
continue
@@ -3368,6 +3433,9 @@ class FeatureFlagViewSet(
for key, value in filters.items():
if key == "active":
queryset = filter_flags_by_active_param(queryset, value)
+ elif key == "archived":
+ is_archived = value if isinstance(value, bool) else str(value).lower() == "true"
+ queryset = queryset.filter(archived=is_archived)
elif key == "created_by_id":
user_ids = parse_created_by_ids(value)
if user_ids:
@@ -3421,6 +3489,21 @@ class FeatureFlagViewSet(
queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()
except (json.JSONDecodeError, TypeError):
pass
+ elif key == "excluded_tags":
+ try:
+ # Handle both list and JSON string
+ excluded_tags = (
+ value if isinstance(value, list) else json.loads(value) if isinstance(value, str) else []
+ )
+ if excluded_tags:
+ # Exclude by ID subquery so a flag carrying both an excluded and a
+ # non-excluded tag is still reliably filtered out.
+ flags_with_excluded_tags = FeatureFlag.objects.filter(
+ team__project_id=self.project_id, tagged_items__tag__name__in=excluded_tags
+ ).values("pk")
+ queryset = queryset.exclude(pk__in=flags_with_excluded_tags)
+ except (json.JSONDecodeError, TypeError):
+ pass
elif key == "has_evaluation_contexts":
# Handle both string and boolean
if isinstance(value, bool):
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 236165f06084..a3c3c639b124 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -785,6 +785,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1340,6 +1341,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
@@ -1630,6 +1632,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1753,6 +1756,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index 1fae3ce7baa2..8c534df8d3e1 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -201,6 +201,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -260,6 +261,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -1198,6 +1200,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -3595,6 +3598,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
@@ -3913,6 +3917,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
@@ -3951,6 +3956,7 @@
"posthog_experiment"."created_at",
"posthog_experiment"."updated_at",
"posthog_experiment"."archived",
+ "posthog_experiment"."feature_flag_auto_archived",
"posthog_experiment"."deleted",
"posthog_experiment"."type",
"posthog_experiment"."variants",
@@ -4417,6 +4423,7 @@
"posthog_featureflag"."updated_at",
"posthog_featureflag"."deleted",
"posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
"posthog_featureflag"."version",
"posthog_featureflag"."last_modified_by_id",
"posthog_featureflag"."rollback_conditions",
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 72165e4fc3b2..0fd99ee3e0fe 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -3682,13 +3682,14 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
team=self.team,
created_by=self.user,
feature_flag=flag,
+ name="My experiment",
start_date=now(),
)
response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"deleted": True})
assert response.status_code == 400
assert (
response.json()["detail"]
- == f"Cannot delete a feature flag that is linked to running experiment(s) with ID(s): {exp.id}. Please stop the experiment(s) before deleting the flag."
+ == f'Cannot delete a feature flag that is linked to running experiment(s): "My experiment" (ID: {exp.id}). Please stop the experiment(s) before deleting the flag.'
)
@parameterized.expand(
@@ -3744,6 +3745,96 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert response.status_code == 200
assert response.json()["is_used_in_replay_settings"] is True
+ def test_archive_flag_requires_disabled(self):
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="enabled-flag", active=True)
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"archived": True})
+ assert response.status_code == 400
+ assert "Cannot archive an enabled feature flag" in response.json()["detail"]
+ flag.refresh_from_db()
+ assert flag.archived is False
+
+ def test_archive_disabled_flag(self):
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="disabled-flag", active=False)
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"archived": True})
+ assert response.status_code == 200, response.content
+ assert response.json()["archived"] is True
+ assert response.json()["status"] == "ARCHIVED"
+ flag.refresh_from_db()
+ assert flag.archived is True
+
+ def test_archive_and_disable_flag_in_one_request(self):
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="enabled-flag", active=True)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"archived": True, "active": False}
+ )
+ assert response.status_code == 200, response.content
+ flag.refresh_from_db()
+ assert flag.archived is True
+ assert flag.active is False
+
+ def test_cannot_enable_archived_flag(self):
+ flag = FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="archived-flag", active=False, archived=True
+ )
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"active": True})
+ assert response.status_code == 400
+ assert response.json()["detail"] == "Cannot enable an archived feature flag. Unarchive it first."
+
+ def test_unarchive_flag_stays_disabled(self):
+ flag = FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="archived-flag", active=False, archived=True
+ )
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"archived": False})
+ assert response.status_code == 200, response.content
+ flag.refresh_from_db()
+ assert flag.archived is False
+ assert flag.active is False
+
+ @parameterized.expand(
+ [
+ ("default", "", True, False),
+ ("archived_true", "?archived=true", False, True),
+ ("archived_false", "?archived=false", True, False),
+ ]
+ )
+ def test_list_archived_filtering(self, _name, query, expect_visible, expect_archived):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="visible-flag")
+ FeatureFlag.objects.create(
+ team=self.team, created_by=self.user, key="archived-flag", active=False, archived=True
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{query}")
+ assert response.status_code == 200
+ keys = {flag["key"] for flag in response.json()["results"]}
+ assert ("visible-flag" in keys) is expect_visible
+ assert ("archived-flag" in keys) is expect_archived
+
+ def test_list_excluded_tags_filtering(self):
+ for key, tags in [
+ ("deprecated-flag", ["deprecated"]),
+ ("multi-tag-flag", ["deprecated", "app"]),
+ ("app-flag", ["app"]),
+ ("untagged-flag", []),
+ ]:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "key": key,
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
+ "tags": tags,
+ },
+ format="json",
+ )
+ assert response.status_code == 201, response.content
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/?excluded_tags={json.dumps(['deprecated'])}"
+ )
+ assert response.status_code == 200
+ keys = {flag["key"] for flag in response.json()["results"]}
+ assert "deprecated-flag" not in keys
+ assert "multi-tag-flag" not in keys
+ assert {"app-flag", "untagged-flag"} <= keys
+
def test_getting_flags_is_not_nplus1(self) -> None:
self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
@@ -11011,6 +11102,34 @@ class TestFeatureFlagMatchingIds(APIBaseTest):
assert data["total"] == 1
assert data["ids"] == [active_flag.id]
+ def test_matching_ids_excludes_archived_by_default(self):
+ visible_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="visible_flag",
+ filters={"groups": [{"rollout_percentage": 50, "properties": []}]},
+ )
+ archived_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="archived_flag",
+ archived=True,
+ active=False,
+ filters={"groups": [{"rollout_percentage": 50, "properties": []}]},
+ )
+
+ # Default: archived flag is absent from the "select all matching" set.
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/matching_ids/")
+ assert response.status_code == 200
+ ids = response.json()["ids"]
+ assert visible_flag.id in ids
+ assert archived_flag.id not in ids
+
+ # ?archived=true returns only archived flags.
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/matching_ids/?archived=true")
+ assert response.status_code == 200
+ assert response.json()["ids"] == [archived_flag.id]
+
def test_matching_ids_excludes_deleted_flags(self):
flag = FeatureFlag.objects.create(
team=self.team,
@@ -11169,6 +11288,36 @@ class TestFeatureFlagBulkDelete(APIBaseTest):
assert active_flag.deleted is False
assert inactive_flag.deleted is True
+ def test_bulk_delete_by_filter_excludes_archived_by_default(self):
+ """An archived flag must not be deleted by a filter-based bulk delete, even when it
+ matches the filter (archived flags are inactive, so an active=false filter matches them)."""
+ archived_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="archived_inactive_flag",
+ archived=True,
+ active=False,
+ filters={"groups": [{"rollout_percentage": 50, "properties": []}]},
+ )
+ inactive_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="plain_inactive_flag",
+ active=False,
+ filters={"groups": [{"rollout_percentage": 50, "properties": []}]},
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",
+ {"filters": {"active": "false"}},
+ )
+
+ assert response.status_code == 200
+ archived_flag.refresh_from_db()
+ inactive_flag.refresh_from_db()
+ assert archived_flag.deleted is False
+ assert inactive_flag.deleted is True
+
def test_bulk_delete_by_ids_no_limit(self):
"""Test that ID-based deletion has no 100 limit (unlike the old endpoint)."""
# Create 150 flags
@@ -11217,7 +11366,11 @@ class TestFeatureFlagBulkDelete(APIBaseTest):
data = response.json()
assert len(data["deleted"]) == 0
assert len(data["errors"]) == 1
- assert "experiment" in data["errors"][0]["reason"].lower()
+ # The error names the blocking experiment, matching the single-delete path's formatting.
+ assert (
+ 'Cannot delete a feature flag linked to running experiment(s): "Test Experiment"'
+ in (data["errors"][0]["reason"])
+ )
# Verify flag is NOT deleted
flag.refresh_from_db()
diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
index cdd209073f0f..3d56c9fbadcf 100644
--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
@@ -187,6 +187,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
"active": self.feature_flag_to_copy.active,
"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,
"deleted": False,
+ "archived": False,
"created_by": ANY,
"id": ANY,
"created_at": ANY,
@@ -281,6 +282,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
"active": self.feature_flag_to_copy.active,
"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,
"deleted": False,
+ "archived": False,
"created_by": ANY,
"rollback_conditions": None,
"performed_rollback": False,
@@ -420,6 +422,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
"active": self.feature_flag_to_copy.active,
"ensure_experience_continuity": self.feature_flag_to_copy.ensure_experience_continuity,
"deleted": False,
+ "archived": False,
"created_by": ANY,
"rollback_conditions": None,
"performed_rollback": False,
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index 147a43a5dc1f..7bae90d83978 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -18,6 +18,7 @@ FeatureFlagStatusReason = str
class FeatureFlagStatus(StrEnum):
ACTIVE = "active"
STALE = "stale"
+ ARCHIVED = "archived"
DELETED = "deleted"
UNKNOWN = "unknown"
@@ -34,6 +35,19 @@ class FeatureFlagRolloutSummary:
is_multivariate: bool
+def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) -> QuerySet:
+ """Hide archived flags unless the caller explicitly asked for them.
+
+ This is the API's default for the list, `matching_ids`, and filter-based `bulk_delete`
+ paths — archived flags stay out of "select all" / bulk-delete sets unless `archived` is
+ passed. `requested` is whether the caller provided an `archived` param (the value filter
+ itself is applied separately). The frontend `flagMatchesFilters` keeps its own mirror.
+ """
+ if not requested:
+ return queryset.filter(archived=False)
+ return queryset
+
+
def filter_flags_by_active_param(queryset: QuerySet, value: str | bool) -> QuerySet:
"""
Filter a FeatureFlag queryset by the `active` param (STALE / true / false).
@@ -111,6 +125,7 @@ def filter_flags_by_active_param(queryset: QuerySet, value: str | bool) -> Query
# - STALE: The feature flag is likely safe to remove. Detection uses the best available signal:
# 1. If last_called_at exists: flag hasn't been called in 30+ days (usage-based)
# 2. If last_called_at is NULL: flag is 100% rolled out and 30+ days old (config-based)
+# - ARCHIVED: The feature flag has been archived (done for good, kept for historical data).
# - DELETED: The feature flag has been soft deleted.
# - UNKNOWN: The feature flag is not found in the database.
#
@@ -143,6 +158,9 @@ class FeatureFlagStatusChecker:
if flag.deleted:
return FeatureFlagStatus.DELETED, "Flag has been deleted"
+ if flag.archived:
+ return FeatureFlagStatus.ARCHIVED, "Flag has been archived"
+
# Disabled flags are not evaluated for staleness
if not flag.active:
return FeatureFlagStatus.ACTIVE, "Flag is disabled (not evaluated for staleness)"
diff --git a/products/feature_flags/backend/migrations/0004_featureflag_archived.py b/products/feature_flags/backend/migrations/0004_featureflag_archived.py
new file mode 100644
index 000000000000..16686c583b48
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0004_featureflag_archived.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0003_evaluationcontext_hidden_from_suggestions"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="featureflag",
+ name="archived",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/feature_flags/backend/migrations/0005_featureflag_archived_disabled_constraint.py b/products/feature_flags/backend/migrations/0005_featureflag_archived_disabled_constraint.py
new file mode 100644
index 000000000000..ad90995c4bdd
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0005_featureflag_archived_disabled_constraint.py
@@ -0,0 +1,19 @@
+from django.db import migrations, models
+from django.db.models import Q
+
+from posthog.migration_helpers.not_valid_constraint import AddConstraintNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0004_featureflag_archived"),
+ ]
+
+ operations = [
+ AddConstraintNotValid(
+ model_name="featureflag",
+ constraint=models.CheckConstraint(
+ condition=~Q(archived=True, active=True), name="archived_flag_must_be_disabled"
+ ),
+ ),
+ ]
diff --git a/products/feature_flags/backend/migrations/0006_validate_archived_flag_must_be_disabled.py b/products/feature_flags/backend/migrations/0006_validate_archived_flag_must_be_disabled.py
new file mode 100644
index 000000000000..4c4bf03edbc7
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0006_validate_archived_flag_must_be_disabled.py
@@ -0,0 +1,13 @@
+from django.db import migrations
+
+from posthog.migration_helpers.not_valid_constraint import ValidateConstraint
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0005_featureflag_archived_disabled_constraint"),
+ ]
+
+ operations = [
+ ValidateConstraint(model_name="featureflag", name="archived_flag_must_be_disabled"),
+ ]
diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txt
index 8340a5df9e39..0eb81c439068 100644
--- a/products/feature_flags/backend/migrations/max_migration.txt
+++ b/products/feature_flags/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_evaluationcontext_hidden_from_suggestions
+0006_validate_archived_flag_must_be_disabled
diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.py
index 0e5bfb0da071..767552f5f73c 100644
--- a/products/feature_flags/backend/models/feature_flag.py
+++ b/products/feature_flags/backend/models/feature_flag.py
@@ -71,6 +71,12 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
updated_at = models.DateTimeField(null=True, auto_now=True)
deleted = models.BooleanField(default=False)
active = models.BooleanField(default=True)
+ # Archived flags are "done for good" (e.g. a finished experiment's flag): hidden from
+ # the flag list by default but kept so linked experiments/surveys retain their data.
+ # An archived flag must be disabled — enforced at the DB level by the
+ # `archived_flag_must_be_disabled` check constraint below, so writers that bypass the
+ # serializer (e.g. the experiment service) can't persist an archived-but-still-serving flag.
+ archived = models.BooleanField(default=False, db_default=False)
version = models.IntegerField(default=1, null=True)
last_modified_by = models.ForeignKey(
@@ -139,7 +145,12 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
objects_including_soft_deleted: models.Manager["FeatureFlag"] = RootTeamManager()
class Meta:
- constraints = [models.UniqueConstraint(fields=["team", "key"], name="unique key for team")]
+ constraints = [
+ models.UniqueConstraint(fields=["team", "key"], name="unique key for team"),
+ # An archived flag must be disabled — keeps an archived flag from ever serving traffic,
+ # regardless of which code path wrote it.
+ models.CheckConstraint(condition=~Q(archived=True, active=True), name="archived_flag_must_be_disabled"),
+ ]
db_table = "posthog_featureflag"
def __str__(self):
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 4b7f62090cda..45e1d0321466 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -193,6 +193,8 @@ export interface FeatureFlagApi {
filters?: FeatureFlagApiFilters
deleted?: boolean
active?: boolean
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean
readonly created_by: UserBasicApi
created_at?: string
/** @nullable */
@@ -692,6 +694,8 @@ export interface FeatureFlagCreateRequestSchemaApi {
filters?: FeatureFlagFiltersSchemaApi
/** Whether the feature flag is active. */
active?: boolean
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean
/** Organizational tags for this feature flag. */
tags?: string[]
/** Evaluation contexts that control where this flag evaluates at runtime. */
@@ -728,6 +732,8 @@ export interface PatchedFeatureFlagPartialUpdateRequestSchemaApi {
filters?: FeatureFlagFiltersSchemaApi
/** Whether the feature flag is active. */
active?: boolean
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean
/** Organizational tags for this feature flag. */
tags?: string[]
/** Evaluation contexts that control where this flag evaluates at runtime. */
@@ -837,7 +843,7 @@ export interface FeatureFlagRolloutSummaryApi {
}
export interface FeatureFlagStatusResponseApi {
- /** Flag staleness/evaluation status: active, stale, deleted, or unknown. 'active' means the flag was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled out. Use the `rollout` object to determine rollout completeness. */
+ /** Flag staleness/evaluation status: active, stale, archived, deleted, or unknown. 'active' means the flag was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled out. Use the `rollout` object to determine rollout completeness. */
status: string
/** Human-readable explanation of the status */
reason: string
@@ -1053,8 +1059,12 @@ export interface BulkDeleteFiltersApi {
excluded_properties?: string
/** Tag names to filter by. Flags carrying at least one of these tags match. */
tags?: string[]
+ /** Tag names to exclude. Flags carrying any of these tags are filtered out. */
+ excluded_tags?: string[]
/** When true, only matches flags with at least one evaluation context. */
has_evaluation_contexts?: boolean
+ /** Filter by archived state. When omitted, archived flags are excluded. */
+ archived?: boolean
}
export interface BulkDeleteRequestApi {
@@ -1404,6 +1414,10 @@ export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive
+ /**
+ * Filter by archived state. When omitted, archived flags are excluded.
+ */
+ archived?: FeatureFlagsListArchived
/**
* Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
@@ -1416,6 +1430,10 @@ export type FeatureFlagsListParams = {
* JSON-encoded list of feature flag keys to exclude from the results.
*/
excluded_properties?: string
+ /**
+ * JSON-encoded list of tag names to exclude. Flags carrying any of these tags are filtered out.
+ */
+ excluded_tags?: string
/**
* Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without.
*/
@@ -1447,6 +1465,13 @@ export const FeatureFlagsListActive = {
True: 'true',
} as const
+export type FeatureFlagsListArchived = (typeof FeatureFlagsListArchived)[keyof typeof FeatureFlagsListArchived]
+
+export const FeatureFlagsListArchived = {
+ False: 'false',
+ True: 'true',
+} as const
+
export type FeatureFlagsListEvaluationRuntime =
(typeof FeatureFlagsListEvaluationRuntime)[keyof typeof FeatureFlagsListEvaluationRuntime]
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 9271ad4f4d2c..99756c95ffe4 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -361,6 +361,12 @@ export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Feature flag targeting configuration.'),
active: zod.boolean().optional().describe('Whether the feature flag is active.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
tags: zod.array(zod.string()).optional().describe('Organizational tags for this feature flag.'),
evaluation_contexts: zod
.array(zod.string())
@@ -422,6 +428,12 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod
filters: zod.record(zod.string(), zod.unknown()).optional(),
deleted: zod.boolean().optional(),
active: zod.boolean().optional(),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
created_at: zod.iso.datetime({ offset: true }).optional(),
version: zod.number().default(featureFlagsUpdateBodyVersionDefault),
ensure_experience_continuity: zod.boolean().nullish(),
@@ -776,6 +788,12 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Feature flag targeting configuration.'),
active: zod.boolean().optional().describe('Whether the feature flag is active.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
tags: zod.array(zod.string()).optional().describe('Organizational tags for this feature flag.'),
evaluation_contexts: zod
.array(zod.string())
@@ -837,6 +855,12 @@ export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ z
filters: zod.record(zod.string(), zod.unknown()).optional(),
deleted: zod.boolean().optional(),
active: zod.boolean().optional(),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
created_at: zod.iso.datetime({ offset: true }).optional(),
version: zod.number().default(featureFlagsCreateStaticCohortForFlagCreateBodyVersionDefault),
ensure_experience_continuity: zod.boolean().nullish(),
@@ -919,6 +943,12 @@ export const FeatureFlagsDashboardCreateBody = /* @__PURE__ */ zod
filters: zod.record(zod.string(), zod.unknown()).optional(),
deleted: zod.boolean().optional(),
active: zod.boolean().optional(),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
created_at: zod.iso.datetime({ offset: true }).optional(),
version: zod.number().default(featureFlagsDashboardCreateBodyVersionDefault),
ensure_experience_continuity: zod.boolean().nullish(),
@@ -1001,6 +1031,12 @@ export const FeatureFlagsEnrichUsageDashboardCreateBody = /* @__PURE__ */ zod
filters: zod.record(zod.string(), zod.unknown()).optional(),
deleted: zod.boolean().optional(),
active: zod.boolean().optional(),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
created_at: zod.iso.datetime({ offset: true }).optional(),
version: zod.number().default(featureFlagsEnrichUsageDashboardCreateBodyVersionDefault),
ensure_experience_continuity: zod.boolean().nullish(),
@@ -1135,10 +1171,18 @@ export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
.array(zod.string())
.optional()
.describe('Tag names to filter by. Flags carrying at least one of these tags match.'),
+ excluded_tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Tag names to exclude. Flags carrying any of these tags are filtered out.'),
has_evaluation_contexts: zod
.boolean()
.optional()
.describe('When true, only matches flags with at least one evaluation context.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe('Filter by archived state. When omitted, archived flags are excluded.'),
})
.describe("Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.")
.optional()
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index a13f1d6477b5..81732c260fa0 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -442,6 +442,7 @@ tools:
- name
- filters
- active
+ - archived
- tags
- evaluation_contexts
- is_remote_configuration
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c5355d3b10dc..1e8350a67c3b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9204,6 +9204,11 @@ export namespace Schemas {
snapshots: ApproveSnapshotInput[];
}
+ export interface ArchiveExperiment {
+ /** When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way). */
+ disable_feature_flag?: boolean;
+ }
+
export interface Artifact {
id: string;
content_hash: string;
@@ -11547,8 +11552,12 @@ export namespace Schemas {
excluded_properties?: string;
/** Tag names to filter by. Flags carrying at least one of these tags match. */
tags?: string[];
+ /** Tag names to exclude. Flags carrying any of these tags are filtered out. */
+ excluded_tags?: string[];
/** When true, only matches flags with at least one evaluation context. */
has_evaluation_contexts?: boolean;
+ /** Filter by archived state. When omitted, archived flags are excluded. */
+ archived?: boolean;
}
export interface BulkDeleteRequest {
@@ -22116,6 +22125,8 @@ export namespace Schemas {
filters?: FeatureFlagFilters;
deleted?: boolean;
active?: boolean;
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean;
readonly created_by: UserBasic;
created_at?: string;
/** @nullable */
@@ -22615,6 +22626,8 @@ export namespace Schemas {
filters?: FeatureFlagFiltersSchema;
/** Whether the feature flag is active. */
active?: boolean;
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean;
/** Organizational tags for this feature flag. */
tags?: string[];
/** Evaluation contexts that control where this flag evaluates at runtime. */
@@ -22657,7 +22670,7 @@ export namespace Schemas {
}
export interface FeatureFlagStatusResponse {
- /** Flag staleness/evaluation status: active, stale, deleted, or unknown. 'active' means the flag was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled out. Use the `rollout` object to determine rollout completeness. */
+ /** Flag staleness/evaluation status: active, stale, archived, deleted, or unknown. 'active' means the flag was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled out. Use the `rollout` object to determine rollout completeness. */
status: string;
/** Human-readable explanation of the status */
reason: string;
@@ -35727,6 +35740,8 @@ export namespace Schemas {
filters?: FeatureFlagFiltersSchema;
/** Whether the feature flag is active. */
active?: boolean;
+ /** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */
+ archived?: boolean;
/** Organizational tags for this feature flag. */
tags?: string[];
/** Evaluation contexts that control where this flag evaluates at runtime. */
@@ -58211,6 +58226,10 @@ export namespace Schemas {
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive;
+ /**
+ * Filter by archived state. When omitted, archived flags are excluded.
+ */
+ archived?: FeatureFlagsListArchived;
/**
* Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
@@ -58223,6 +58242,10 @@ export namespace Schemas {
* JSON-encoded list of feature flag keys to exclude from the results.
*/
excluded_properties?: string;
+ /**
+ * JSON-encoded list of tag names to exclude. Flags carrying any of these tags are filtered out.
+ */
+ excluded_tags?: string;
/**
* Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without.
*/
@@ -58255,6 +58278,14 @@ export namespace Schemas {
True: 'true',
} as const;
+ export type FeatureFlagsListArchived = typeof FeatureFlagsListArchived[keyof typeof FeatureFlagsListArchived];
+
+
+ export const FeatureFlagsListArchived = {
+ False: 'false',
+ True: 'true',
+ } as const;
+
export type FeatureFlagsListEvaluationRuntime = typeof FeatureFlagsListEvaluationRuntime[keyof typeof FeatureFlagsListEvaluationRuntime];
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index cb1dfb145cc2..52da34702ffd 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -4907,8 +4907,10 @@ export const ExperimentsDestroyParams = /* @__PURE__ */ zod.object({
* Archive an ended experiment.
*
* Hides the experiment from the default list view. The experiment can be
- * restored at any time by updating archived=false. Returns 400 if the
- * experiment is already archived or has not ended yet.
+ * restored at any time by updating archived=false. When the linked feature
+ * flag is still enabled, pass disable_feature_flag=true to also disable and
+ * archive it. Returns 400 if the experiment is already archived or has not
+ * ended yet.
*/
export const ExperimentsArchiveCreateParams = /* @__PURE__ */ zod.object({
id: zod.number().describe('A unique integer value identifying this experiment.'),
@@ -4919,6 +4921,17 @@ export const ExperimentsArchiveCreateParams = /* @__PURE__ */ zod.object({
),
})
+export const experimentsArchiveCreateBodyDisableFeatureFlagDefault = false
+
+export const ExperimentsArchiveCreateBody = /* @__PURE__ */ zod.object({
+ disable_feature_flag: zod
+ .boolean()
+ .default(experimentsArchiveCreateBodyDisableFeatureFlagDefault)
+ .describe(
+ 'When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way).'
+ ),
+})
+
/**
* Copy an experiment into another project in the same organization as a new draft.
*/
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index dadd0fdc011b..25cbeb46dd49 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -55,6 +55,10 @@ export const FeatureFlagsListParams = /* @__PURE__ */ zod.object({
export const FeatureFlagsListQueryParams = /* @__PURE__ */ zod.object({
active: zod.enum(['STALE', 'false', 'true']).optional(),
+ archived: zod
+ .enum(['false', 'true'])
+ .optional()
+ .describe('Filter by archived state. When omitted, archived flags are excluded.'),
created_by_id: zod
.string()
.optional()
@@ -69,6 +73,10 @@ export const FeatureFlagsListQueryParams = /* @__PURE__ */ zod.object({
.string()
.optional()
.describe('JSON-encoded list of feature flag keys to exclude from the results.'),
+ excluded_tags: zod
+ .string()
+ .optional()
+ .describe('JSON-encoded list of tag names to exclude. Flags carrying any of these tags are filtered out.'),
has_evaluation_contexts: zod
.enum(['false', 'true'])
.optional()
@@ -384,6 +392,12 @@ export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Feature flag targeting configuration.'),
active: zod.boolean().optional().describe('Whether the feature flag is active.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
tags: zod.array(zod.string()).optional().describe('Organizational tags for this feature flag.'),
evaluation_contexts: zod
.array(zod.string())
@@ -740,6 +754,12 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Feature flag targeting configuration.'),
active: zod.boolean().optional().describe('Whether the feature flag is active.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
+ ),
tags: zod.array(zod.string()).optional().describe('Organizational tags for this feature flag.'),
evaluation_contexts: zod
.array(zod.string())
@@ -930,10 +950,18 @@ export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
.array(zod.string())
.optional()
.describe('Tag names to filter by. Flags carrying at least one of these tags match.'),
+ excluded_tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Tag names to exclude. Flags carrying any of these tags are filtered out.'),
has_evaluation_contexts: zod
.boolean()
.optional()
.describe('When true, only matches flags with at least one evaluation context.'),
+ archived: zod
+ .boolean()
+ .optional()
+ .describe('Filter by archived state. When omitted, archived flags are excluded.'),
})
.describe("Allowed filter keys for bulk_delete — same shape as the list endpoint's query params.")
.optional()
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 0331fd7ec7b3..2a0cebf73958 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -9,6 +9,7 @@ import {
ExperimentSavedMetricsPartialUpdateBody,
ExperimentSavedMetricsPartialUpdateParams,
ExperimentSavedMetricsRetrieveParams,
+ ExperimentsArchiveCreateBody,
ExperimentsArchiveCreateParams,
ExperimentsCalculateRunningTimeCreateBody,
ExperimentsCopyToProjectCreateBody,
@@ -38,9 +39,9 @@ import { castStringToInt } from '@/tools/cast-helpers'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-const ExperimentArchiveSchema = ExperimentsArchiveCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']),
-})
+const ExperimentArchiveSchema = ExperimentsArchiveCreateParams.omit({ project_id: true })
+ .extend(ExperimentsArchiveCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']) })
const experimentArchive = (): ToolBase<typeof ExperimentArchiveSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -48,9 +49,14 @@ const experimentArchive = (): ToolBase<typeof ExperimentArchiveSchema, WithPostH
schema: ExperimentArchiveSchema,
handler: async (context: Context, params: z.infer<typeof ExperimentArchiveSchema>) => {
const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.disable_feature_flag !== undefined) {
+ body['disable_feature_flag'] = params.disable_feature_flag
+ }
const result = await context.api.request<Schemas.Experiment>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/archive/`,
+ body,
})
return await withPostHogUrl(context, result, `/experiments/${result.id}`)
},
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 352d3b815ae8..c156b77eb9f5 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -35,7 +35,7 @@ import { castStringToInt } from '@/tools/cast-helpers'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-const CreateFeatureFlagSchema = FeatureFlagsCreateBody.extend({
+const CreateFeatureFlagSchema = FeatureFlagsCreateBody.omit({ archived: true }).extend({
is_remote_configuration: FeatureFlagsCreateBody.shape['is_remote_configuration'].describe(
'Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set the delivered payload through the `filters` param under `filters.payloads.true` as a JSON-encoded string. There is no dedicated payload parameter.'
),
@@ -134,9 +134,11 @@ const featureFlagGetAll = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/`,
query: {
active: params.active,
+ archived: params.archived,
created_by_id: params.created_by_id,
evaluation_runtime: params.evaluation_runtime,
excluded_properties: params.excluded_properties,
+ excluded_tags: params.excluded_tags,
has_evaluation_contexts: params.has_evaluation_contexts,
limit: params.limit,
offset: params.offset,
@@ -647,6 +649,9 @@ const updateFeatureFlag = (): ToolBase<typeof UpdateFeatureFlagSchema, WithPostH
if (params.active !== undefined) {
body['active'] = params.active
}
+ if (params.archived !== undefined) {
+ body['archived'] = params.archived
+ }
if (params.tags !== undefined) {
body['tags'] = params.tags
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-archive.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-archive.json
index 1f1461179dd3..a193f28dd5d7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-archive.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-archive.json
@@ -1,6 +1,11 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "disable_feature_flag": {
+ "default": false,
+ "description": "When the linked feature flag is still enabled, also disable and archive it along with the experiment. Has no effect if the flag is already disabled (it is archived either way).",
+ "type": "boolean"
+ },
"id": {
"description": "A unique integer value identifying this experiment.",
"type": "number"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
index 1b10662e4769..d5bdccea390d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
@@ -5,6 +5,11 @@
"enum": ["STALE", "false", "true"],
"type": "string"
},
+ "archived": {
+ "description": "Filter by archived state. When omitted, archived flags are excluded.",
+ "enum": ["false", "true"],
+ "type": "string"
+ },
"created_by_id": {
"description": "Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.",
"type": "string"
@@ -18,6 +23,10 @@
"description": "JSON-encoded list of feature flag keys to exclude from the results.",
"type": "string"
},
+ "excluded_tags": {
+ "description": "JSON-encoded list of tag names to exclude. Flags carrying any of these tags are filtered out.",
+ "type": "string"
+ },
"has_evaluation_contexts": {
"description": "Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without.",
"enum": ["false", "true"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json
index e15501ab2c55..4e6f76779235 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json
@@ -9,6 +9,10 @@
"enum": ["true", "false", "STALE"],
"type": "string"
},
+ "archived": {
+ "description": "Filter by archived state. When omitted, archived flags are excluded.",
+ "type": "boolean"
+ },
"created_by_id": {
"description": "Filter to flags created by a specific user ID.",
"type": "number"
@@ -22,6 +26,13 @@
"description": "JSON-encoded property filter to exclude. Same shape as the list endpoint.",
"type": "string"
},
+ "excluded_tags": {
+ "description": "Tag names to exclude. Flags carrying any of these tags are filtered out.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"has_evaluation_contexts": {
"description": "When true, only matches flags with at least one evaluation context.",
"type": "boolean"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json
index d02d402c6856..c7d0109663f6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json
@@ -5,6 +5,10 @@
"description": "Whether the feature flag is active.",
"type": "boolean"
},
+ "archived": {
+ "description": "Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).",
+ "type": "boolean"
+ },
"bucketing_identifier": {
"anyOf": [
{