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): explain stale status on the flag detail page (#90214)

James Gill3300cac9a65a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f356aeaaa879..9809edcc1d91 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6944,6 +6944,10 @@ snapshots:
hash: v1.k794b7964.e08249de5d15170f153371d39a565900bb2bbfc88b8bfd3d38a2600cff9065e3.qDTsHl-ou0yZimNtzHHuM3R3c7N8zdSt0A8LUIMc2dc
scenes-app-feature-flags--new-remote-config-flag-payload-error--light:
hash: v1.k794b7964.bbbbecef36aa418ff943f76d2006e75aec34f4ed6b26c4303ad005cbc95771ce.t6SkxtqE_6K7m6nlXwksQYnWs2s91AkmcYNUBy5ao-8
+ scenes-app-feature-flags--stale-feature-flag--dark:
+ hash: v1.k794b7964.214b934af2eb71704ef4af64e7bcfc3fbb28ad3773918bda4e44c20baeafcbad.8sHPg_xq9nSmcUHiVqmWx5xtfnUGFA7o96H2Xe4xWwE
+ scenes-app-feature-flags--stale-feature-flag--light:
+ hash: v1.k794b7964.b8b76f0cb2539ca5dace61ff7cdb75ff0d749efbb3c682d79cd5fd7cd9ab95bf.0131PJ9_-uAsdJezfweIeC_AYlVSHdn6Q9WJ2chWHy4
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--dark:
hash: v1.k794b7964.33b7e69158cdb17991413a077b7dac6e915f6899c917fea9086f39fb02409699.paRiPQ8Dk84qM73rCI6ccr0k9jO1Oy0PpXtRG5PfiTM
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 6a25aa86f257..606fcabcd3f8 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -38,6 +38,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'resolveFingerprint', // Retried while the error finishes ingesting; the fingerprint scene surfaces its own state
'saveEarlyAccessFeature', // Field-level errors handled in earlyAccessFeatureLogic
'loadWaitlistResponsesCount', // Soft-fails to a dash on the features list when survey access is missing
+ 'loadFeatureFlagStatus', // The flag page just hides its stale banner when the verdict can't be loaded
'loadExistingSubscription', // Background eligibility check for the dashboard subscribe nudge
'loadFreeTierSubscriptionCount', // Background free-tier limit check for the dashboard subscribe nudge
'sendNudgeNotification', // Background delivery request for the dashboard subscribe nudge
diff --git a/frontend/src/layout/navigation-3000/sidepanel/SidePanel.stories.tsx b/frontend/src/layout/navigation-3000/sidepanel/SidePanel.stories.tsx
index 35b1beabfc0f..94f7df8d7dd0 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/SidePanel.stories.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/SidePanel.stories.tsx
@@ -61,6 +61,12 @@ const meta: Meta<StoryArgs> = {
'/api/projects/:team_id/feature_flags/:flagId/status': {
status: 'active',
reason: 'Feature flag is active',
+ rollout: {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 50,
+ is_multivariate: false,
+ },
},
'/api/projects/:team_id/feature_flags/:flagId/activity': { results: [], count: 0 },
'/api/projects/:team_id/feature_flags/:flagId/access_controls': {
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a4c34fd62eb9..0144432e7146 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -125,7 +125,6 @@ import {
ExternalDataSourceRevenueAnalyticsConfig,
ExternalDataSourceSchema,
ExternalDataSourceSyncSchema,
- FeatureFlagStatusResponse,
FeatureFlagType,
FileSystemDeleteResponse,
GoogleAdsConversionActionType,
@@ -1167,13 +1166,6 @@ export class ApiRequest {
)
}
- public featureFlagStatus(teamId: TeamType['id'], featureFlagId: FeatureFlagType['id']): ApiRequest {
- return this.projectsDetail(teamId)
- .addPathComponent('feature_flags')
- .addPathComponent(String(featureFlagId))
- .addPathComponent('status')
- }
-
public featureFlagCreateScheduledChange(teamId: TeamType['id']): ApiRequest {
return this.projectsDetail(teamId).addPathComponent('scheduled_changes')
}
@@ -2416,12 +2408,6 @@ const api = {
): Promise<ScheduledChangeType> {
return await new ApiRequest().featureFlagScheduledChange(teamId, scheduledChangeId).update({ data })
},
- async getStatus(
- teamId: TeamType['id'],
- featureFlagId: FeatureFlagType['id']
- ): Promise<FeatureFlagStatusResponse> {
- return await new ApiRequest().featureFlagStatus(teamId, featureFlagId).get()
- },
},
fileSystem: {
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
index 17026b6336fc..02be00e085ad 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
@@ -79,6 +79,7 @@ import {
QueryBasedInsightModel,
} from '~/types'
+import { FeatureFlagStaleBanner } from 'products/feature_flags/frontend/FeatureFlagStaleBanner'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { featureFlagContextItems } from './featureFlagAiContext'
@@ -478,6 +479,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {
experiments and surveys keep their data.
</LemonBanner>
)}
+ <FeatureFlagStaleBanner />
{earlyAccessFeature && earlyAccessFeature.stage === EarlyAccessFeatureStage.Concept && (
<LemonBanner type="info">
This feature flag is assigned to an early access feature in the{' '}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
index 43654d6b453c..53e26f5e6703 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
@@ -9,6 +9,8 @@ import { mswDecorator } from '~/mocks/browser'
import featureFlags from './__mocks__/feature_flags.json'
import { featureFlagLogic } from './featureFlagLogic'
+const STALE_FLAG_ID = 1498
+
const meta: Meta = {
component: App,
tags: ['ff'],
@@ -34,17 +36,51 @@ const meta: Meta = {
detail: 'Not found.',
},
],
- '/api/projects/:team_id/feature_flags/:flagId/': ({ params }) => [
- 200,
- featureFlags.results.find((r) => r.id === Number(params['flagId'])),
- ],
- '/api/projects/:team_id/feature_flags/:flagId/status': () => [
- 200,
- {
- status: 'active',
- reason: 'Feature flag is active',
- },
- ],
+ '/api/projects/:team_id/feature_flags/:flagId/': ({ params }) => {
+ const flag = featureFlags.results.find((r) => r.id === Number(params['flagId']))
+ if (flag?.id !== STALE_FLAG_ID) {
+ return [200, flag]
+ }
+ // A flag that stopped being called but still gates 40% of users. That is the
+ // case the stale banner exists for, because "stale" reads most easily as "safe
+ // to delete" when the flag is still live for real users.
+ return [
+ 200,
+ {
+ ...flag,
+ last_called_at: '2022-12-14T00:00:00Z',
+ filters: { ...flag.filters, groups: [{ properties: [], rollout_percentage: 40 }] },
+ },
+ ]
+ },
+ '/api/projects/:team_id/feature_flags/:flagId/status': ({ params }) =>
+ Number(params['flagId']) === STALE_FLAG_ID
+ ? [
+ 200,
+ {
+ status: 'stale',
+ reason: 'Flag has not been called in 45 days',
+ rollout: {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 40,
+ is_multivariate: false,
+ },
+ },
+ ]
+ : [
+ 200,
+ {
+ status: 'active',
+ reason: 'Feature flag is active',
+ rollout: {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 50,
+ is_multivariate: false,
+ },
+ },
+ ],
'/api/environments/:team_id/default_evaluation_contexts/': {
default_evaluation_contexts: [],
available_contexts: [],
@@ -95,6 +131,12 @@ export const EditEncryptedRemoteConfigFeatureFlag: Story = {
},
}
+export const StaleFeatureFlag: Story = {
+ parameters: {
+ pageUrl: urls.featureFlag(STALE_FLAG_ID),
+ },
+}
+
export const FeatureFlagNotFound: Story = {
parameters: {
pageUrl: urls.featureFlag(1111111111111),
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index f86f9b6aba4e..42f6ba8e3c41 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -93,6 +93,12 @@ const MOCK_FEATURE_FLAG = {
const MOCK_FEATURE_FLAG_STATUS = {
status: 'active',
reason: 'mock reason',
+ rollout: {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 50,
+ is_multivariate: false,
+ },
}
const MOCK_EXPERIMENT = {
@@ -2304,6 +2310,168 @@ describe('featureFlagLogic', () => {
})
})
+ describe('stale status after a mutation', () => {
+ const STATUS_URL = `/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/status`
+
+ function statusMock(status: string, reason: string): Parameters<typeof useMocks>[0] {
+ return { get: { [STATUS_URL]: () => [200, { ...MOCK_FEATURE_FLAG_STATUS, status, reason }] } }
+ }
+
+ // The banner asks the reader to disable the flag or change its rollout. `flagStatus` is a
+ // server verdict about the saved flag, so without a refetch it keeps the boot-time answer
+ // and the banner advises an action the reader already took.
+ it.each([
+ [
+ 'the flag is disabled',
+ () => logic.actions.updateFeatureFlagActiveSuccess({ ...MOCK_FEATURE_FLAG, active: false }),
+ ],
+ ['an edit is saved', () => logic.actions.saveFeatureFlagSuccess(MOCK_FEATURE_FLAG)],
+ ])('clears the stale banner when %s', async (_name, mutate) => {
+ useMocks(statusMock('stale', 'Flag has not been called in 45 days'))
+ await expectLogic(logic, () => logic.actions.loadFeatureFlagStatus()).toFinishAllListeners()
+ expect(logic.values.showStaleFlagBanner).toBe(true)
+
+ useMocks(statusMock('active', 'Flag is disabled (not evaluated for staleness)'))
+ await expectLogic(logic, mutate).toFinishAllListeners()
+
+ expect(logic.values.showStaleFlagBanner).toBe(false)
+ })
+
+ it('hides the stale banner when a post-mutation status refresh fails', async () => {
+ // kea-loaders keeps the prior value on failure, so a refetch that 500s must not leave the
+ // banner rendering the earlier stale verdict. Silence the loader's logged rejection.
+ silenceKeaLoadersErrors()
+ try {
+ useMocks(statusMock('stale', 'Flag has not been called in 45 days'))
+ await expectLogic(logic, () => logic.actions.loadFeatureFlagStatus()).toFinishAllListeners()
+ expect(logic.values.showStaleFlagBanner).toBe(true)
+
+ useMocks({ get: { [STATUS_URL]: () => [500, {}] } })
+ await expectLogic(logic, () => logic.actions.loadFeatureFlagStatus()).toFinishAllListeners()
+
+ expect(logic.values.showStaleFlagBanner).toBe(false)
+ } finally {
+ resumeKeaLoadersErrors()
+ }
+ })
+
+ it('keeps the newest verdict when an earlier status request resolves last', async () => {
+ // Two overlapping requests to the same URL, with the older one resolving last. Without the
+ // loader's breakpoint, that late stale success would overwrite the newer verdict.
+ const resolvers: Array<(response: [number, Record<string, unknown>]) => void> = []
+ const waitForRequests = async (count: number): Promise<void> => {
+ for (let attempt = 0; attempt < 20 && resolvers.length < count; attempt++) {
+ await Promise.resolve()
+ }
+ if (resolvers.length < count) {
+ throw new Error(`Expected ${count} status requests, saw ${resolvers.length}`)
+ }
+ }
+ useMocks({ get: { [STATUS_URL]: async () => new Promise((resolve) => resolvers.push(resolve)) } })
+
+ logic.actions.loadFeatureFlagStatus() // older request
+ await waitForRequests(1)
+ logic.actions.loadFeatureFlagStatus() // newer request
+ await waitForRequests(2)
+
+ resolvers[1]([200, { ...MOCK_FEATURE_FLAG_STATUS, status: 'active', reason: 'Flag was called today' }])
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagStatusSuccess'])
+
+ resolvers[0]([
+ 200,
+ { ...MOCK_FEATURE_FLAG_STATUS, status: 'stale', reason: 'Flag has not been called in 45 days' },
+ ])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.flagStatus?.status).toBe('active')
+ })
+
+ it('clears the stale banner when the current flag is disabled from the Projects tab', async () => {
+ const patchMock = {
+ patch: {
+ '/api/projects/:team_id/feature_flags/:id/': async ({ request, params }: any) => {
+ const body = (await request.json()) as { active: boolean }
+ return [200, { id: Number(params.id), active: body.active }]
+ },
+ },
+ }
+ useMocks({ ...statusMock('stale', 'Flag has not been called in 45 days'), ...patchMock })
+ await expectLogic(logic, () => logic.actions.loadFeatureFlagStatus()).toFinishAllListeners()
+ expect(logic.values.showStaleFlagBanner).toBe(true)
+
+ useMocks({ ...statusMock('active', 'Flag is disabled (not evaluated for staleness)'), ...patchMock })
+ await expectLogic(logic, () =>
+ logic.actions.toggleProjectFlagActive(MOCK_TEAM_ID, MOCK_FEATURE_FLAG.id, false)
+ ).toFinishAllListeners()
+
+ expect(logic.values.showStaleFlagBanner).toBe(false)
+ })
+
+ it('shows the stale banner after a restored flag turns out stale', async () => {
+ // Restore un-deletes the flag, so the retained DELETED verdict is no longer right. Without
+ // a refetch the banner keeps that verdict and never surfaces the restored flag's staleness.
+ const updateSpy = jest.spyOn(api, 'update').mockResolvedValue({ ...MOCK_FEATURE_FLAG, deleted: false })
+ try {
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [
+ 200,
+ MOCK_FEATURE_FLAG,
+ ],
+ [STATUS_URL]: () => [
+ 200,
+ {
+ ...MOCK_FEATURE_FLAG_STATUS,
+ status: 'stale',
+ reason: 'Flag has not been called in 45 days',
+ },
+ ],
+ },
+ })
+ await expectLogic(logic, () =>
+ logic.actions.restoreFeatureFlag(MOCK_FEATURE_FLAG)
+ ).toFinishAllListeners()
+
+ expect(logic.values.showStaleFlagBanner).toBe(true)
+ } finally {
+ updateSpy.mockRestore()
+ }
+ })
+
+ it('shows the stale banner after an unarchived flag turns out stale', async () => {
+ // While the flag is archived the endpoint answers ARCHIVED, so that verdict is what sits
+ // in flagStatus. Unarchiving clears the selector's archived guard, and only the refetch
+ // replaces the retained verdict. The archived direction is hidden by that guard either
+ // way, so it cannot cover this.
+ const updateSpy = jest.spyOn(api, 'update').mockResolvedValue({ ...MOCK_FEATURE_FLAG, archived: false })
+ try {
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [
+ 200,
+ { ...MOCK_FEATURE_FLAG, archived: false },
+ ],
+ [STATUS_URL]: () => [
+ 200,
+ {
+ ...MOCK_FEATURE_FLAG_STATUS,
+ status: 'stale',
+ reason: 'Flag has not been called in 45 days',
+ },
+ ],
+ },
+ })
+ await expectLogic(logic, () =>
+ logic.actions.updateFeatureFlagArchived({ archived: false })
+ ).toFinishAllListeners()
+
+ expect(logic.values.showStaleFlagBanner).toBe(true)
+ } finally {
+ updateSpy.mockRestore()
+ }
+ })
+ })
+
describe('updateFeatureFlagArchived archive telemetry', () => {
// One test here rejects the archive request on purpose; kea-loaders would log the failure
beforeEach(silenceKeaLoadersErrors)
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index e182863ad8ca..bc0b635ddcd0 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -65,7 +65,7 @@ import {
FeatureFlagBucketingIdentifier,
FeatureFlagEvaluationRuntime,
FeatureFlagGroupType,
- FeatureFlagStatusResponse,
+ FeatureFlagStatus,
FeatureFlagType,
FilterLogicalOperator,
InsightModel,
@@ -93,8 +93,12 @@ import {
featureFlagsCopyFlagsCreate,
featureFlagsCopyFlagsDependencyRequirementsCreate,
featureFlagsList,
+ featureFlagsStatusRetrieve,
} from 'products/feature_flags/frontend/generated/api'
-import type { CopyFlagsDependencyRequirementsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'
+import type {
+ CopyFlagsDependencyRequirementsResponseApi,
+ FeatureFlagStatusResponseApi,
+} from 'products/feature_flags/frontend/generated/api.schemas'
import type { CopyFlagsResponseApi } from '../../../../products/feature_flags/frontend/generated/api.schemas'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
@@ -868,7 +872,7 @@ export interface featureFlagLogicValues {
ValidationErrorType
>
flagIntent: FlagIntent | null
- flagStatus: FeatureFlagStatusResponse | null
+ flagStatus: FeatureFlagStatusResponseApi | null
flagStatusLoading: boolean
flagType: 'boolean' | 'multivariate' | 'remote_config'
flagTypeString:
@@ -929,6 +933,7 @@ export interface featureFlagLogicValues {
selectedTab: FeatureFlagsTab
showFeatureFlagErrors: boolean
showImplementation: boolean
+ showStaleFlagBanner: boolean
sidePanelContext: SidePanelSceneContext | null
templateExpanded: boolean
templates: Array<{
@@ -1150,7 +1155,7 @@ export interface featureFlagLogicActions {
error: string
errorObject?: any
}
- loadFeatureFlagStatus: () => any
+ loadFeatureFlagStatus: (_: void) => void
loadFeatureFlagStatusFailure: (
error: string,
errorObject?: any
@@ -1159,11 +1164,11 @@ export interface featureFlagLogicActions {
errorObject?: any
}
loadFeatureFlagStatusSuccess: (
- flagStatus: Promise<FeatureFlagStatusResponse> | null,
- payload?: any
+ flagStatus: FeatureFlagStatusResponseApi | null,
+ payload?: void
) => {
- flagStatus: Promise<FeatureFlagStatusResponse> | null
- payload?: any
+ flagStatus: FeatureFlagStatusResponseApi | null
+ payload?: void
}
loadFeatureFlagSuccess: (
featureFlag: FeatureFlagType,
@@ -1931,6 +1936,7 @@ export interface featureFlagLogicMeta {
hasSurveys: (featureFlag: FeatureFlagType) => boolean | null
hasEncryptedPayloadBeenSaved: (featureFlag: FeatureFlagType, props: any) => boolean | undefined
hasExperiment: (featureFlag: FeatureFlagType) => boolean | null
+ showStaleFlagBanner: (featureFlag: FeatureFlagType, flagStatus: FeatureFlagStatusResponseApi | null) => boolean
isDraftExperiment: (experiment: any) => boolean
properties: (featureFlag: FeatureFlagType) => AnyPropertyFilter[]
variantErrors: (variants: MultivariateFlagVariant[]) => VariantError[]
@@ -3246,13 +3252,28 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
}
},
},
+ // A server verdict about the saved flag, so it does not follow the working copy. Every
+ // mutation that can change staleness or rollout must dispatch this again, or the stale
+ // banner outlives the change the reader just made.
flagStatus: [
- null as FeatureFlagStatusResponse | null,
+ null as FeatureFlagStatusResponseApi | null,
{
- loadFeatureFlagStatus: () => {
+ loadFeatureFlagStatus: async (_: void, breakpoint) => {
const { currentProjectId } = values
if (currentProjectId && props.id && props.id !== 'new' && props.id !== 'link') {
- return api.featureFlags.getStatus(currentProjectId, props.id)
+ try {
+ const status = await featureFlagsStatusRetrieve(String(currentProjectId), props.id)
+ // A mutation can start a newer status request while this one is open. Discard
+ // this response if so, or a slow earlier request would overwrite the newer verdict.
+ breakpoint()
+ return status
+ } catch (error) {
+ // The failure reducer nulls the verdict, so a superseded request that fails
+ // late would erase the verdict a newer request already wrote. Breakpoint
+ // first: kea-loaders swallows that and dispatches no failure.
+ breakpoint()
+ throw error
+ }
}
return null
},
@@ -3289,6 +3310,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
projectFlagActiveUpdated: (state, { teamId, flagId, active }) =>
state.map((p) => (p.team_id === teamId && p.flag_id === flagId ? { ...p, active } : p)),
},
+ // kea-loaders keeps the prior value when a refetch fails, so a failed status refresh after a
+ // mutation would leave the banner rendering a verdict for a flag that no longer has it. Drop
+ // the verdict when a refetch starts or fails; only a successful load may show the banner.
+ flagStatus: {
+ loadFeatureFlagStatus: () => null,
+ loadFeatureFlagStatusFailure: () => null,
+ },
}),
listeners(({ actions, values, props, sharedListeners }) => ({
loadCopyDependencyRequirements: async (_, breakpoint): Promise<void> => {
@@ -3561,6 +3589,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
// Whole flag just persisted — the baseline is now the saved state, so the form reads clean.
actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlag))
actions.updateFlag(featureFlag)
+ actions.loadFeatureFlagStatus()
if (featureFlag.id && isOnFeatureFlagPage(props.id)) {
router.actions.replace(urls.featureFlag(featureFlag.id))
}
@@ -3646,6 +3675,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlagActiveUpdate))
}
actions.updateFlag(featureFlagActiveUpdate)
+ actions.loadFeatureFlagStatus()
}
},
toggleProjectFlagActive: async ({ teamId, flagId, active }) => {
@@ -3677,6 +3707,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
}
actions.updateFlag(syncedFlag)
refreshTreeItem('feature_flag', String(flagId))
+ // Disabling changes the staleness verdict, so refetch it as the other mutation
+ // paths do, or the stale banner outlives the toggle made from the Projects tab.
+ actions.loadFeatureFlagStatus()
}
},
refreshFeatureFlagSuccess: ({ featureFlagRefresh }) => {
@@ -3719,6 +3752,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlagActiveUpdate))
}
actions.updateFlag(featureFlagActiveUpdate)
+ actions.loadFeatureFlagStatus()
}
},
updateFeatureFlagArchivedFailure: ({ errorObject }) => {
@@ -3772,6 +3806,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
refreshTreeItem('feature_flag', String(featureFlag.id))
}
actions.loadFeatureFlag()
+ // The flag is no longer deleted, so its real verdict may differ from the retained
+ // DELETED one. Refetch it so the banner reflects the restored flag.
+ actions.loadFeatureFlagStatus()
},
})
},
@@ -4420,6 +4457,25 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
return featureFlag?.experiment_set && featureFlag.experiment_set.length > 0
},
],
+ // The status endpoint serializes a StrEnum through a CharField, so it answers with the
+ // lowercase value 'stale'. The flag list serializer returns the enum member name 'STALE'
+ // instead. Both are typed as plain strings, so a wrong comparison here fails silently.
+ showStaleFlagBanner: [
+ (s) => [s.featureFlag, s.flagStatus],
+ (featureFlag: FeatureFlagType, flagStatus: FeatureFlagStatusResponseApi | null): boolean => {
+ // The reducer nulls `flagStatus` when a load starts or fails, so only a settled,
+ // successful verdict reaches this comparison.
+ if (flagStatus?.status !== FeatureFlagStatus.STALE) {
+ return false
+ }
+ return Boolean(
+ featureFlag.id &&
+ !featureFlag.deleted &&
+ !featureFlag.archived &&
+ !featureFlag.is_remote_configuration
+ )
+ },
+ ],
isDraftExperiment: [
(s) => [s.experiment],
(experiment) => {
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
index e243e6de24a0..6794c5cf4fa4 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
@@ -333,6 +333,12 @@ const meta: Meta = {
[`/api/projects/:team_id/feature_flags/${FEATURE_FLAG_ID}/status`]: {
status: 'active',
reason: 'Feature flag is active',
+ rollout: {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 50,
+ is_multivariate: false,
+ },
},
[`/api/projects/:team_id/surveys/${SURVEY_ID}/`]: survey,
'/api/projects/:team_id/surveys/responses_count/': { [SURVEY_ID]: 42 },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 074f19c91b99..fab7d7d21a37 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4518,11 +4518,6 @@ export enum FeatureFlagStatus {
UNKNOWN = 'unknown',
}
-export interface FeatureFlagStatusResponse {
- status: FeatureFlagStatus
- reason: string
-}
-
export interface CombinedFeatureFlagAndValueType {
feature_flag: FeatureFlagType
value: boolean | string
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index adfc77be2d78..910ce7d2fa41 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -2604,6 +2604,21 @@ class EvaluationReasonsResponseSerializer(serializers.Serializer):
pass
+class WholeNumberFloatField(serializers.FloatField):
+ """Keeps a fractional rollout, and leaves a whole one as the integer the API already sent.
+
+ A plain FloatField renders 40 as 40.0, which moves the documented type of a published
+ response from integer to number. FinitePercentageField normalizes the same data on the
+ write side for the same reason.
+ """
+
+ # DRF stubs type the base `Field.to_representation` as `-> str`, so a numeric return trips
+ # `[override]`. FloatField itself returns a float at runtime, so the narrower type is correct.
+ def to_representation(self, value: Any) -> int | float: # type: ignore[override]
+ number = float(value)
+ return int(number) if number.is_integer() else number
+
+
class FeatureFlagRolloutSummarySerializer(serializers.Serializer):
effectively_full_rollout = serializers.BooleanField(
help_text=(
@@ -2617,16 +2632,18 @@ class FeatureFlagRolloutSummarySerializer(serializers.Serializer):
has_targeting_conditions = serializers.BooleanField(
help_text=(
"True if any release condition has property filters, i.e. the flag is conditionally targeted "
- "rather than a blanket rollout. When true, `max_rollout_percentage` is a percentage within the "
- "targeted segment, not of the whole user base."
+ "rather than a blanket rollout. This says nothing about which condition produced "
+ "`max_rollout_percentage`: the two fields are computed independently over the whole condition "
+ "list."
)
)
- max_rollout_percentage = serializers.IntegerField(
+ max_rollout_percentage = WholeNumberFloatField(
allow_null=True,
help_text=(
"Highest rollout percentage (0-100) across the flag's release conditions, treating a missing "
- "percentage as 100. Null when the flag has no release conditions. Interpret together with "
- "`has_targeting_conditions`."
+ "percentage as 100. Null when the flag has no release conditions. The maximum can come from an "
+ "untargeted condition even when `has_targeting_conditions` is true, so it cannot be attributed "
+ "to a targeted condition or read as a share of a targeted segment."
),
)
is_multivariate = serializers.BooleanField(
@@ -2643,6 +2660,13 @@ class FeatureFlagStatusResponseSerializer(serializers.Serializer):
)
)
reason = serializers.CharField(help_text="Human-readable explanation of the status")
+ reason_states_rollout = serializers.BooleanField(
+ help_text=(
+ "True when `reason` already describes the flag's rollout, which happens when the status was reached "
+ "from the configuration rather than from evaluation data. A caller that narrates the rollout "
+ "separately should stay quiet rather than repeat it."
+ )
+ )
rollout = FeatureFlagRolloutSummarySerializer(
help_text="Summary of the flag's rollout configuration, for determining whether it is fully rolled out."
)
@@ -4517,7 +4541,12 @@ class FeatureFlagViewSet(
# Route through the declared serializer so it is the single source of truth for the
# response shape and the dataclass cannot silently drift from the OpenAPI/MCP schema.
response = FeatureFlagStatusResponseSerializer(
- {"status": flag_status, "reason": reason, "rollout": asdict(rollout)}
+ {
+ "status": flag_status,
+ "reason": reason,
+ "reason_states_rollout": checker.reason_states_rollout,
+ "rollout": asdict(rollout),
+ }
)
return Response(response.data, status=status.HTTP_200_OK)
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 df87f982416a..65e73b8a329e 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -17,7 +17,7 @@ from unittest.mock import ANY, MagicMock, patch
from django.core.cache import cache
from django.db import IntegrityError
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils.timezone import now
import grpc
@@ -62,6 +62,7 @@ from products.feature_flags.backend.api.feature_flag import (
FLAG_FILTERS_VIOLATION_COUNTER,
FLAG_FILTERS_WRITE_COUNTER,
FeatureFlagSerializer,
+ FeatureFlagStatusResponseSerializer,
parse_created_by_ids,
)
from products.feature_flags.backend.encrypted_flag_payloads import (
@@ -11723,6 +11724,26 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):
self.assertEqual(len(entries), 1)
+class TestFeatureFlagStatusResponseSerializer(SimpleTestCase):
+ def test_fractional_rollout_percentage_is_not_truncated(self):
+ # Release conditions accept decimals, so a rollout can be 0.5. IntegerField dropped that
+ # to 0, which made the stale banner read "0% of all users" for a flag still gating users.
+ serialized = FeatureFlagStatusResponseSerializer(
+ {
+ "status": FeatureFlagStatus.STALE,
+ "reason": "Flag has not been called in 45 days",
+ "reason_states_rollout": False,
+ "rollout": {
+ "effectively_full_rollout": False,
+ "has_targeting_conditions": False,
+ "max_rollout_percentage": 0.5,
+ "is_multivariate": False,
+ },
+ }
+ ).data
+ assert serialized["rollout"]["max_rollout_percentage"] == 0.5
+
+
class TestFeatureFlagStatus(APIBaseTest, ClickhouseTestMixin):
def setUp(self):
cache.clear()
@@ -12303,6 +12324,45 @@ class TestFeatureFlagStatus(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["rollout"], expected_rollout)
+ # (name, last_called_at, expected) — the route the stale verdict came from.
+ @parameterized.expand(
+ [
+ ("config_route", None, True),
+ ("usage_route", datetime.now(UTC) - timedelta(days=45), False),
+ ]
+ )
+ def test_flag_status_reports_whether_reason_states_rollout(self, name, last_called_at, expected):
+ flag = FeatureFlag.objects.create(
+ name=f"{name} flag",
+ key=f"{name}-flag",
+ team=self.team,
+ active=True,
+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},
+ last_called_at=last_called_at,
+ created_at=datetime.now(UTC) - timedelta(days=45),
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/status")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["status"], FeatureFlagStatus.STALE)
+ self.assertEqual(response.json()["reason_states_rollout"], expected)
+
+ def test_flag_status_keeps_whole_rollout_percentages_as_integers(self):
+ """A whole rollout stays the integer the endpoint has always sent; a fractional one keeps its value."""
+ for key, percentage, expected in (("whole", 100, 100), ("fractional", 0.5, 0.5)):
+ flag = FeatureFlag.objects.create(
+ name=f"{key} flag",
+ key=f"{key}-rollout-flag",
+ team=self.team,
+ active=True,
+ filters={"groups": [{"rollout_percentage": percentage, "properties": []}]},
+ last_called_at=datetime.now(UTC),
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/status")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ returned = response.json()["rollout"]["max_rollout_percentage"]
+ self.assertEqual(returned, expected)
+ self.assertIsInstance(returned, type(expected))
+
def test_get_flags_with_stale_filter_usage_and_config_based(self):
"""Test filtering by STALE status with both usage and config-based detection"""
FeatureFlag.objects.all().delete()
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index 48b48537ad1e..f029fbfda35d 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -1,4 +1,3 @@
-from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from enum import StrEnum
@@ -6,6 +5,8 @@ from django.db.models import Q, QuerySet
import structlog
+from posthog.dataclasses import frozen
+
from .models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -32,14 +33,15 @@ class FeatureFlagStatus(StrEnum):
UNKNOWN = "unknown"
-@dataclass
+@frozen
class FeatureFlagRolloutSummary:
# Whether the flag is effectively rolled out to everyone, independent of recent evaluation.
effectively_full_rollout: bool
# Whether any release condition has property filters (conditionally targeted vs. blanket rollout).
has_targeting_conditions: bool
# Highest rollout percentage across release conditions, or None when there are no conditions.
- max_rollout_percentage: int | None
+ # A fractional rollout (e.g. 0.5) stays a float, matching how conditions store the value.
+ max_rollout_percentage: int | float | None
# Whether the flag serves multiple variants.
is_multivariate: bool
@@ -185,6 +187,10 @@ class FeatureFlagStatusChecker:
):
self.feature_flag_id = feature_flag_id
self.feature_flag = feature_flag
+ # Set when `get_status` reaches STALE through the configuration route, where the reason it
+ # returns already states the rollout. Callers that narrate the rollout separately read this
+ # rather than re-deriving the route from the flag.
+ self.reason_states_rollout = False
def get_status(self) -> tuple[FeatureFlagStatus, FeatureFlagStatusReason]:
if not self.feature_flag_id and not self.feature_flag:
@@ -236,6 +242,7 @@ class FeatureFlagStatusChecker:
if is_flag_older_than_stale_threshold:
is_fully_rolled_out, rolled_out_reason = self.is_flag_fully_rolled_out(flag)
if is_fully_rolled_out:
+ self.reason_states_rollout = True
return FeatureFlagStatus.STALE, rolled_out_reason
return FeatureFlagStatus.ACTIVE, "Flag has no usage data yet"
@@ -268,7 +275,7 @@ class FeatureFlagStatusChecker:
multivariate = filters.get("multivariate")
has_targeting_conditions = False
- max_rollout_percentage: int | None = None
+ max_rollout_percentage: int | float | None = None
for group in groups:
if group.get("properties"):
has_targeting_conditions = True
diff --git a/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx b/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx
new file mode 100644
index 000000000000..7364592ea58e
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx
@@ -0,0 +1,321 @@
+import { MOCK_DEFAULT_PROJECT } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { NEW_FLAG, featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
+import { FeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
+
+import { useMocks } from '~/mocks/jest'
+import type { Mocks } from '~/mocks/utils'
+import { groupsModel } from '~/models/groupsModel'
+import { initKeaTests } from '~/test/init'
+import { FeatureFlagType } from '~/types'
+
+import { FeatureFlagStaleBanner } from './FeatureFlagStaleBanner'
+
+jest.mock('posthog-js')
+
+const FLAG_ID = 1
+const ACTION_SELECTOR = '[data-attr="feature-flag-stale-banner-view-usage"]'
+
+const HEADING = 'This flag may no longer be needed'
+const GUIDANCE = 'Review usage and code references before disabling or archiving this flag.'
+const STALE_REASON = 'This boolean flag will always evaluate to "true"'
+
+// One condition covering everyone with no property filters, which is what the summary reports for
+// a flag whose only condition omits its rollout percentage.
+const FULL_ROLLOUT = {
+ effectively_full_rollout: false,
+ has_targeting_conditions: false,
+ max_rollout_percentage: 100,
+ is_multivariate: false,
+}
+
+// The backend reached the stale verdict from evaluation data, so `reason` says nothing about the
+// rollout and the banner is free to describe it.
+const STALE_STATUS = {
+ status: 'stale',
+ reason: STALE_REASON,
+ reason_states_rollout: false,
+ rollout: FULL_ROLLOUT,
+}
+
+const ACTIVE_STATUS = {
+ status: 'active',
+ reason: 'Flag was called today',
+ reason_states_rollout: false,
+ rollout: FULL_ROLLOUT,
+}
+
+function buildFlag(overrides: Partial<FeatureFlagType> = {}): FeatureFlagType {
+ return { ...NEW_FLAG, id: FLAG_ID, key: 'test-flag', name: 'test-name', ...overrides }
+}
+
+describe('FeatureFlagStaleBanner', () => {
+ function endpointMocks({
+ flag = buildFlag(),
+ status = STALE_STATUS as unknown,
+ statusCode = 200,
+ dependentFlags = [] as { id: number; key: string; name: string }[],
+ } = {}): Mocks {
+ return {
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${flag.id}/`]: () => [200, flag],
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${flag.id}/status`]: () => [
+ statusCode,
+ status,
+ ],
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${flag.id}/dependent_flags/`]: () => [
+ 200,
+ dependentFlags,
+ ],
+ },
+ }
+ }
+
+ function mountAndRender(id: number | 'new' = FLAG_ID): ReturnType<typeof featureFlagLogic.build> {
+ const logicProps = { id }
+ const logic = featureFlagLogic(logicProps)
+ logic.mount()
+ render(
+ <Provider>
+ <BindLogic logic={featureFlagLogic} props={logicProps}>
+ <FeatureFlagStaleBanner />
+ </BindLogic>
+ </Provider>
+ )
+ return logic
+ }
+
+ async function settle(logic: ReturnType<typeof featureFlagLogic.build>): Promise<void> {
+ await act(async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ })
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ ;(posthog.capture as jest.Mock).mockClear()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('explains a stale flag and offers a way to check its usage', async () => {
+ // The reason already states the rollout, so no rollout line joins it and the reason can be
+ // matched exactly. The rollout lines have their own cases below.
+ useMocks(endpointMocks({ status: { ...STALE_STATUS, reason_states_rollout: true } }))
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(screen.getByText(HEADING)).toBeInTheDocument()
+ expect(screen.getByText(`${STALE_REASON}.`)).toBeInTheDocument()
+ expect(screen.getByText(GUIDANCE)).toBeInTheDocument()
+ expect(document.querySelectorAll(ACTION_SELECTOR).length).toBeGreaterThan(0)
+ })
+
+ // Reading `stale` as "proven safe to delete" is the failure this banner exists to prevent, so a
+ // rollout must never read as a larger or smaller share of users than it is.
+ it.each([
+ {
+ name: 'a flag that covers everyone',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, effectively_full_rollout: true },
+ says: /One release condition rolls out to all users\./,
+ },
+ {
+ // One 100% condition plus one 100% variant satisfies the full-rollout check while a
+ // targeted condition above it serves a different variant, so both flags come back true
+ // and the full-rollout sentence would be false.
+ name: 'a multivariate flag that targets a subset and also covers everyone',
+ flag: buildFlag(),
+ rollout: {
+ effectively_full_rollout: true,
+ has_targeting_conditions: true,
+ max_rollout_percentage: 40,
+ is_multivariate: true,
+ },
+ says: /Its highest rollout across release conditions is 40%\. Some conditions target specific users, so this may not be 40% of all users\./,
+ },
+ {
+ // The shape `max_rollout_percentage_across_multiple_groups` pins in
+ // products/feature_flags/backend/test/test_flag_status.py: a 30% targeted condition next
+ // to a 75% blanket one. The maximum belongs to the blanket condition, so the banner must
+ // not place it inside the targeted one.
+ name: 'a flag whose largest rollout sits outside its targeted condition',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, has_targeting_conditions: true, max_rollout_percentage: 75 },
+ says: /Its highest rollout across release conditions is 75%\. Some conditions target specific users, so this may not be 75% of all users\./,
+ },
+ {
+ // Stale from the rollout alone, so the reason already carries the coverage. Appending a
+ // percentage here reads as a contradiction next to 'will always evaluate to "true"'.
+ name: 'a targeted flag the backend calls stale from its rollout alone',
+ flag: buildFlag(),
+ reasonStatesRollout: true,
+ rollout: { ...FULL_ROLLOUT, effectively_full_rollout: true, has_targeting_conditions: true },
+ says: null,
+ },
+ {
+ name: 'a flag that still serves part of the user base',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, max_rollout_percentage: 40 },
+ says: /Its rollout is 40% of all users\./,
+ },
+ {
+ // A rollout written through the API keeps more precision than the editor allows, and the
+ // raw float reads as a bug. FractionalRolloutWarning on the same page trims it the same way.
+ name: 'a flag on a high-precision fractional rollout',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, max_rollout_percentage: 33.333333333333336 },
+ says: /Its rollout is 33.33% of all users\./,
+ },
+ {
+ // A boolean flag whose only condition omits its percentage evaluates to 100% at runtime,
+ // so max_rollout_percentage is 100 while effectively_full_rollout stays false. It still
+ // reaches everyone, and the banner must say so rather than fall silent.
+ name: 'a boolean flag whose condition omits its rollout percentage',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT },
+ says: /One release condition rolls out to all users\./,
+ },
+ {
+ // is_multivariate reports only that variants exist, not how traffic divides. A single
+ // 100% variant produces the same summary as a real split, so the banner cannot claim a
+ // split; it states the coverage both shapes share.
+ name: 'a multivariate flag that covers everyone',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, is_multivariate: true },
+ says: /One release condition rolls out to all users\./,
+ },
+ {
+ // `effectively_full_rollout` is true for a flag with no release conditions, so a
+ // sentence about a condition would describe something that is not there.
+ name: 'a flag with no release conditions',
+ flag: buildFlag(),
+ rollout: { ...FULL_ROLLOUT, effectively_full_rollout: true, max_rollout_percentage: null },
+ says: null,
+ },
+ {
+ // The backend read the rollout to reach its verdict, so the reason already carries the
+ // fact and the banner must not repeat it.
+ name: 'a flag the backend calls stale from its rollout alone',
+ flag: buildFlag(),
+ reasonStatesRollout: true,
+ rollout: { ...FULL_ROLLOUT, effectively_full_rollout: true },
+ says: null,
+ },
+ ])('describes the rollout of $name', async ({ flag, rollout, says, reasonStatesRollout }) => {
+ useMocks(
+ endpointMocks({
+ flag,
+ status: { ...STALE_STATUS, rollout, reason_states_rollout: Boolean(reasonStatesRollout) },
+ })
+ )
+ const logic = mountAndRender()
+ await settle(logic)
+
+ // The reason and the rollout share one paragraph, so an exact match on the reason alone
+ // proves that no rollout sentence was added to it.
+ expect(screen.getByText(says ?? `${STALE_REASON}.`)).toBeInTheDocument()
+ })
+
+ it('names the aggregation unit for a group-based flag', async () => {
+ // A flag evaluated on organizations serves a share of organizations, not users, and the rest
+ // of the flag page already says so. Seed the group type so the label resolves to a real noun.
+ groupsModel.mount()
+ groupsModel.actions.loadAllGroupTypesSuccess([
+ {
+ group_type: 'organization',
+ group_type_index: 0,
+ name_singular: 'organization',
+ name_plural: 'organizations',
+ },
+ ] as any)
+
+ const flag = buildFlag({ filters: { ...NEW_FLAG.filters, aggregation_group_type_index: 0 } })
+ useMocks(
+ endpointMocks({
+ flag,
+ status: { ...STALE_STATUS, rollout: { ...FULL_ROLLOUT, max_rollout_percentage: 40 } },
+ })
+ )
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(screen.getByText(/Its rollout is 40% of all organizations\./)).toBeInTheDocument()
+ })
+
+ it.each([
+ { name: 'the flag is not stale', flag: buildFlag(), status: ACTIVE_STATUS, statusCode: 200 },
+ { name: 'the flag is deleted', flag: buildFlag({ deleted: true }), status: STALE_STATUS, statusCode: 200 },
+ { name: 'the flag is archived', flag: buildFlag({ archived: true }), status: STALE_STATUS, statusCode: 200 },
+ {
+ name: 'the flag is remote configuration',
+ flag: buildFlag({ is_remote_configuration: true }),
+ status: STALE_STATUS,
+ statusCode: 200,
+ },
+ { name: 'the status request failed', flag: buildFlag(), status: {}, statusCode: 500 },
+ ])('renders nothing when $name', async ({ flag, status, statusCode }) => {
+ useMocks(endpointMocks({ flag, status, statusCode }))
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(screen.queryByText(HEADING)).not.toBeInTheDocument()
+ })
+
+ it('renders nothing for an unsaved flag', async () => {
+ useMocks(endpointMocks())
+ const logic = mountAndRender('new')
+ await settle(logic)
+
+ expect(screen.queryByText(HEADING)).not.toBeInTheDocument()
+ })
+
+ it('does not flash while the status request is in flight', async () => {
+ useMocks(endpointMocks())
+ const logic = mountAndRender()
+
+ expect(screen.queryByText(HEADING)).not.toBeInTheDocument()
+
+ await settle(logic)
+ expect(screen.getByText(HEADING)).toBeInTheDocument()
+ })
+
+ it('warns that an experiment is linked to the flag', async () => {
+ useMocks(endpointMocks({ flag: buildFlag({ experiment_set: [123] }) }))
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(screen.getByText('This flag is linked to an experiment.')).toBeInTheDocument()
+ })
+
+ it('warns that other flags depend on the flag', async () => {
+ useMocks(endpointMocks({ dependentFlags: [{ id: 2, key: 'dependent-flag', name: 'Dependent flag' }] }))
+ const logic = mountAndRender()
+ logic.actions.loadDependentFlags()
+ await settle(logic)
+
+ expect(screen.getByText('Other flags depend on this flag.')).toBeInTheDocument()
+ })
+
+ it('opens the usage tab and reports the click', async () => {
+ useMocks(endpointMocks())
+ const logic = mountAndRender()
+ await settle(logic)
+
+ act(() => {
+ document.querySelector<HTMLElement>(ACTION_SELECTOR)?.click()
+ })
+
+ expect(logic.values.activeTab).toBe(FeatureFlagsTab.USAGE)
+ expect(posthog.capture).toHaveBeenCalledWith('feature flag stale banner view usage clicked')
+ })
+})
diff --git a/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx b/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx
new file mode 100644
index 000000000000..bd732637a6a2
--- /dev/null
+++ b/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx
@@ -0,0 +1,89 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { endWithPunctation } from 'lib/utils/strings'
+import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
+import { FeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
+
+import { formatPercentage } from './FractionalRolloutWarning'
+import type { FeatureFlagRolloutSummaryApi } from './generated/api.schemas'
+
+// Rollout is supporting detail, not a second verdict on staleness. Every line states only what the
+// summary establishes, because the summary reads `filters.groups` and `filters.multivariate` and
+// nothing else. It cannot see evaluation order, early exit, or which variant a condition overrides.
+// Targeting is checked before full rollout: both can be true for a multivariate flag, and the
+// targeted case is the one the reader needs.
+// `targets` is the flag's aggregation unit (people, or a group noun like "organizations"), so a
+// flag evaluated on groups does not report its rollout as a share of users.
+function rolloutSentence(
+ rollout: FeatureFlagRolloutSummaryApi | undefined,
+ reasonStatesRollout: boolean,
+ targets: string
+): string | null {
+ if (!rollout || rollout.max_rollout_percentage === null) {
+ // A flag with no release conditions. `effectively_full_rollout` is true for this shape, so
+ // naming a condition that rolls out to everyone would describe something that is not there.
+ return null
+ }
+ const percentage = formatPercentage(rollout.max_rollout_percentage)
+
+ if (rollout.has_targeting_conditions) {
+ // The two fields are computed independently over the whole condition list.
+ // `has_targeting_conditions` means some condition has property filters, and
+ // `max_rollout_percentage` is the maximum across every condition. They need not describe the
+ // same condition, so the banner reports the number without saying which one produced it.
+ // When the reason already states the rollout, repeating it adds nothing.
+ return reasonStatesRollout
+ ? null
+ : `Its highest rollout across release conditions is ${percentage}. Some conditions target specific ${targets}, so this may not be ${percentage} of all ${targets}.`
+ }
+ if (rollout.max_rollout_percentage < 100) {
+ // `effectively_full_rollout` needs a condition at an explicit 100, so it implies a maximum
+ // of 100 and cannot be true here.
+ return `Its rollout is ${percentage} of all ${targets}.`
+ }
+ // A condition with no property filters covers everyone, at an explicit 100% or with the
+ // percentage omitted, which evaluates to 100% at runtime. The banner stops there rather than
+ // saying everyone gets the same result, which the summary cannot establish: with early exit an
+ // earlier partial condition short-circuits the rest, and another condition can override the
+ // variant. When the reason already states the rollout, repeating it adds nothing.
+ return reasonStatesRollout ? null : `One release condition rolls out to all ${targets}.`
+}
+
+export function FeatureFlagStaleBanner(): JSX.Element | null {
+ const { showStaleFlagBanner, flagStatus, hasExperiment, dependentFlags, aggregationTargetName } =
+ useValues(featureFlagLogic)
+ const { setSelectedTab } = useActions(featureFlagLogic)
+
+ if (!showStaleFlagBanner || !flagStatus) {
+ return null
+ }
+
+ const rollout = rolloutSentence(flagStatus.rollout, flagStatus.reason_states_rollout, aggregationTargetName)
+
+ return (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'View usage',
+ 'data-attr': 'feature-flag-stale-banner-view-usage',
+ onClick: () => {
+ posthog.capture('feature flag stale banner view usage clicked')
+ setSelectedTab(FeatureFlagsTab.USAGE)
+ },
+ }}
+ >
+ <div className="flex flex-col gap-1">
+ <strong>This flag may no longer be needed</strong>
+ <span>
+ {endWithPunctation(flagStatus.reason)}
+ {rollout ? ` ${rollout}` : ''}
+ </span>
+ {hasExperiment && <span>This flag is linked to an experiment.</span>}
+ {dependentFlags.length > 0 && <span>Other flags depend on this flag.</span>}
+ <span>Review usage and code references before disabling or archiving this flag.</span>
+ </div>
+ </LemonBanner>
+ )
+}
diff --git a/products/feature_flags/frontend/FractionalRolloutWarning.tsx b/products/feature_flags/frontend/FractionalRolloutWarning.tsx
index 8f2855aefa62..4706711b6f91 100644
--- a/products/feature_flags/frontend/FractionalRolloutWarning.tsx
+++ b/products/feature_flags/frontend/FractionalRolloutWarning.tsx
@@ -22,7 +22,7 @@ export function fractionalRolloutPercentages(filterGroups: FeatureFlagGroupType[
* precision than the editor's two decimal places, and 33.333333333333336 reads as a bug rather
* than a warning. Significant digits rather than fixed decimals, so a sub-0.01 rollout such as
* 0.00015 doesn't render as 0. */
-function formatPercentage(percentage: number): string {
+export function formatPercentage(percentage: number): string {
return `${Number(percentage.toPrecision(4))}%`
}
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 198b115e0df3..5a62b79ab7ef 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1163,10 +1163,10 @@ export interface DependentFlagApi {
export interface FeatureFlagRolloutSummaryApi {
/** True if the flag is effectively rolled out to everyone, independent of recent evaluation. For boolean flags this means at least one release condition targets 100% with no property filters (or there are no release conditions); for multivariate flags it means a single variant is served to 100% via a fully rolled out release condition. This is the signal for 'fully rolled out' / GA — unlike `status`, which only reflects recent evaluation. */
effectively_full_rollout: boolean
- /** True if any release condition has property filters, i.e. the flag is conditionally targeted rather than a blanket rollout. When true, `max_rollout_percentage` is a percentage within the targeted segment, not of the whole user base. */
+ /** True if any release condition has property filters, i.e. the flag is conditionally targeted rather than a blanket rollout. This says nothing about which condition produced `max_rollout_percentage`: the two fields are computed independently over the whole condition list. */
has_targeting_conditions: boolean
/**
- * Highest rollout percentage (0-100) across the flag's release conditions, treating a missing percentage as 100. Null when the flag has no release conditions. Interpret together with `has_targeting_conditions`.
+ * Highest rollout percentage (0-100) across the flag's release conditions, treating a missing percentage as 100. Null when the flag has no release conditions. The maximum can come from an untargeted condition even when `has_targeting_conditions` is true, so it cannot be attributed to a targeted condition or read as a share of a targeted segment.
* @nullable
*/
max_rollout_percentage: number | null
@@ -1179,6 +1179,8 @@ export interface FeatureFlagStatusResponseApi {
status: string
/** Human-readable explanation of the status */
reason: string
+ /** True when `reason` already describes the flag's rollout, which happens when the status was reached from the configuration rather than from evaluation data. A caller that narrates the rollout separately should stay quiet rather than repeat it. */
+ reason_states_rollout: boolean
/** Summary of the flag's rollout configuration, for determining whether it is fully rolled out. */
rollout: FeatureFlagRolloutSummaryApi
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 115ec640fe5b..33b421f593b5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39266,10 +39266,10 @@ export namespace Schemas {
export interface FeatureFlagRolloutSummary {
/** True if the flag is effectively rolled out to everyone, independent of recent evaluation. For boolean flags this means at least one release condition targets 100% with no property filters (or there are no release conditions); for multivariate flags it means a single variant is served to 100% via a fully rolled out release condition. This is the signal for 'fully rolled out' / GA — unlike `status`, which only reflects recent evaluation. */
effectively_full_rollout: boolean;
- /** True if any release condition has property filters, i.e. the flag is conditionally targeted rather than a blanket rollout. When true, `max_rollout_percentage` is a percentage within the targeted segment, not of the whole user base. */
+ /** True if any release condition has property filters, i.e. the flag is conditionally targeted rather than a blanket rollout. This says nothing about which condition produced `max_rollout_percentage`: the two fields are computed independently over the whole condition list. */
has_targeting_conditions: boolean;
/**
- * Highest rollout percentage (0-100) across the flag's release conditions, treating a missing percentage as 100. Null when the flag has no release conditions. Interpret together with `has_targeting_conditions`.
+ * Highest rollout percentage (0-100) across the flag's release conditions, treating a missing percentage as 100. Null when the flag has no release conditions. The maximum can come from an untargeted condition even when `has_targeting_conditions` is true, so it cannot be attributed to a targeted condition or read as a share of a targeted segment.
* @nullable
*/
max_rollout_percentage: number | null;
@@ -39282,6 +39282,8 @@ export namespace Schemas {
status: string;
/** Human-readable explanation of the status */
reason: string;
+ /** True when `reason` already describes the flag's rollout, which happens when the status was reached from the configuration rather than from evaluation data. A caller that narrates the rollout separately should stay quiet rather than repeat it. */
+ reason_states_rollout: boolean;
/** Summary of the flag's rollout configuration, for determining whether it is fully rolled out. */
rollout: FeatureFlagRolloutSummary;
}