:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): distinguish blast-radius errors and save-time 403s (#68066)
posthog[bot]cde39141c2b0
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex a46a593f67e7..eeedbe16c997 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -8,6 +8,7 @@ import { waitForPlugin } from 'kea-waitfor'import { windowValuesPlugin } from 'kea-window-values'import posthog from 'posthog-js'+import { isAccessDeniedError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import {addProjectIdIfMissing,@@ -37,6 +38,14 @@ const ERROR_FILTER_ALLOW_LIST = ['saveEarlyAccessFeature', // Field-level errors handled in earlyAccessFeatureLogic]+/*+Write actions that show their own friendly message for access-denied 403s+(code `permission_denied`), so the generic toast would be a duplicate.+Unlike ERROR_FILTER_ALLOW_LIST, this only suppresses access-denied errors;+other failures on these actions still toast.+*/+const ACCESS_DENIED_SELF_HANDLED = new Set(['saveFeatureFlag'])+/*Transient gateway/proxy errors. These are infrastructure-level failures (the gateway can'treach the backend), not application bugs, so we still toast the user a retryable failure but@@ -114,11 +123,19 @@ export function initKea({// `before_send` filter in `selfReadOnlyModeLogic`.// Toast if it's a fetch error or a specific API update errorconst isLoadAction = typeof actionKey === 'string' && /^(load|get|fetch)[A-Z]/.test(actionKey)+ // Access-denied 403s (code `permission_denied`) are suppressed only where the+ // owning UI surfaces them itself: load actions (AccessDenied scene gates) and the+ // self-handled write actions above. Other writes keep the generic toast, since+ // most write flows have no failure handling of their own. Read-only mode uses+ // distinct codes (`read_only_blocked`, `impersonation_read_only`) and still toasts.+ const isAccessDenied =+ isAccessDeniedError(error) && (isLoadAction || ACCESS_DENIED_SELF_HANDLED.has(String(actionKey)))if (!ERROR_FILTER_ALLOW_LIST.includes(actionKey) &&error?.status !== undefined &&![200, 201, 204, 401, 409].includes(error.status) && // 401 is handled by api.ts and the userLogic, 409 is handled by approval workflow- !(isLoadAction && error.status === 403) // 403 access denied is handled by sceneLogic gates+ !(isLoadAction && error.status === 403) && // 403 access denied is handled by sceneLogic gates+ !isAccessDenied) {let errorMessage = error.detail || error.statusTextconst isTwoFactorError =diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex c2b2ce51640e..ac41fff41377 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -1,6 +1,11 @@import { dayjs } from 'lib/dayjs'import { humanFriendlyDuration } from 'lib/utils/durations'+/** A 403 with DRF's `permission_denied` code — the user lacks access to the resource itself. */+export function isAccessDeniedError(error: { status?: number; code?: string | null }): boolean {+ return error.status === 403 && error.code === 'permission_denied'+}+export class ApiError extends Error {/** Django REST Framework `detail` - used in downstream error handling. */detail: string | nulldiff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsxindex 673d56b6b38a..ce050d411085 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx@@ -15,7 +15,7 @@ import { INSTANTLY_AVAILABLE_PROPERTIES } from 'lib/constants'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { GroupsAccessStatus, groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'import { GroupsIntroductionOption } from 'lib/introductions/GroupsIntroductionOption'-import { IconArrowDown, IconArrowUp, IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'+import { IconArrowDown, IconArrowUp, IconErrorOutline, IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'@@ -131,6 +131,7 @@ export function FeatureFlagReleaseConditions({propertySelectErrors,affectedCounts,totalCounts,+ blastRadiusErrors,filtersTaxonomicOptions,aggregationTargetName,properties,@@ -146,6 +147,7 @@ export function FeatureFlagReleaseConditions({addConditionSet,moveConditionSetUp,moveConditionSetDown,+ calculateBlastRadiusForCondition,} = useActions(releaseConditionsLogic)const { showGroupsOptions, groupTypes, aggregationLabel } = useValues(groupsModel)@@ -444,16 +446,39 @@ export function FeatureFlagReleaseConditions({of <b>{aggregationTargetName(group.aggregation_group_type_index)}</b> in this set.{(() => {const targetIndex = group.aggregation_group_type_index+ const resolvedGroupTypeIndex = resolveAggregationGroupTypeIndex(+ targetIndex,+ filters.aggregation_group_type_index+ )const pluralName = aggregationTargetName(targetIndex)- const singularName = aggregationLabel(- resolveAggregationGroupTypeIndex(- targetIndex,- filters.aggregation_group_type_index- ),- true- ).singular- const affected = group.sort_key ? affectedCounts[group.sort_key] : undefined- const total = group.sort_key ? totalCounts[group.sort_key] : undefined+ const singularName = aggregationLabel(resolvedGroupTypeIndex, true).singular+ const sortKey = group.sort_key+ const affected = sortKey ? affectedCounts[sortKey] : undefined+ const total = sortKey ? totalCounts[sortKey] : undefined+ if (sortKey && blastRadiusErrors[sortKey]) {+ return (+ <div+ role="status"+ className="basis-full flex items-center gap-2 mt-1 text-secondary"+ >+ <IconErrorOutline className="text-danger text-base shrink-0" />+ <span>Couldn't estimate how many {pluralName} match.</span>+ <LemonButton+ type="secondary"+ size="xsmall"+ onClick={() =>+ calculateBlastRadiusForCondition(+ sortKey,+ group.properties,+ resolvedGroupTypeIndex+ )+ }+ >+ Retry+ </LemonButton>+ </div>+ )+ }if (affected === undefined || affected < 0 || total === undefined) {return (<div className="basis-full flex items-center mt-1">diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsxindex f6dcb91a2a7b..06c7c05f10b6 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx@@ -48,7 +48,7 @@ import { isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utiimport { TaxonomicFilterGroupType, TaxonomicFilterProps } from 'lib/components/TaxonomicFilter/types'import { FEATURE_FLAGS } from 'lib/constants'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'+import { IconArrowDown, IconArrowUp, IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'@@ -330,6 +330,12 @@ interface ConditionProps {totalGroups: numberaffectedCounts: Record<string, number | undefined>totalCounts: Record<string, number | undefined>+ blastRadiusErrors: Record<string, boolean>+ calculateBlastRadiusForCondition: (+ sortKey: string,+ properties: AnyPropertyFilter[] | undefined,+ groupTypeIndex: number | null+ ) => voidaggregationTargetName: (conditionGroupTypeIndex?: number | null) => stringgetDistinctIdName: (distinctId: string) => stringtaxonomicGroupTypesForCondition: (conditionGroupTypeIndex: number | null | undefined) => TaxonomicFilterGroupType[]@@ -400,6 +406,8 @@ const ConditionContent = ({totalGroups,affectedCounts,totalCounts,+ blastRadiusErrors,+ calculateBlastRadiusForCondition,aggregationTargetName,getDistinctIdName,taxonomicGroupTypesForCondition,@@ -658,7 +666,32 @@ const ConditionContent = ({data-attr="rollout-percentage"/></div>- {group.sort_key && affectedCounts[group.sort_key] !== undefined ? (+ {group.sort_key && blastRadiusErrors[group.sort_key] ? (+ <div+ role="status"+ className="text-xs text-muted mt-2 flex items-center gap-2"+ >+ <IconErrorOutline className="text-danger text-sm shrink-0" />+ <span>Couldn't estimate how many {resolvedTargetName} match.</span>+ <LemonButton+ type="secondary"+ size="xsmall"+ onClick={() =>+ group.sort_key &&+ calculateBlastRadiusForCondition(+ group.sort_key,+ group.properties,+ resolveAggregationGroupTypeIndex(+ group.aggregation_group_type_index,+ releaseFilters.aggregation_group_type_index+ )+ )+ }+ >+ Retry+ </LemonButton>+ </div>+ ) : group.sort_key && affectedCounts[group.sort_key] !== undefined ? (<div className="text-xs text-muted mt-2">{(() => {const affected = group.sort_key@@ -833,6 +866,7 @@ export function FeatureFlagReleaseConditionsCollapsible({filtersTaxonomicOptions,affectedCounts,totalCounts,+ blastRadiusErrors,aggregationTargetName,getDistinctIdName,taxonomicGroupTypesForCondition,@@ -865,6 +899,7 @@ export function FeatureFlagReleaseConditionsCollapsible({setIsAnyItemDragging,setDraggedGroup,setEarlyExit,+ calculateBlastRadiusForCondition,} = useActions(releaseConditionsLogic)const handleAddConditionSet = (): void => {@@ -1230,6 +1265,8 @@ export function FeatureFlagReleaseConditionsCollapsible({totalGroups={filterGroups.length}affectedCounts={affectedCounts}totalCounts={totalCounts}+ blastRadiusErrors={blastRadiusErrors}+ calculateBlastRadiusForCondition={calculateBlastRadiusForCondition}aggregationTargetName={aggregationTargetName}getDistinctIdName={getDistinctIdName}taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}@@ -1306,6 +1343,8 @@ export function FeatureFlagReleaseConditionsCollapsible({totalGroups={filterGroups.length}affectedCounts={affectedCounts}totalCounts={totalCounts}+ blastRadiusErrors={blastRadiusErrors}+ calculateBlastRadiusForCondition={calculateBlastRadiusForCondition}aggregationTargetName={aggregationTargetName}getDistinctIdName={getDistinctIdName}taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}@@ -1357,6 +1396,8 @@ export function FeatureFlagReleaseConditionsCollapsible({totalGroups={filterGroups.length}affectedCounts={affectedCounts}totalCounts={totalCounts}+ blastRadiusErrors={blastRadiusErrors}+ calculateBlastRadiusForCondition={calculateBlastRadiusForCondition}aggregationTargetName={aggregationTargetName}getDistinctIdName={getDistinctIdName}taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}@@ -1390,6 +1431,8 @@ export function FeatureFlagReleaseConditionsCollapsible({totalGroups={filterGroups.length}affectedCounts={affectedCounts}totalCounts={totalCounts}+ blastRadiusErrors={blastRadiusErrors}+ calculateBlastRadiusForCondition={calculateBlastRadiusForCondition}aggregationTargetName={aggregationTargetName}getDistinctIdName={getDistinctIdName}taxonomicGroupTypesForCondition={taxonomicGroupTypesForCondition}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 0bf8ec583a29..8735d7f2a989 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -258,6 +258,51 @@ describe('featureFlagLogic', () => {})})+ describe('saveFeatureFlag error handling', () => {+ it('shows the friendly permission toast on a save-time 403', async () => {+ useMocks({+ patch: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 403,+ { type: 'authentication_error', code: 'permission_denied', detail: 'Nope' },+ ],+ },+ })+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ try {+ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ }).toDispatchActions(['saveFeatureFlagFailure'])++ expect(toastSpy).toHaveBeenCalledWith('Nope')+ } finally {+ toastSpy.mockRestore()+ }+ })++ it('does not show the permission toast for other save errors', async () => {+ useMocks({+ patch: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 500,+ { type: 'server_error', detail: 'boom' },+ ],+ },+ })+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ try {+ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ }).toDispatchActions(['saveFeatureFlagFailure'])++ // The permission-specific branch must not fire; the generic loaders toast owns this case.+ expect(toastSpy).not.toHaveBeenCalledWith('Nope')+ } finally {+ toastSpy.mockRestore()+ }+ })+ })+describe('setMultivariateEnabled functionality', () => {it('adds default variants when enabling multivariate', async () => {await expectLogic(logic).toMatchValues({diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 1f338d50298e..60a70d0d9b22 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -20,6 +20,7 @@ import { CombinedLocation } from 'kea-router/lib/utils'import { createElement } from 'react'import api, { PaginatedResponse } from 'lib/api'+import { isAccessDeniedError } from 'lib/api-error'import { handleApprovalRequired } from 'lib/approvals/utils'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'@@ -1309,7 +1310,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)} catch (e: any) {- if (e.status === 403 && e.code === 'permission_denied') {+ if (isAccessDeniedError(e)) {actions.setAccessDeniedToFeatureFlag()} else {actions.setFeatureFlagMissing()@@ -1449,6 +1450,14 @@ export const featureFlagLogic = kea<featureFlagLogicType>([} catch (error: any) {if (error.code === 'behavioral_cohort_found' || error.code === 'cohort_does_not_exist') {eventUsageLogic.actions.reportFailedToCreateFeatureFlagWithCohort(error.code, error.detail)+ } else if (isAccessDeniedError(error)) {+ // Mirror the load path's access-denied handling instead of the generic+ // "Save feature flag failed: ..." toast. The global loaders handler+ // suppresses its toast for permission_denied, so this is the only message.+ lemonToast.error(+ error.detail ||+ "You don't have permission to edit this feature flag. Contact your administrator to request editing rights."+ )}throw error}diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.tsindex 22e4ba776225..5679d8fea4b2 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts@@ -98,6 +98,64 @@ describe('the feature flag release conditions logic', () => {})})+ it('flags a distinct error state when the blast radius call fails', async () => {+ const createSpy = jest.spyOn(api, 'create').mockRejectedValue(new Error('boom'))++ try {+ await expectLogic(logic, () => {+ logic.actions.calculateBlastRadiusForCondition(+ 'X',+ [+ {+ key: 'aloha',+ value: 'aloha',+ type: PropertyFilterType.Person,+ operator: PropertyOperator.Exact,+ },+ ],+ null+ )+ }).toFinishAllListeners()++ // The error is surfaced distinctly rather than masked as -1, which the render+ // path can't tell apart from the still-loading (undefined) state.+ expect(logic.values.blastRadiusErrors.X).toBe(true)+ expect(logic.values.affectedCounts.X).toBeUndefined()+ expect(logic.values.totalCounts.X).toBeUndefined()+ } finally {+ createSpy.mockRestore()+ }+ })++ it('clears the error state once a recalculation succeeds', async () => {+ logic.actions.setBlastRadiusError('X')+ expect(logic.values.blastRadiusErrors.X).toBe(true)++ const createSpy = jest.spyOn(api, 'create').mockResolvedValue({ affected: 10, total: 100 })+ try {+ await expectLogic(logic, () => {+ logic.actions.calculateBlastRadiusForCondition(+ 'X',+ [+ {+ key: 'aloha',+ value: 'aloha',+ type: PropertyFilterType.Person,+ operator: PropertyOperator.Exact,+ },+ ],+ null+ )+ }).toFinishAllListeners()++ expect(logic.values.blastRadiusErrors.X).toBeUndefined()+ expect(logic.values.affectedCounts.X).toBe(10)+ expect(logic.values.totalCounts.X).toBe(100)+ } finally {+ createSpy.mockRestore()+ }+ })+it('loads when editing a flag with multiple conditions', async () => {// clear existing logiclogic?.unmount()@@ -235,7 +293,8 @@ describe('the feature flag release conditions logic', () => {])}).toDispatchActions(['setAffectedCount', 'setTotalCount'])- // Update with complete property — triggers API call after debounce+ // Update with complete property — triggers API call after debounce.+ // Three pairs: the immediate reset, calculateBlastRadiusForCondition's reset, the API result.await expectLogic(logic, () => {logic.actions.updateConditionSet(0, 20, [{@@ -246,6 +305,7 @@ describe('the feature flag release conditions logic', () => {},])})+ .toDispatchActions(['setAffectedCount', 'setTotalCount']).toDispatchActions(['setAffectedCount', 'setTotalCount']).toDispatchActions(['setAffectedCount', 'setTotalCount']).toMatchValues({@@ -272,6 +332,7 @@ describe('the feature flag release conditions logic', () => {},])})+ .toDispatchActions(['setAffectedCount', 'setTotalCount']).toDispatchActions(['setAffectedCount', 'setTotalCount']).toDispatchActions(['setAffectedCount', 'setTotalCount']).toMatchValues({diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.tsindex 5d4ee80891cb..90e3568af786 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts@@ -144,6 +144,7 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseConditionsortKey,count,}),+ setBlastRadiusError: (sortKey: string) => ({ sortKey }),calculateBlastRadius: true,calculateBlastRadiusForCondition: (sortKey: string,@@ -373,6 +374,26 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition}),},],+ // Tracks conditions whose blast-radius estimate failed, so the UI can distinguish a+ // genuine error from the still-loading (undefined) state instead of spinning forever.+ blastRadiusErrors: [+ {} as Record<string, boolean>,+ {+ setBlastRadiusError: (state, { sortKey }) => ({+ ...state,+ [sortKey]: true,+ }),+ // Cleared when setAffectedCount fires (reset or result); the two counts are always+ // written together, so listening to setAffectedCount alone is sufficient.+ setAffectedCount: (state, { sortKey }) => {+ if (!state[sortKey]) {+ return state+ }+ const { [sortKey]: _, ...rest } = state+ return rest+ },+ },+ ],flagKeyCache: [{} as Record<string, string>,{@@ -481,16 +502,7 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseConditiongroup.aggregation_group_type_index,values.filters?.aggregation_group_type_index)- const response: UserBlastRadiusType = await api.create(- `api/projects/${values.currentProjectId}/feature_flags/user_blast_radius`,- {- condition: { properties: newProperties },- group_type_index: groupTypeIndex,- }- )-- actions.setAffectedCount(sortKey, response.affected)- actions.setTotalCount(sortKey, response.total)+ actions.calculateBlastRadiusForCondition(sortKey, newProperties, groupTypeIndex)},setConditionAggregation: ({ index }) => {const group = values.filters.groups[index]@@ -546,29 +558,31 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseCondition}},calculateBlastRadiusForCondition: async ({ sortKey, properties, groupTypeIndex }) => {- actions.setAffectedCount(sortKey, undefined)- actions.setTotalCount(sortKey, undefined)-- let response: UserBlastRadiusTypeif (!properties || properties.some(isEmptyProperty)) {// don't compute for incomplete conditions- response = { affected: -1, total: -1 }- } else {- try {- response = await api.create(- `api/projects/${values.currentProjectId}/feature_flags/user_blast_radius`,- {- condition: { properties },- group_type_index: groupTypeIndex,- }- )- } catch {- response = { affected: -1, total: -1 }- }+ actions.setAffectedCount(sortKey, -1)+ actions.setTotalCount(sortKey, -1)+ return}- actions.setAffectedCount(sortKey, response.affected)- actions.setTotalCount(sortKey, response.total)+ actions.setAffectedCount(sortKey, undefined)+ actions.setTotalCount(sortKey, undefined)++ try {+ const response: UserBlastRadiusType = await api.create(+ `api/projects/${values.currentProjectId}/feature_flags/user_blast_radius`,+ {+ condition: { properties },+ group_type_index: groupTypeIndex,+ }+ )+ actions.setAffectedCount(sortKey, response.affected)+ actions.setTotalCount(sortKey, response.total)+ } catch {+ // Surface the failure to the UI rather than masking it as -1, which the+ // render path can't tell apart from "still loading".+ actions.setBlastRadiusError(sortKey)+ }},calculateBlastRadius: () => {values.filters.groups.forEach((condition: FeatureFlagGroupTypeWithSortKey) => {