: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(metrics): hold the preview gate while alpha enrollment reaches the server (#98422)
Daniel Visca70cc34bd831d
diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsxindex 9b74fbff0f2a..d0ca20578a1c 100644--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useActions, useMountedLogic, useValues } from 'kea'@@ -66,7 +66,12 @@ const mockedUseActions = useActions as jest.Mockconst mockedUseMountedLogic = useMountedLogic as jest.Mockconst mockLoadEarlyAccessFeatures = jest.fn()-const mockUpdateEarlyAccessFeatureEnrollment = jest.fn()+// Mirrors posthog-js: enrollment takes effect locally the moment it is stored, so the+// enriched feature flips to enabled and the scene gate re-renders on the same render pass.+const mockUpdateEarlyAccessFeatureEnrollment = jest.fn((flagKey: string, enabled: boolean) => {+ enrolledFlags = enabled ? [...enrolledFlags, flagKey] : enrolledFlags.filter((key) => key !== flagKey)+})+let enrolledFlags: string[] = []const mockSubmitConceptSurvey = jest.fn()const mockAddProductIntentForCrossSell = jest.fn()const mockOpenSupportForm = jest.fn()@@ -100,6 +105,34 @@ function isSupportLogicRef(logic: unknown): boolean {return logic === supportLogic}+// productSetupStatusLogic is keyed, so the gate calls it as a factory; the mock returns a+// stable sentinel and we identity-compare against what the factory hands the component.+function isProductSetupStatusLogicRef(logic: unknown): boolean {+ return (logic as { __mock?: string } | null | undefined)?.__mock === 'productSetupStatusLogic'+}++jest.mock('lib/components/ProductEmptyState/productSetupStatusLogic', () => {+ const sentinel = { __mock: 'productSetupStatusLogic' }+ return { productSetupStatusLogic: () => sentinel }+})++// The gate's settling state lives in a kea logic (repo rule: no business logic in hooks).+// Mock the module so tests steer it through this sentinel: the factory returns an object whose+// identity marks it, and `mockSettling`/`mockStartSettling` stand in for its value and action.+jest.mock('./featurePreviewGateSettlingLogic', () => ({+ featurePreviewGateSettlingLogic: () => ({ __mock: 'featurePreviewGateSettlingLogic' }),+}))++let mockSettling = false+const mockStartSettling = jest.fn(() => {+ mockSettling = true+})+const mockMarkServerCaughtUp = jest.fn()++function isSettlingLogicRef(logic: unknown): boolean {+ return (logic as { __mock?: string } | null | undefined)?.__mock === 'featurePreviewGateSettlingLogic'+}+function setupMocks({earlyAccessFeatures = [],waitlistSurveysEnabled = false,@@ -108,6 +141,7 @@ function setupMocks({featureFlags = {},cloud = true,isDebug = false,+ setupStatus = 'unknown',}: {earlyAccessFeatures?: Array<{flagKey: string@@ -121,12 +155,19 @@ function setupMocks({featureFlags?: Record<string, boolean | string>cloud?: booleanisDebug?: boolean+ setupStatus?: string} = {}): void {mockedUseMountedLogic.mockReturnValue({})mockedUseValues.mockImplementation((logic: unknown) => {if (isFeaturePreviewsLogicRef(logic)) {- return { earlyAccessFeatures, waitlistSurveysEnabled, conceptSurveySubmissions }+ return {+ earlyAccessFeatures: earlyAccessFeatures.map((feature) =>+ enrolledFlags.includes(feature.flagKey) ? { ...feature, enabled: true } : feature+ ),+ waitlistSurveysEnabled,+ conceptSurveySubmissions,+ }}if (isSceneLogicRef(logic)) {return { activeSceneId }@@ -137,6 +178,12 @@ function setupMocks({if (isPreflightLogicRef(logic)) {return { preflight: { cloud, is_debug: isDebug } }}+ if (isProductSetupStatusLogicRef(logic)) {+ return { status: setupStatus }+ }+ if (isSettlingLogicRef(logic)) {+ return { settling: mockSettling }+ }return {}})@@ -152,6 +199,9 @@ function setupMocks({if (isSupportLogicRef(logic)) {return { openSupportForm: mockOpenSupportForm }}+ if (isSettlingLogicRef(logic)) {+ return { startSettling: mockStartSettling, markServerCaughtUp: mockMarkServerCaughtUp }+ }return {}})}@@ -159,6 +209,8 @@ function setupMocks({describe('FeaturePreviewSceneGate', () => {beforeEach(() => {jest.clearAllMocks()+ enrolledFlags = []+ mockSettling = falsesetupMocks()})@@ -176,6 +228,74 @@ describe('FeaturePreviewSceneGate', () => {expect(screen.queryByTestId('product-introduction')).not.toBeInTheDocument()})+ test('opting in starts the settling window', () => {+ setupMocks({ earlyAccessFeatures: [{ flagKey: BASE_CONFIG.flag, enabled: false, stage: 'alpha' }] })++ render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)+ fireEvent.click(screen.getByRole('switch'))++ expect(mockStartSettling).toHaveBeenCalledTimes(1)+ })++ test('while settling with the flag on, holds on an enabling state instead of mounting a scene whose API still 403s', () => {+ // The browser evaluates the flag on the moment enrollment is stored locally, while the+ // API keeps denying until the enrollment person property is ingested. Mounting the+ // scene in that window is what showed "Detect status failed" until a reload.+ mockSettling = true+ setupMocks({ featureFlags: { [BASE_CONFIG.flag]: true } })++ render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)++ expect(screen.getByTestId('feature-preview-enabling')).toBeInTheDocument()+ expect(screen.getByText(/turning the feature preview on/i)).toBeInTheDocument()+ expect(screen.queryByTestId('scene-content-rendered')).not.toBeInTheDocument()+ expect(screen.queryByTestId('product-introduction')).not.toBeInTheDocument()+ })++ test('a rejected enrollment (impersonated session) never starts settling', () => {+ // featurePreviewsLogic refuses enrollment for impersonated sessions, so the flag never+ // flips and there is nothing to wait on - the gate must stay exactly as it was.+ ;(window as unknown as { IMPERSONATED_SESSION?: boolean }).IMPERSONATED_SESSION = true+ setupMocks({ earlyAccessFeatures: [{ flagKey: BASE_CONFIG.flag, enabled: false, stage: 'alpha' }] })++ render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)+ fireEvent.click(screen.getByRole('switch'))++ expect(mockStartSettling).not.toHaveBeenCalled()+ expect(screen.queryByTestId('feature-preview-enabling')).not.toBeInTheDocument()+ expect(screen.getByTestId('product-introduction')).toBeInTheDocument()+ delete (window as unknown as { IMPERSONATED_SESSION?: boolean }).IMPERSONATED_SESSION+ })++ test('a successful server detection ends the enabling state early', () => {+ // The window exists because the API lags the browser. Once the product's own setup+ // detection gets a real answer from the server, the wait has done its job.+ mockSettling = true+ setupMocks({ featureFlags: { [BASE_CONFIG.flag]: true }, setupStatus: 'has-data' })++ render(+ <FeaturePreviewSceneGate config={{ ...BASE_CONFIG, productIntent: ProductKey.METRICS }}>+ {CHILDREN}+ </FeaturePreviewSceneGate>+ )++ expect(mockMarkServerCaughtUp).toHaveBeenCalled()+ })++ test('no detection answer yet keeps the wait running', () => {+ mockSettling = true+ setupMocks({ featureFlags: { [BASE_CONFIG.flag]: true }, setupStatus: 'loading' })++ render(+ <FeaturePreviewSceneGate config={{ ...BASE_CONFIG, productIntent: ProductKey.METRICS }}>+ {CHILDREN}+ </FeaturePreviewSceneGate>+ )++ expect(mockMarkServerCaughtUp).not.toHaveBeenCalled()+ expect(screen.getByTestId('feature-preview-enabling')).toBeInTheDocument()+ })+test('renders the gate when flag is off', () => {setupMocks({ featureFlags: { [BASE_CONFIG.flag]: false } })diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsxindex 9853b20b0c1b..1d0aa9a96f30 100644--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx@@ -5,8 +5,10 @@ import { IconCheck } from '@posthog/icons'import { LemonButton, LemonInput, LemonSwitch } from '@posthog/lemon-ui'import { EnrichedEarlyAccessFeature, featurePreviewsLogic } from 'lib/components/FeaturePreviews/featurePreviewsLogic'+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { supportLogic } from 'lib/components/Support/supportLogic'+import { Spinner } from 'lib/lemon-ui/Spinner'import {FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON,areClientFeatureFlagsHonored,@@ -20,6 +22,7 @@ import { urls } from 'scenes/urls'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { FeaturePreviewGateConfig } from '~/types'+import { featurePreviewGateSettlingLogic } from './featurePreviewGateSettlingLogic'import { SceneContent } from './SceneContent'import { SceneTitleSection } from './SceneTitleSection'@@ -31,16 +34,60 @@ export function FeaturePreviewSceneGate({children: React.ReactNode}): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)+ const settlingLogic = featurePreviewGateSettlingLogic({ flag: config.flag })+ const { settling } = useValues(settlingLogic)+ const { markServerCaughtUp } = useActions(settlingLogic)+const isEnabled = featureFlags[config.flag as keyof typeof featureFlags]- if (isEnabled) {+ if (isEnabled && !settling) {return <>{children}</>}- return <FeaturePreviewGateContent config={config} />+ // Only hold the enabling state once the flag is actually on locally; before that the gate+ // has nothing to wait for and should keep showing the toggle.+ const justEnrolled = settling && !!isEnabled+ return (+ <>+ {config.productIntent && settling && (+ <SetupDetectionEarlyStop productKey={config.productIntent} onServerCaughtUp={markServerCaughtUp} />+ )}+ <FeaturePreviewGateContent config={config} justEnrolled={justEnrolled} />+ </>+ )}-function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConfig }): JSX.Element {+/**+ * Watches the product's own setup detection while the gate settles: once detection has any real+ * answer from the server, the enrollment window has closed and the wait has done its job. Lives+ * in its own component so `productSetupStatusLogic` is only mounted with a real productKey -+ * the keyed logic throws on a missing key, and gates without a product intent simply wait out+ * the timer.+ */+function SetupDetectionEarlyStop({+ productKey,+ onServerCaughtUp,+}: {+ productKey: ProductKey+ onServerCaughtUp: () => void+}): null {+ const { status: setupStatus } = useValues(productSetupStatusLogic({ productKey }))+ useEffect(() => {+ if (setupStatus !== 'loading' && setupStatus !== 'unknown') {+ onServerCaughtUp()+ }+ }, [setupStatus, onServerCaughtUp])+ return null+}++function FeaturePreviewGateContent({+ config,+ justEnrolled,+}: {+ config: FeaturePreviewGateConfig+ justEnrolled: boolean+}): JSX.Element {const { earlyAccessFeatures } = useValues(featurePreviewsLogic)const { loadEarlyAccessFeatures, updateEarlyAccessFeatureEnrollment } = useActions(featurePreviewsLogic)+ const { startSettling } = useActions(featurePreviewGateSettlingLogic({ flag: config.flag }))const { activeSceneId } = useValues(sceneLogic)const { preflight } = useValues(preflightLogic)const { openSupportForm } = useActions(supportLogic)@@ -54,6 +101,30 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConficonst sceneConfig = sceneIdForHeader ? sceneConfigurations[sceneIdForHeader] : undefinedconst flagsHonored = areClientFeatureFlagsHonored(preflight)+ // The user just opted in: the flag is on locally but the API still 403s until ingestion+ // catches up. Hold here instead of mounting a scene whose every request fails.+ if (justEnrolled) {+ return (+ <SceneContent>+ {sceneConfig?.name && (+ <SceneTitleSection+ name={sceneConfig.name}+ description={sceneConfig.description}+ resourceType={{ type: sceneConfig.iconType || 'default' }}+ />+ )}+ <div+ className="flex items-center gap-2 text-secondary"+ data-attr="feature-preview-enabling"+ role="status"+ >+ <Spinner className="text-lg" />+ <span>Turning the feature preview on. This takes a few seconds.</span>+ </div>+ </SceneContent>+ )+ }+// Concept ("Coming Soon") features never enable their flag, so the enrollment toggle is a// dead end there. When the feature carries a waitlist survey, collect an email instead.// Alpha and beta enrollments do enable their flag, so those stages keep the self-serve@@ -103,9 +174,14 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConfi<LemonSwitchchecked={feature.enabled}disabledReason={!flagsHonored && FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON}- onChange={(checked) =>+ onChange={(checked) => {updateEarlyAccessFeatureEnrollment(feature.flagKey, checked, feature.stage)- }+ // featurePreviewsLogic refuses enrollment for impersonated+ // sessions, so there is nothing to wait on in that case.+ if (checked && !window.IMPERSONATED_SESSION) {+ startSettling()+ }+ }}id="feature-preview-gate-switch"/><span className="font-semibold">Enable feature preview</span>diff --git a/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.test.ts b/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.test.tsnew file mode 100644index 000000000000..60dad8024c73--- /dev/null+++ b/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.test.ts@@ -0,0 +1,52 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { featurePreviewGateSettlingLogic } from './featurePreviewGateSettlingLogic'++describe('featurePreviewGateSettlingLogic', () => {+ beforeEach(() => {+ initKeaTests()+ jest.useFakeTimers()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('settles on startSettling and stops when the server catches up', async () => {+ const logic = featurePreviewGateSettlingLogic({ flag: 'flag-a' })+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.startSettling()+ }).toMatchValues({ settling: true })++ await expectLogic(logic, () => {+ logic.actions.markServerCaughtUp()+ }).toMatchValues({ settling: false })++ // The early stop disposes the timeout, so no late timer can flip the state again.+ jest.runAllTimers()+ expect(logic.values.settling).toBe(false)+ })++ it('stops settling on its own past the timeout, so a slow pipeline cannot lock the gate', async () => {+ const logic = featurePreviewGateSettlingLogic({ flag: 'flag-b' })+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.startSettling()+ }).toMatchValues({ settling: true })++ await expectLogic(logic, () => {+ jest.advanceTimersByTime(15000)+ }).toMatchValues({ settling: false })+ })++ it('does not settle while nothing was started', () => {+ const logic = featurePreviewGateSettlingLogic({ flag: 'flag-c' })+ logic.mount()+ expect(logic.values.settling).toBe(false)+ })+})diff --git a/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.ts b/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.tsnew file mode 100644index 000000000000..2c3f5282e402--- /dev/null+++ b/frontend/src/layout/scenes/components/featurePreviewGateSettlingLogic.ts@@ -0,0 +1,84 @@+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'++/**+ * Upper bound on the "turning it on" state after opt-in. Ingestion normally catches up within+ * seconds and a successful setup detection ends the wait early; the cap only exists so a slow+ * pipeline can never lock the user on the enabling state.+ */+const ENROLLMENT_SETTLE_TIMEOUT_MS = 15000++export interface FeaturePreviewGateSettlingLogicProps {+ flag: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featurePreviewGateSettlingLogicValues {+ settling: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featurePreviewGateSettlingLogicActions {+ markServerCaughtUp: () => {+ value: true+ }+ startSettling: () => {+ value: true+ }+ stopSettling: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featurePreviewGateSettlingLogicMeta {+ key: string+}++export type featurePreviewGateSettlingLogicType = MakeLogicType<+ featurePreviewGateSettlingLogicValues,+ featurePreviewGateSettlingLogicActions,+ FeaturePreviewGateSettlingLogicProps,+ featurePreviewGateSettlingLogicMeta+>++/**+ * Tracks the window between a user opting into a feature preview and the API agreeing. The+ * browser evaluates the flag as on the moment enrollment is stored locally (it is a locally+ * stored person property), while the API keeps denying until that property is ingested. A scene+ * mounted in that window 403s on every request, which reads as a broken product until a reload.+ * The scene gate holds an enabling state while `settling` is true; a successful setup detection+ * (`markServerCaughtUp`, fired by the gate) or the timeout ends the wait.+ */+export const featurePreviewGateSettlingLogic = kea<featurePreviewGateSettlingLogicType>([+ props({} as FeaturePreviewGateSettlingLogicProps),+ key((props) => props.flag),+ path((key) => ['layout', 'scenes', 'components', 'featurePreviewGateSettlingLogic', key]),+ actions({+ startSettling: true,+ stopSettling: true,+ markServerCaughtUp: true,+ }),+ reducers({+ settling: [+ false,+ {+ startSettling: () => true,+ stopSettling: () => false,+ markServerCaughtUp: () => false,+ },+ ],+ }),+ listeners(({ actions, cache }) => ({+ startSettling: () => {+ cache.disposables.add(() => {+ const id = window.setTimeout(() => actions.stopSettling(), ENROLLMENT_SETTLE_TIMEOUT_MS)+ return () => clearTimeout(id)+ }, 'settle-timeout')+ },+ markServerCaughtUp: () => {+ // Ending the wait early makes the timeout redundant; dispose it so it cannot fire+ // after the gate has already mounted the scene.+ cache.disposables.dispose('settle-timeout')+ },+ })),+])diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 222dedb8f397..c517b05392b8 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -6,6 +6,20 @@ export function isAccessDeniedError(error: { status?: number; code?: string | nureturn error.status === 403 && error.code === 'permission_denied'}+/** DRF code for `PostHogFeatureFlagPermission` (posthog/permissions.py). Keep in sync with the backend. */+export const FEATURE_FLAG_REQUIRED_ERROR_CODE = 'feature_flag_required'++/**+ * A 403 from a feature flag gate rather than from access control: the flag behind the product+ * is not on for this user yet. Early access enrollment reaches the server as an ingested person+ * property, so this is also what the seconds right after enabling a feature preview look like,+ * while the browser already evaluates the flag as on.+ */+export function isFeatureFlagGatedError(error: unknown): boolean {+ const failure = error as { status?: number; code?: string | null } | null+ return failure?.status === 403 && failure?.code === FEATURE_FLAG_REQUIRED_ERROR_CODE+}+/** DRF code for `ClickHouseQueryMemoryLimitExceeded` (posthog/exceptions.py). Keep in sync with the backend. */export const CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE = 'clickhouse_memory_limit_exceeded'diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 75dead41c856..cd2b3ba7ef5c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7859,7 +7859,10 @@ export interface FeaturePreviewGateConfig {offerRequestAccess?: boolean/*** Product intent recorded when a user joins the waitlist from the gate, so waitlist sign-ups- * count as product intent the same way opting in from the feature previews page does.+ * count as product intent the same way opting in from the feature previews page does. When+ * set, the gate also reads this product's setup-detection status to end the post-enrollment+ * "turning it on" state as soon as the API agrees the flag is on, instead of waiting out a+ * fixed timer.*/productIntent?: ProductKey}diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 7b3563eff824..38e1f9ed6e00 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -1213,6 +1213,13 @@ def posthog_feature_flag_enabled()+# DRF error code for a flag-gated 403, so a client can tell "not on this alpha yet" apart from a+# plain access-control denial. Early access enrollment reaches the server as an ingested person+# property, so a user who has just turned a feature preview on keeps getting denied for a few+# seconds - the frontend treats this code as "access on its way", not as an error.+FEATURE_FLAG_REQUIRED_ERROR_CODE = "feature_flag_required"++class PostHogFeatureFlagPermission(BasePermission):def has_permission(self, request, view) -> bool:user = cast(User, request.user)@@ -1250,6 +1257,7 @@ class PostHogFeatureFlagPermission(BasePermission):self.message = (f"This action requires feature flag {required_flag!r} to be enabled for your organization.")+ self.code = FEATURE_FLAG_REQUIRED_ERROR_CODEreturn Falsereturn Truediff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex d99eae38f5b5..f942b1200ef9 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -32,7 +32,12 @@ from posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from posthog.permissions import AccessControlPermission, ActiveOrganizationPermission, PostHogFeatureFlagPermission+from posthog.permissions import (+ FEATURE_FLAG_REQUIRED_ERROR_CODE,+ AccessControlPermission,+ ActiveOrganizationPermission,+ PostHogFeatureFlagPermission,+)from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.models.access_control import AccessControl@@ -1350,6 +1355,14 @@ class TestPostHogFeatureFlagPermission(BaseTest):result = self.permission.has_permission(request, view)self.assertFalse(result)+ # DRF passes both onto the 403 body. The code lets a client tell a not-yet-ingested+ # alpha enrollment (which clears on its own seconds later) apart from a plain+ # access-control denial.+ self.assertEqual(self.permission.code, FEATURE_FLAG_REQUIRED_ERROR_CODE)+ self.assertEqual(+ self.permission.message,+ "This action requires feature flag 'my-flag' to be enabled for your organization.",+ )@patch("posthog.permissions._FORCE_ENABLED_FLAGS", frozenset({"my-flag"}))@patch("posthoganalytics.feature_enabled")diff --git a/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts b/products/metrics/frontend/emptyState/metricsSetupLogic.test.tsindex 1f9f92bc4539..15778d67bbb7 100644--- a/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts+++ b/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts@@ -33,4 +33,26 @@ describe('metricsSetupLogic', () => {await expectLogic(metricsSetupLogic).toFinishAllListeners()expect(productSetupStatusLogic({ productKey: ProductKey.METRICS }).values.status).toBe(expected)})++ it('treats a flag-gated 403 as unknown, so a fresh alpha enrollment never surfaces an error', async () => {+ // The enrollment person property takes seconds to ingest after the user turns the+ // preview on; until then the API denies with the feature_flag_required code. That+ // window is not a detection failure, and the poll answers properly once it closes.+ ;(canViewMetrics as jest.Mock).mockReturnValue(true)+ ;(metricsHasMetricsRetrieve as jest.Mock).mockRejectedValue({ status: 403, code: 'feature_flag_required' })+ metricsSetupLogic.mount()+ await expectLogic(metricsSetupLogic).toFinishAllListeners()+ expect(productSetupStatusLogic({ productKey: ProductKey.METRICS }).values.status).toBe('unknown')+ // A clean `unknown` answer, not a detection failure: the loader's failure path would+ // also land on `unknown`, but only after filing an error.+ expect(metricsSetupLogic.values.detectedStatus).toBe('unknown')+ })++ it('still fails open on other errors', async () => {+ ;(canViewMetrics as jest.Mock).mockReturnValue(true)+ ;(metricsHasMetricsRetrieve as jest.Mock).mockRejectedValue(new Error('network down'))+ metricsSetupLogic.mount()+ await expectLogic(metricsSetupLogic).toFinishAllListeners()+ expect(productSetupStatusLogic({ productKey: ProductKey.METRICS }).values.status).toBe('unknown')+ })})diff --git a/products/metrics/frontend/emptyState/metricsSetupLogic.ts b/products/metrics/frontend/emptyState/metricsSetupLogic.tsindex f0ccbad3b1c1..9a79c68f95a2 100644--- a/products/metrics/frontend/emptyState/metricsSetupLogic.ts+++ b/products/metrics/frontend/emptyState/metricsSetupLogic.ts@@ -1,3 +1,4 @@+import { isFeatureFlagGatedError } from 'lib/api-error'import { createSetupDetectionLogic } from 'lib/components/ProductEmptyState/setupDetectionLogic'import { retryWithBackoff } from 'lib/utils/async'import { addProductIntent } from 'lib/utils/product-intents'@@ -31,8 +32,21 @@ export const metricsSetupLogic = createSetupDetectionLogic({if (!teamId) {return 'unknown'}- const response = await retryWithBackoff(() => metricsHasMetricsRetrieve(String(teamId)), { maxAttempts: 3 })- return response.hasMetrics ? 'has-data' : 'needs-setup'+ try {+ const response = await retryWithBackoff(() => metricsHasMetricsRetrieve(String(teamId)), {+ maxAttempts: 3,+ })+ return response.hasMetrics ? 'has-data' : 'needs-setup'+ } catch (error) {+ // The alpha enrollment has not reached the server yet: it arrives as an ingested+ // person property, so a user who just turned the feature preview on is still denied+ // for a few seconds. That is not a detection failure worth an error toast - report+ // `unknown` and let the next poll answer.+ if (isFeatureFlagGatedError(error)) {+ return 'unknown'+ }+ throw error+ }},onDetected: (status) => {if (status === 'needs-setup') {