: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
feat(experiments): Add freeze-exposure lifecycle action (#63838)
Marcel Poelkere65a2983e085
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 44e6baf54fec..dbfbbda67389 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -22320,6 +22320,14 @@"description": {"type": ["string", "null"]},+ "exposure_frozen": {+ "description": "Stamped by the experiment exposure freeze: the group carries a machine-added snapshot-cohort condition.",+ "type": "boolean"+ },+ "exposure_frozen_cohort": {+ "description": "Snapshot cohort the exposure freeze AND'd into this group's properties.",+ "type": "number"+ },"properties": {"items": {"$ref": "#/definitions/AnyPropertyFilter"diff --git a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsxindex 642082513940..a3f16b053411 100644--- a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx+++ b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx@@ -182,7 +182,8 @@ export const RelatedExperimentsTable = ({[ExperimentStatus.Draft]: 1,[ExperimentStatus.Running]: 2,[ExperimentStatus.Paused]: 3,- [ExperimentStatus.Stopped]: 4,+ [ExperimentStatus.ExposureFrozen]: 4,+ [ExperimentStatus.Stopped]: 5,}return score[statusA] > score[statusB] ? 1 : -1},diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsxindex a33018944e64..17e9be1643d1 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx@@ -22,6 +22,7 @@ import { groupsModel } from '~/models/groupsModel'import { ExperimentConclusion } from '~/types'import { CONCLUSION_DISPLAY_CONFIG } from '../constants'+import { hasFrozenExposureStamps } from '../experimentActions'import { experimentLogic } from '../experimentLogic'import { modalsLogic } from '../modalsLogic'import { VariantTag } from './VariantTag'@@ -301,6 +302,13 @@ export function FinishExperimentModal(): JSX.Element {</div>) : (<>+ {hasFrozenExposureStamps(experiment) && (+ <LemonBanner type="info">+ Exposure is frozen for this experiment. If you end it without shipping a variant,+ the feature flag keeps serving variants only to the frozen snapshot of+ already-enrolled users. Shipping a variant removes the freeze.+ </LemonBanner>+ )}<div><LemonLabel showOptional>Variant to keep</LemonLabel><div className="text-xs text-muted mb-1">diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsxindex 0344b84f62af..8df0e1d5e4e1 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx@@ -6,6 +6,7 @@ import {IconArchive,IconCopy,IconEye,+ IconLock,IconPause,IconPlay,IconPlusSmall,@@ -40,7 +41,14 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { CopyExperimentToProjectModal } from '../CopyExperimentToProjectModal'import { DuplicateExperimentModal } from '../DuplicateExperimentModal'-import { canArchiveExperiment, confirmArchiveExperiment, confirmDeleteExperiment } from '../experimentActions'+import {+ canArchiveExperiment,+ canFreezeExposure,+ confirmArchiveExperiment,+ confirmDeleteExperiment,+ confirmFreezeExposure,+ hasFrozenExposureStamps,+} from '../experimentActions'import { experimentLogic } from '../experimentLogic'import { isExperimentPaused } from '../experimentsLogic'import { modalsLogic } from '../modalsLogic'@@ -63,6 +71,7 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {isExperimentLaunched,isExperimentStopped,isCreatingExperimentDashboard,+ freezeExposureLoading,showDebugPanel,} = useValues(experimentLogic)const {@@ -71,6 +80,7 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {createExposureCohort,createExperimentDashboard,resetRunningExperiment,+ freezeExposure,toggleDebugPanel,} = useActions(experimentLogic)const { currentProjectId } = useValues(projectLogic)@@ -97,6 +107,7 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {const exposureCohortId = experiment?.exposure_cohortconst showRunningState = isExperimentRunning && !isExperimentStopped && !!experiment.feature_flagconst paused = isExperimentPaused(experiment)+ const showFreezeExposure = canFreezeExposure(experiment)const handleArchive = (): void =>confirmArchiveExperiment(experiment, (disableFlag) => archiveExperiment(disableFlag))@@ -121,9 +132,16 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {All events collected thus far will still exist, but won't be applied to the experimentunless you manually change the start date after launching the experiment again.</p>- <p>- The <b>feature flag remains untouched</b>, so variants stay visible to users.- </p>+ {hasFrozenExposureStamps(experiment) ? (+ <p>+ The <b>exposure freeze is removed</b>: the flag serves its original release conditions+ again and the snapshot cohort is deleted. Everything else on the flag stays untouched.+ </p>+ ) : (+ <p>+ The <b>feature flag remains untouched</b>, so variants stay visible to users.+ </p>+ )}</div>{experiment.archived && (<div className="text-sm text-secondary">Resetting will also unarchive the experiment.</div>@@ -279,15 +297,29 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {Resume experiment</SceneMenuBarItem>) : (- <SceneMenuBarItem- opensFloatingUi- variant="destructive"- onClick={() => openPauseExperimentModal()}- data-attr={`${RESOURCE_TYPE}-menubar-pause`}- >- <IconPause />- Pause experiment- </SceneMenuBarItem>+ <>+ {showFreezeExposure && (+ <SceneMenuBarItem+ opensFloatingUi+ onClick={() => confirmFreezeExposure(freezeExposure)}+ disabled={freezeExposureLoading}+ tooltip={freezeExposureLoading ? 'Freezing exposure…' : undefined}+ data-attr={`${RESOURCE_TYPE}-menubar-freeze-exposure`}+ >+ <IconLock />+ Freeze exposure+ </SceneMenuBarItem>+ )}+ <SceneMenuBarItem+ opensFloatingUi+ variant="destructive"+ onClick={() => openPauseExperimentModal()}+ data-attr={`${RESOURCE_TYPE}-menubar-pause`}+ >+ <IconPause />+ Pause experiment+ </SceneMenuBarItem>+ </>))}</SceneMenuBarMenu>{showStaffMenu && (diff --git a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsxindex 51aa00045f18..eb09225a07f9 100644--- a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx@@ -7,6 +7,7 @@ import {IconCopy,IconEye,IconFlask,+ IconLock,IconPause,IconPlay,IconPlusSmall,@@ -35,7 +36,14 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { CopyExperimentToProjectModal } from '../CopyExperimentToProjectModal'import { DuplicateExperimentModal } from '../DuplicateExperimentModal'-import { canArchiveExperiment, confirmArchiveExperiment, confirmDeleteExperiment } from '../experimentActions'+import {+ canArchiveExperiment,+ canFreezeExposure,+ confirmArchiveExperiment,+ confirmDeleteExperiment,+ confirmFreezeExposure,+ hasFrozenExposureStamps,+} from '../experimentActions'import { experimentLogic } from '../experimentLogic'import { isExperimentPaused } from '../experimentsLogic'import { modalsLogic } from '../modalsLogic'@@ -53,6 +61,7 @@ export function PageHeaderCustom(): JSX.Element {isCreatingExperimentDashboard,experimentLoading,launchExperimentLoading,+ freezeExposureLoading,} = useValues(experimentLogic)const {launchExperiment,@@ -62,6 +71,7 @@ export function PageHeaderCustom(): JSX.Element {createExperimentDashboard,updateExperiment,setHogfettiTrigger,+ freezeExposure,} = useActions(experimentLogic)const { currentProjectId } = useValues(projectLogic)const { currentOrganization } = useValues(organizationLogic)@@ -248,14 +258,28 @@ export function PageHeaderCustom(): JSX.Element {<IconPlay /> Resume experiment</ButtonPrimitive>) : (- <ButtonPrimitive- variant="danger"- menuItem- data-attr="pause-experiment"- onClick={() => openPauseExperimentModal()}- >- <IconPause /> Pause experiment- </ButtonPrimitive>+ <>+ {canFreezeExposure(experiment) && (+ <ButtonPrimitive+ menuItem+ data-attr="freeze-exposure"+ onClick={() => confirmFreezeExposure(freezeExposure)}+ disabledReasons={{+ 'Freezing exposure...': freezeExposureLoading,+ }}+ >+ <IconLock /> Freeze exposure+ </ButtonPrimitive>+ )}+ <ButtonPrimitive+ variant="danger"+ menuItem+ data-attr="pause-experiment"+ onClick={() => openPauseExperimentModal()}+ >+ <IconPause /> Pause experiment+ </ButtonPrimitive>+ </>))}<ResetButton />@@ -345,9 +369,16 @@ const ResetButton = (): JSX.Element => {All events collected thus far will still exist, but won't be applied to the experimentunless you manually change the start date after launching the experiment again.</p>- <p>- The <b>feature flag remains untouched</b>, so variants stay visible to users.- </p>+ {hasFrozenExposureStamps(experiment) ? (+ <p>+ The <b>exposure freeze is removed</b>: the flag serves its original release conditions+ again and the snapshot cohort is deleted. Everything else on the flag stays untouched.+ </p>+ ) : (+ <p>+ The <b>feature flag remains untouched</b>, so variants stay visible to users.+ </p>+ )}</div>{experiment.archived && (<div className="text-sm text-secondary">Resetting will also unarchive the experiment.</div>diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsxindex 31b3c1a5e1b7..926427ae6246 100644--- a/frontend/src/scenes/experiments/Experiments.tsx+++ b/frontend/src/scenes/experiments/Experiments.tsx@@ -147,6 +147,7 @@ const ExperimentsTableFilters = ({{ label: 'Draft', value: ExperimentStatus.Draft },{ label: 'Running', value: ExperimentStatus.Running },{ label: 'Paused', value: ExperimentStatus.Paused },+ { label: 'Exposure frozen', value: ExperimentStatus.ExposureFrozen },{ label: 'Complete', value: ExperimentStatus.Stopped },] as { label: string; value: string }[]}@@ -335,7 +336,8 @@ const ExperimentsTable = ({[ExperimentStatus.Draft]: 1,[ExperimentStatus.Running]: 2,[ExperimentStatus.Paused]: 3,- [ExperimentStatus.Stopped]: 4,+ [ExperimentStatus.ExposureFrozen]: 4,+ [ExperimentStatus.Stopped]: 5,}return score[statusA] > score[statusB] ? 1 : -1},diff --git a/frontend/src/scenes/experiments/experimentActions.tsx b/frontend/src/scenes/experiments/experimentActions.tsxindex 1924c80350ce..b90060d521f0 100644--- a/frontend/src/scenes/experiments/experimentActions.tsx+++ b/frontend/src/scenes/experiments/experimentActions.tsx@@ -4,7 +4,7 @@ import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { Experiment } from '~/types'-import { hasEnded } from './experimentsLogic'+import { hasEnded, isExperimentExposureFrozen, isExperimentPaused, isLaunched } from './experimentsLogic'/** Whether an experiment is in a state where it can be archived (ignoring permissions). */export function canArchiveExperiment(@@ -13,6 +13,70 @@ export function canArchiveExperiment(return !experiment.archived && hasEnded(experiment)}+/** Whether the experiment's flag release groups still carry the exposure-freeze stamps.+ * Unlike the status check, this also covers paused or stopped experiments whose flag was+ * frozen earlier — reset clears the stamps in all of those states. */+export function hasFrozenExposureStamps(experiment: Pick<Experiment, 'feature_flag'>): boolean {+ return !!experiment.feature_flag?.filters?.groups?.some((group) => group.exposure_frozen === true)+}++/** Whether an experiment can have its exposure frozen (ignoring permissions). */+export function canFreezeExposure(+ experiment: Pick<Experiment, 'start_date' | 'end_date' | 'status' | 'feature_flag' | 'holdout_id' | 'holdout'>+): boolean {+ const flagFilters = experiment.feature_flag?.filters+ // Freezing exposure narrows the flag to a person cohort, which group-aggregated flags can't use.+ const isGroupAggregated = flagFilters?.aggregation_group_type_index != null+ // Holdout assignment and early access enrollment (super_groups) are evaluated before release+ // conditions, so the freeze couldn't stop enrollment through them — the backend rejects these.+ const hasHoldout =+ experiment.holdout_id != null ||+ experiment.holdout != null ||+ !!flagFilters?.holdout ||+ !!flagFilters?.holdout_groups?.length+ const hasSuperGroups = !!flagFilters?.super_groups?.length+ return (+ isLaunched(experiment) &&+ !hasEnded(experiment) &&+ !isExperimentPaused(experiment) &&+ !isExperimentExposureFrozen(experiment) &&+ !isGroupAggregated &&+ !hasHoldout &&+ !hasSuperGroups+ )+}++export function confirmFreezeExposure(onConfirm: () => void): void {+ LemonDialog.open({+ title: 'Freeze exposure?',+ content: (+ <div className="text-sm text-secondary max-w-md">+ <p>+ New users can <b>no longer enroll</b>. Everyone already enrolled keeps their variant, and metrics+ keep updating — useful for measuring long-term impact (revenue, retention, renewals) after you stop+ adding new users.+ </p>+ <p>+ This snapshots the currently-exposed users into a static cohort and narrows the feature flag to it.+ The experiment <b>keeps running</b>, so results keep updating.+ </p>+ <p>From a frozen state you can end an experiment or ship a variant at any time.</p>+ </div>+ ),+ primaryButton: {+ children: 'Freeze exposure',+ type: 'primary',+ onClick: onConfirm,+ size: 'small',+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'tertiary',+ size: 'small',+ },+ })+}+export function confirmArchiveExperiment(experiment: Pick<Experiment, 'feature_flag'>,onConfirm: (disableFeatureFlag: boolean) => voiddiff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 73df067ed3ec..e4e9ab194927 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -1279,6 +1279,53 @@ describe('experimentLogic', () => {})})+ describe('freezeExposure', () => {+ it('calls freeze_exposure endpoint, updates experiment, and toggles the loading guard', async () => {+ const frozenResponse = { ...experiment, status: 'exposure_frozen' }+ const createSpy = jest.spyOn(api, 'create').mockResolvedValue(frozenResponse)++ const keyed = experimentLogic({ experimentId: experiment.id })+ keyed.mount()+ keyed.actions.setExperiment(experiment)++ expect(keyed.values.freezeExposureLoading).toBe(false)++ await expectLogic(keyed, () => {+ keyed.actions.freezeExposure()+ })+ .toDispatchActions(['freezeExposure', 'setFreezeExposureLoading', 'setExperiment'])+ .toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledWith(+ expect.stringContaining(`/experiments/${experiment.id}/freeze_exposure`)+ )+ expect(keyed.values.experiment.status).toBe('exposure_frozen')+ // Loading guard is reset after the request settles.+ expect(keyed.values.freezeExposureLoading).toBe(false)++ createSpy.mockRestore()+ keyed.unmount()+ })++ it('shows error toast and resets the loading guard on failure', async () => {+ const createSpy = jest.spyOn(api, 'create').mockRejectedValue({+ detail: 'Experiment exposure is already frozen.',+ })+ const errorMock = lemonToast.error as jest.Mock+ errorMock.mockClear()++ logic.actions.setExperiment(experiment)++ await expectLogic(logic, () => {+ logic.actions.freezeExposure()+ }).toFinishAllListeners()++ expect(errorMock).toHaveBeenCalledWith('Experiment exposure is already frozen.')+ expect(logic.values.freezeExposureLoading).toBe(false)+ createSpy.mockRestore()+ })+ })+describe('resetRunningExperiment', () => {it('calls reset endpoint and updates experiment to draft state', async () => {const runningExperiment = {diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 635d13dabca5..0c2d39d5e0ee 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -609,6 +609,8 @@ export const experimentLogic = kea<experimentLogicType>([}) => ({ selectedVariantKey, releaseToEveryone, openCleanupPr: openCleanupPr ?? false }),pauseExperiment: true,resumeExperiment: true,+ freezeExposure: true,+ setFreezeExposureLoading: (loading: boolean) => ({ loading }),archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),unarchiveExperiment: true,resetRunningExperiment: true,@@ -1169,6 +1171,12 @@ export const experimentLogic = kea<experimentLogicType>([setEndExperimentLoading: (_, { loading }) => loading,},],+ freezeExposureLoading: [+ false,+ {+ setFreezeExposureLoading: (_, { loading }) => loading,+ },+ ],hogfettiTrigger: [null as (() => void) | null,{@@ -1465,6 +1473,24 @@ export const experimentLogic = kea<experimentLogicType>([lemonToast.error(error.detail || 'Failed to resume experiment')}},+ freezeExposure: async () => {+ if (values.freezeExposureLoading) {+ return+ }+ actions.setFreezeExposureLoading(true)+ try {+ const response: Experiment = await api.create(+ `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/freeze_exposure`+ )+ actions.setExperiment(response)+ refreshTreeItem('experiment', String(values.experimentId))+ lemonToast.success('Exposure frozen — enrolled users keep their variant and metrics keep updating')+ } catch (error: any) {+ lemonToast.error(error.detail || 'Failed to freeze exposure')+ } finally {+ actions.setFreezeExposureLoading(false)+ }+ },archiveExperiment: async ({ disableFeatureFlag }) => {try {const response: Experiment = await api.create(diff --git a/frontend/src/scenes/experiments/experimentStatus.ts b/frontend/src/scenes/experiments/experimentStatus.tsindex e8bd6d00be39..7977d31cb0fe 100644--- a/frontend/src/scenes/experiments/experimentStatus.ts+++ b/frontend/src/scenes/experiments/experimentStatus.ts@@ -27,6 +27,10 @@ export function isExperimentPaused(experiment: ExperimentStatusInput): boolean {return getExperimentStatus(experiment) === ExperimentStatus.Paused}+export function isExperimentExposureFrozen(experiment: ExperimentStatusInput): boolean {+ return getExperimentStatus(experiment) === ExperimentStatus.ExposureFrozen+}+export function isLaunched(experiment: ExperimentStatusInput): boolean {return getExperimentStatus(experiment) !== ExperimentStatus.Draft}diff --git a/frontend/src/scenes/experiments/experimentsLogic.test.ts b/frontend/src/scenes/experiments/experimentsLogic.test.tsindex 530c84ffc329..671e845f0a26 100644--- a/frontend/src/scenes/experiments/experimentsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentsLogic.test.ts@@ -15,7 +15,9 @@ import {experimentsLogic,getExperimentStatus,getExperimentStatusColor,+ getExperimentStatusLabel,hasEnded,+ isExperimentExposureFrozen,isExperimentPaused,} from './experimentsLogic'@@ -572,15 +574,35 @@ describe('utility functions', () => {})})+ describe('getExperimentStatus', () => {+ it('returns ExposureFrozen when the API status is exposure_frozen', () => {+ const frozenExperiment = createMockExperiment({+ start_date: '2024-01-01',+ end_date: null,+ status: ExperimentStatus.ExposureFrozen,+ feature_flag: { active: true },+ })+ expect(getExperimentStatus(frozenExperiment)).toBe(ExperimentStatus.ExposureFrozen)+ expect(isExperimentExposureFrozen(frozenExperiment)).toBe(true)+ })+ })+describe('getExperimentStatusColor', () => {it('returns correct colors for each status', () => {expect(getExperimentStatusColor(ExperimentStatus.Draft)).toBe('default')expect(getExperimentStatusColor(ExperimentStatus.Running)).toBe('success')expect(getExperimentStatusColor(ExperimentStatus.Paused)).toBe('warning')+ expect(getExperimentStatusColor(ExperimentStatus.ExposureFrozen)).toBe('highlight')expect(getExperimentStatusColor(ExperimentStatus.Stopped)).toBe('completion')})})+ describe('getExperimentStatusLabel', () => {+ it('labels exposure_frozen as Exposure frozen', () => {+ expect(getExperimentStatusLabel(ExperimentStatus.ExposureFrozen)).toBe('Exposure frozen')+ })+ })+describe('hasEnded', () => {it.each([{ status: ExperimentStatus.Running, expected: false, desc: 'running experiment' },diff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.tsindex e02fef293234..6e458fa652c0 100644--- a/frontend/src/scenes/experiments/experimentsLogic.ts+++ b/frontend/src/scenes/experiments/experimentsLogic.ts@@ -70,7 +70,13 @@ const DEFAULT_MODAL_FILTERS: FeatureFlagModalFilters = {evaluation_runtime: undefined,}-export { getExperimentStatus, hasEnded, isExperimentPaused, isLaunched } from './experimentStatus'+export {+ getExperimentStatus,+ hasEnded,+ isExperimentExposureFrozen,+ isExperimentPaused,+ isLaunched,+} from './experimentStatus'export function isSingleVariantShipped(experiment: Experiment): boolean {const filters = experiment.feature_flag?.filters@@ -104,6 +110,8 @@ export function getExperimentStatusLabel(status: ExperimentStatus): string {return 'Running'case ExperimentStatus.Paused:return 'Paused'+ case ExperimentStatus.ExposureFrozen:+ return 'Exposure frozen'case ExperimentStatus.Stopped:return 'Complete'}@@ -117,6 +125,8 @@ export function getExperimentStatusColor(status: ExperimentStatus): LemonTagTypereturn 'success'case ExperimentStatus.Paused:return 'warning'+ case ExperimentStatus.ExposureFrozen:+ return 'highlight'case ExperimentStatus.Stopped:return 'completion'}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 8a31ddf44cd8..7c8324732fe9 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1100,6 +1100,9 @@ export enum ExperimentStatus {Draft = 'draft',Running = 'running',Paused = 'paused',+ // Running with enrollment frozen to the already-exposed cohort while metrics keep flowing.+ // Derived from the feature flag, not stored — see Experiment.is_exposure_frozen.+ ExposureFrozen = 'exposure_frozen',Stopped = 'stopped',}@@ -4236,6 +4239,10 @@ export interface FeatureFlagGroupType {sort_key?: string | null // Client-side only stable id for sorting.description?: string | nullaggregation_group_type_index?: integer | null+ /** Stamped by the experiment exposure freeze: the group carries a machine-added snapshot-cohort condition. */+ exposure_frozen?: boolean+ /** Snapshot cohort the exposure freeze AND'd into this group's properties. */+ exposure_frozen_cohort?: number}export interface MultivariateFlagVariant {@@ -4266,6 +4273,12 @@ export interface FeatureFlagFilters {payloads?: Record<string, JsonType>early_exit?: booleanfeature_enrollment?: boolean+ /** Experiment holdout exclusion, evaluated by the flag matcher before release conditions. */+ holdout?: { id: number; exclusion_percentage: number } | null+ /** Legacy holdout representation, also evaluated before release conditions. */+ holdout_groups?: FeatureFlagGroupType[] | null+ /** Early access enrollment conditions, evaluated before release conditions. */+ super_groups?: FeatureFlagGroupType[] | null}export interface FeatureFlagBasicType {diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 51eaafcdaa82..1f2ad5c09957 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -699,6 +699,7 @@'holdout_id','id','is_draft',+ 'is_exposure_frozen','is_launched','is_paused','is_running',diff --git a/posthog/schema.py b/posthog/schema.pyindex 4cdad8ac670b..bda1d074acfc 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -15526,6 +15526,16 @@ class FeatureFlagGroupType(BaseModel):)aggregation_group_type_index: int | None = Nonedescription: str | None = None+ exposure_frozen: bool | None = Field(+ default=None,+ description=(+ "Stamped by the experiment exposure freeze: the group carries a machine-added snapshot-cohort condition."+ ),+ )+ exposure_frozen_cohort: float | None = Field(+ default=None,+ description=("Snapshot cohort the exposure freeze AND'd into this group's properties."),+ )properties: (list[EventPropertyFilterdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 83ce14df9e0e..8f46a45d6272 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -571,7 +571,7 @@ SPECTACULAR_SETTINGS = {# for the list endpoint) that both expose `type`/`status`. Pin both to their pre-existing# generated names so the shared enums don't get component-prefixed auto-names on collision."ExperimentTypeEnum": ["web", "product", None],- "ExperimentStatusEnum": ["draft", "running", "paused", "stopped"],+ "ExperimentStatusEnum": ["draft", "running", "paused", "exposure_frozen", "stopped"],# Two `sync_frequency` ChoiceFields with different member sets: warehouse-source schemas# accept sub-15min cadences, while saved-query (view) materialization floors at 15min.# Pin both to stable names so neither gets a component-prefixed auto-name on collision.diff --git a/products/dashboards/backend/api/test/test_experiment_widgets.py b/products/dashboards/backend/api/test/test_experiment_widgets.pyindex aa4920a4a64a..db6551dff5e7 100644--- a/products/dashboards/backend/api/test/test_experiment_widgets.py+++ b/products/dashboards/backend/api/test/test_experiment_widgets.py@@ -23,7 +23,7 @@ from products.dashboards.backend.widgets.experiment_results import (run_experiment_results_widget,)from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import EXPOSURE_FROZEN_GROUP_KEY, Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -86,12 +86,18 @@ class TestExperimentsListWidget(APIBaseTest):start_date: Any = None,end_date: Any = None,flag_active: bool = True,+ exposure_frozen: bool = False,) -> Experiment:feature_flag = FeatureFlag.objects.create(team=self.team,key=f"flag-{name}",created_by=created_by or self.user,active=flag_active,+ filters=(+ {"groups": [{"properties": [], "rollout_percentage": 100, EXPOSURE_FROZEN_GROUP_KEY: True}]}+ if exposure_frozen+ else {}+ ),)return Experiment.objects.create(team=self.team,@@ -121,6 +127,7 @@ class TestExperimentsListWidget(APIBaseTest):("draft", "draft"),("running", "running"),("paused", "paused"),+ ("exposure_frozen", "exposure_frozen"),("stopped", "stopped"),])@@ -130,11 +137,13 @@ class TestExperimentsListWidget(APIBaseTest):"draft": "Draft exp","running": "Running exp","paused": "Paused exp",+ "exposure_frozen": "Frozen exp","stopped": "Stopped exp",}self._create_experiment("Draft exp")self._create_experiment("Running exp", start_date=now)self._create_experiment("Paused exp", start_date=now, flag_active=False)+ self._create_experiment("Frozen exp", start_date=now, exposure_frozen=True)self._create_experiment("Stopped exp", start_date=now, end_date=now)result = run_experiments_list_widget(self.team, {"status": status_filter}, user=self.user)diff --git a/products/dashboards/backend/widget_specs/configs.py b/products/dashboards/backend/widget_specs/configs.pyindex 759b4642b406..4dce90b53331 100644--- a/products/dashboards/backend/widget_specs/configs.py+++ b/products/dashboards/backend/widget_specs/configs.py@@ -33,7 +33,7 @@ SessionReplayOrderBy = Literal["start_time", "activity_score", "recording_duration", "duration", "click_count", "console_error_count"]WidgetAssigneeType = Literal["user", "role"]-ExperimentsWidgetStatus = Literal["draft", "running", "paused", "stopped", "all"]+ExperimentsWidgetStatus = Literal["draft", "running", "paused", "exposure_frozen", "stopped", "all"]ExperimentsWidgetOrderBy = Literal["created_at", "name", "start_date"]# Matches the logs scene: `earliest` sorts ascending by timestamp, `latest` (default) descending.LogsOrderBy = Literal["latest", "earliest"]diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 8da80bc18390..335456e978d8 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -674,6 +674,7 @@ export const ExperimentsListWidgetConfigApiStatus = {Draft: 'draft',Running: 'running',Paused: 'paused',+ ExposureFrozen: 'exposure_frozen',Stopped: 'stopped',All: 'all',} as constdiff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex 31ff69a64e3e..cfc483b89fca 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -674,7 +674,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault)@@ -1607,7 +1607,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault).describe('Experiment status filter.'),createdBy: zod@@ -2376,7 +2376,7 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsUpdateWidgetsBatchBodyWidgetsItemFourConfigOneStatusDefault).describe('Experiment status filter.'),createdBy: zoddiff --git a/products/dashboards/frontend/generated/widget-config-property-keys.json b/products/dashboards/frontend/generated/widget-config-property-keys.jsonindex 355369790fb6..2fd09f07a2c5 100644--- a/products/dashboards/frontend/generated/widget-config-property-keys.json+++ b/products/dashboards/frontend/generated/widget-config-property-keys.json@@ -287,7 +287,7 @@"$enum": ["ASC", "DESC"]},"status": {- "$enum": ["all", "draft", "paused", "running", "stopped"]+ "$enum": ["all", "draft", "exposure_frozen", "paused", "running", "stopped"]},"createdBy": {"$type": "integer"diff --git a/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.tsindex 2ab7de66bb07..18a6c81cc03f 100644--- a/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.ts+++ b/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.ts@@ -29,7 +29,7 @@ export const ExperimentsListWidgetConfig = /* @__PURE__ */ zod.object({.default(experimentsListWidgetConfigOrderDirectionDefault).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(experimentsListWidgetConfigStatusDefault).describe('Experiment status filter.'),createdBy: zoddiff --git a/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.ts b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.tsindex de04cca28714..d0c4154c1ab5 100644--- a/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.ts+++ b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.ts@@ -29,6 +29,7 @@ export const EXPERIMENTS_WIDGET_STATUS_OPTIONS: { value: ExperimentsListWidgetSt{ value: 'draft', label: 'Draft' },{ value: 'running', label: 'Running' },{ value: 'paused', label: 'Paused' },+ { value: 'exposure_frozen', label: 'Exposure frozen' },{ value: 'stopped', label: 'Complete' },]diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex c02a062e4c39..a13cb4dd48e1 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -10,7 +10,8 @@ from uuid import uuid4from zoneinfo import ZoneInfofrom django.db import transaction-from django.db.models import Case, CharField, Count, F, Prefetch, Q, QuerySet, Value, When+from django.db.models import BooleanField, Case, CharField, Count, F, Prefetch, Q, QuerySet, Value, When+from django.db.models.expressions import RawSQLfrom django.db.models.functions import Coalesce, Now, NullIffrom django.utils import timezone@@ -27,10 +28,21 @@ from posthog.schema import (ExperimentMetric,)-from posthog.api.cohort import CohortSerializer+from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.query import execute_hogql_query++from posthog.api.cohort import CohortSerializer, get_active_flags_using_cohort+from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import EventSource, report_user_action+from posthog.exceptions import (+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+)from posthog.models.activity_logging.utils import get_changed_fields_localfrom posthog.models.filters.filter import Filter+from posthog.models.person.util import validate_person_uuids_existfrom posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Team@@ -44,9 +56,16 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_planfrom products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_mathfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ build_exposure_event_conditions,+ get_exposure_event_and_property,+)from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidatorfrom products.experiments.backend.metric_utils import filter_metric_group_ids_by_eventfrom products.experiments.backend.models.experiment import (+ EXPOSURE_FROZEN_COHORT_KEY,+ EXPOSURE_FROZEN_GROUP_KEY,+ EXPOSURE_FROZEN_GROUP_MARKER,LEGACY_METRIC_KINDS,Experiment,ExperimentHoldout,@@ -97,19 +116,39 @@ DEFAULT_VARIANTS = [{"key": "test", "name": "Test Variant", "rollout_percentage": 50},]+# Synchronous freeze-exposure bounds. The snapshot is built inline in the request, so we cap both the+# time spent scanning $feature_flag_called events (ClickHouse) and the number of exposed users we+# materialize — the Postgres cohort sync is size-linear and is NOT covered by the query timeout.+# The user cap is sized to the cohort insert (batches of 1000, sequential): 100k keeps the whole+# freeze comfortably inside a web request. Long-running / very-high-traffic experiments that exceed+# either bound are rejected rather than frozen synchronously (they would need a future async+# populate path).+FREEZE_EXPOSURE_QUERY_TIMEOUT_SECONDS = 20+FREEZE_EXPOSURE_MAX_EXPOSED_USERS = 100_000+# Cohort membership is person-keyed, so exposed users without a person profile (anonymous+# "personless" traffic, or since-deleted persons) can never match the snapshot cohort and would+# silently lose their variant at freeze time. A small unresolvable share is tolerated as+# deletion/merge noise; beyond this share the freeze is rejected as unable to keep its promise.+FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE = 0.05+# Shared by snapshot creation and cleanup: cleanup only touches cohorts carrying this prefix, so a+# cohort id stamped into the (user-editable) flag filters can't point it at an arbitrary cohort.+FREEZE_EXPOSURE_SNAPSHOT_NAME_PREFIX = "Exposure snapshot for experiment "+class ExperimentQueryStatus(str, Enum):"""Filter values for the experiment list endpoint.- PAUSED is derived (not stored): an experiment is paused when its stored status is RUNNING and- its linked feature flag is inactive. RUNNING and PAUSED are mutually exclusive at the API- layer — RUNNING returns only experiments whose flag is active.+ PAUSED and EXPOSURE_FROZEN are derived (not stored): an experiment is paused when its stored+ status is RUNNING and its linked feature flag is inactive; it is exposure-frozen when its flag+ release groups carry the freeze marker. RUNNING, PAUSED, and EXPOSURE_FROZEN are mutually+ exclusive at the API layer, mirroring the precedence of Experiment.status_label."""DRAFT = "draft"RUNNING = "running"PAUSED = "paused"+ EXPOSURE_FROZEN = "exposure_frozen"STOPPED = "stopped"ALL = "all"@@ -1797,6 +1836,440 @@ class ExperimentService:request=request,)+ # ------------------------------------------------------------------+ # Freeze exposure+ # ------------------------------------------------------------------++ # Not wrapped in @transaction.atomic at the method level: building the snapshot cohort writes to+ # ClickHouse and Postgres (non-transactional side effects), so rather than rely on rollback we+ # clean up the cohort by hand if the locked phase below fails.+ def freeze_exposure(self, experiment: Experiment, *, request: Any) -> Experiment:+ """Freeze exposure on a running experiment while metrics keep flowing.++ Moves the experiment into an "exposure frozen" state: it snapshots the+ already-exposed users into a static cohort and narrows every flag release+ group to that cohort, so new users can no longer enter the experiment while+ already-enrolled users keep their deterministically-assigned variant+ (``multivariate.variants`` is left untouched). Unlike ``end_experiment``,+ ``end_date`` stays null so long-term metrics (revenue/LTV/renewals/retention)+ keep accumulating — the whole point of freezing exposure.++ The snapshot is built synchronously, *before* the flag is narrowed, so the+ flag never points at an unpopulated cohort (which would briefly match no+ one). To keep the request bounded, the exposed-set scan is capped at+ FREEZE_EXPOSURE_QUERY_TIMEOUT_SECONDS and FREEZE_EXPOSURE_MAX_EXPOSED_USERS;+ experiments exceeding either bound — long-running, very-high-traffic ones —+ are rejected rather than frozen in-request.++ Group-aggregated experiments are rejected: their flags target groups, not+ persons, so a person cohort cannot freeze the exposed set. Experiments whose+ exposed set contains a material share of anonymous (personless) users are+ rejected too, since cohort membership is person-keyed and freezing would drop+ those users' variants (see _assert_exposed_persons_resolvable).++ Runs in two phases because the snapshot build can take tens of seconds — plenty of+ time for a concurrent freeze, pause, end, or flag edit to land. Phase 1 (unlocked)+ runs the guards to fail fast, then the expensive ClickHouse scan and cohort build.+ Phase 2 re-fetches the flag under ``select_for_update``, re-runs every guard against+ the fresh rows, and computes the narrowed filters from the fresh state — so a losing+ concurrent freeze gets "already frozen" (and deletes its own cohort) instead of+ double-freezing, and a flag edit that landed mid-scan is narrowed rather than+ clobbered with pre-scan filters.++ ``request`` is required because FeatureFlagSerializer needs a real request+ with authentication and session context to persist the flag change.+ """+ # Phase 1 — unlocked: fail obviously-invalid requests before the expensive snapshot build.+ self._validate_freeze_exposure_state(experiment)++ # 1. Snapshot the actually-exposed set (bounded by time + count; raises if too large to freeze in-request).+ exposed_person_uuids = self._fetch_exposed_person_uuids(experiment)+ if not exposed_person_uuids:+ # An empty snapshot cohort ANDed into every release group would un-enroll every user.+ raise ValidationError(+ "No users have been exposed to this experiment yet, so freezing would stop it for everyone. "+ "Wait until the experiment has recorded exposures."+ )++ # 2. Fail closed if a material share of the exposed set has no person profile: cohort+ # membership is person-keyed, so those users would silently lose their variant.+ self._assert_exposed_persons_resolvable(exposed_person_uuids)++ # 3. Materialize it into a static cohort synchronously, so the flag never points at an unpopulated cohort.+ exposure_snapshot = self._create_exposure_snapshot_cohort(experiment, exposed_person_uuids)++ # Phase 2 — locked: any failure here drops the snapshot cohort, which is referenced only by+ # the flag change attempted below — a failed freeze should leave nothing behind.+ try:+ with transaction.atomic():+ # Lock the flag row so the guard re-check, the transform, and the save happen against+ # a state no concurrent freeze/pause/archive/reset/edit can move underneath us — those+ # writers either committed (we see them) or block until we commit (reset takes this+ # same lock in _clear_frozen_exposure, so it can't slip between our re-check and save).+ locked_flag = (+ FeatureFlag.objects.select_for_update()+ .filter(pk=experiment.feature_flag_id, team_id=experiment.team_id)+ .first()+ )+ if locked_flag is None:+ raise ValidationError("Experiment's feature flag has been deleted.")+ experiment.refresh_from_db()+ # refresh_from_db keeps the cached relation when the FK id is unchanged — swap in the+ # locked row explicitly so the guards read the fresh flag state.+ experiment.feature_flag = locked_flag+ self._validate_freeze_exposure_state(experiment)++ # 4. Narrow every release group to that cohort and stamp the marker.+ #+ # Design note (local evaluation): the narrowed flag now references a static cohort, whose+ # per-person membership can't be shipped to SDKs that evaluate flags locally — static cohorts+ # are excluded from the local-eval flag definitions (products/feature_flags/backend/local_evaluation.py).+ # Such SDKs can't resolve the cohort, so they treat the flag as inconclusive and fall back to+ # /decide, where the freeze is applied correctly; under only_evaluate_locally=True they instead+ # return the flag's default for everyone. This is the standard behavior of any static-cohort flag,+ # not specific to freezing — it just means a frozen experiment is evaluated server-side via /decide+ # rather than locally.+ new_filters = self._transform_filters_for_frozen_exposure(locked_flag.filters, exposure_snapshot.id)++ # 5. Persist the narrowed filters via FeatureFlagSerializer.+ #+ # Design note (approvals): FeatureFlagSerializer.update is decorated with @approval_gate,+ # but flag approval policies are intentionally field-level and scoped to `active`+ # (enable/disable) and `rollout_percentage` changes only — see GATEABLE_FIELDS in+ # products/approvals/backend/actions/feature_flags.py and posthog.com/docs/settings/approvals.+ # Freezing exposure only AND-s a cohort condition into each group's `properties` and stamps+ # `description`; it changes neither `active` nor `rollout_percentage`, so the gate never+ # matches and no change request is raised. We therefore don't special-case ApprovalRequired+ # here. If approvals ever grow to gate property/cohort changes, revisit this: the snapshot+ # cohort would then need to outlive a pending change request rather than be cleaned up below.+ flag_serializer = FeatureFlagSerializer(+ locked_flag,+ data={"filters": new_filters},+ partial=True,+ context={+ "request": request,+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ },+ )+ flag_serializer.is_valid(raise_exception=True)+ flag_serializer.save()+ except Exception:+ exposure_snapshot.delete()+ raise++ # Refresh so the experiment's nested flag reflects the narrowed filters when serialized.+ locked_flag.refresh_from_db()+ experiment.feature_flag = locked_flag++ # end_date intentionally left null — metrics keep flowing.++ self._report_experiment_exposure_frozen(experiment, request=request)++ return experiment++ def _validate_freeze_exposure_state(self, experiment: Experiment) -> None:+ """Guards for freeze_exposure, run twice: unlocked before the expensive snapshot build to+ fail fast, and again under the flag lock to fail closed against whatever landed mid-build."""+ if experiment.is_draft:+ raise ValidationError("Experiment has not been launched yet.")+ if experiment.is_stopped:+ raise ValidationError("Experiment has already ended.")+ if experiment.is_paused:+ # A paused flag serves no one, so there is no live enrollment to freeze; freezing anyway+ # would mislabel the (inactive) experiment as "exposure_frozen". Resume first.+ raise ValidationError("Cannot freeze a paused experiment. Resume it first.")+ if experiment.is_exposure_frozen:+ raise ValidationError("Experiment exposure is already frozen.")++ # Guard on the id, not the relation: feature_flag is a non-nullable FK, so accessing+ # experiment.feature_flag when it's unset raises RelatedObjectDoesNotExist rather than+ # returning None.+ if experiment.feature_flag_id is None:+ raise ValidationError("Experiment does not have a feature flag linked.")+ flag = experiment.feature_flag+ if flag.deleted:+ raise ValidationError("Experiment's feature flag has been deleted.")+ if flag.aggregation_group_type_index is not None:+ raise ValidationError("Group-aggregated experiments cannot have their exposure frozen.")+ # Holdout assignment and early-access enrollment (super_groups) are evaluated by the flag+ # matcher before release conditions, so narrowing the release groups to a cohort cannot stop+ # new users from entering through those paths. Fail closed rather than freeze partially.+ flag_filters = flag.filters or {}+ if experiment.holdout_id is not None or flag_filters.get("holdout") or flag_filters.get("holdout_groups"):+ raise ValidationError(+ "Experiments in a holdout cannot have their exposure frozen: holdout assignment is "+ "evaluated before release conditions, so new users would keep entering the holdout."+ )+ if flag_filters.get("super_groups"):+ raise ValidationError(+ "This experiment's feature flag has early access conditions, which are evaluated "+ "before release conditions, so freezing cannot stop new enrollment."+ )+ # Without release conditions there is nothing to narrow: the transform would be a no-op and+ # the frozen state (derived from the per-group key) could never be detected.+ if not flag_filters.get("groups"):+ raise ValidationError("Experiment's feature flag has no release conditions to freeze.")++ def _fetch_exposed_person_uuids(self, experiment: Experiment) -> list[str]:+ """Return the UUIDs of persons already exposed to the experiment, bounded by time and count.++ Runs a synchronous scan of the experiment's exposure events, honoring+ ``exposure_criteria`` (custom exposure event or action plus its property filters) via the+ same helpers the metrics pipeline uses, and requiring the exposure to have landed a+ variant — so the snapshot is the analyzed population, not everyone who fired the event.+ Capped at FREEZE_EXPOSURE_QUERY_TIMEOUT_SECONDS and returning at most+ FREEZE_EXPOSURE_MAX_EXPOSED_USERS + 1 rows so an over-cap set can be detected and rejected.++ Deliberate deviation from the analysis-side definition:+ ``exposure_criteria.filterTestAccounts`` is NOT applied. It shapes which exposures are+ *analyzed*; this snapshot decides who keeps being *served* a variant, and excluding test+ accounts from it would evict the team's own users at freeze time.+ """+ # start_date is guaranteed non-null here — the caller already asserted the experiment is running.+ start_date = experiment.start_date+ assert start_date is not None+ flag_key = experiment.get_feature_flag_key()++ _, variant_property = get_exposure_event_and_property(flag_key, experiment.exposure_criteria)+ variant_keys = [variant["key"] for variant in experiment.feature_flag.variants]++ conditions: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=start_date),+ ),+ *build_exposure_event_conditions(experiment.exposure_criteria, self.team, flag_key),+ ]+ if variant_keys:+ conditions.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["properties", variant_property]),+ right=ast.Constant(value=variant_keys),+ )+ )++ query = ast.SelectQuery(+ select=[ast.Field(chain=["person_id"])],+ distinct=True,+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=ast.And(exprs=conditions),+ limit=ast.Constant(value=FREEZE_EXPOSURE_MAX_EXPOSED_USERS + 1),+ )+ try:+ with tags_context(+ product=Product.EXPERIMENTS,+ feature=Feature.COHORT,+ team_id=self.team.pk,+ org_id=self.team.organization_id,+ ):+ response = execute_hogql_query(+ query,+ team=self.team,+ settings=HogQLGlobalSettings(max_execution_time=FREEZE_EXPOSURE_QUERY_TIMEOUT_SECONDS),+ # Under the default LimitContext.QUERY the printer clamps any top-level LIMIT to+ # MAX_SELECT_RETURNED_ROWS (50k), which would silently truncate the snapshot and+ # keep the over-cap guard below from ever firing. COHORT_CALCULATION disables the+ # clamp so our explicit LIMIT (cap + 1) is what actually runs.+ limit_context=LimitContext.COHORT_CALCULATION,+ )+ except (+ ClickHouseQueryTimeOut,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ):+ # All three are "the scan is too big for a synchronous request" — timeout, memory+ # limit, and ClickHouse's own pre-execution time estimate — and get the same+ # friendly rejection instead of surfacing as a 500.+ raise ValidationError(+ "This experiment has too much exposure data to freeze instantly. "+ "Freezing very large or long-running experiments isn't supported yet."+ )++ if len(response.results) > FREEZE_EXPOSURE_MAX_EXPOSED_USERS:+ raise ValidationError(+ f"This experiment has too many exposed users (over {FREEZE_EXPOSURE_MAX_EXPOSED_USERS:,}) "+ "to freeze instantly. Freezing very large experiments isn't supported yet."+ )++ return [str(row[0]) for row in response.results]++ def _assert_exposed_persons_resolvable(self, person_uuids: list[str]) -> None:+ """Fail closed when a material share of the exposed set has no person profile.++ Cohort membership is person-keyed, and flag evaluation resolves distinct_id to person+ before checking it, so an exposed user without a person row (anonymous "personless"+ traffic, or a since-deleted person) can never match the snapshot cohort. The cohort+ insert silently skips such users, and post-freeze the narrowed flag stops serving them:+ freezing would break "everyone already enrolled keeps their variant" for exactly that+ share of the population. Typical for experiments exposed on logged-out surfaces, where+ the share can be the majority. A small unresolved share is tolerated as deletion/merge+ noise; beyond FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE the freeze is rejected, before any+ cohort is created.+ """+ resolved_count = len(validate_person_uuids_exist(self.team.id, person_uuids))+ unresolved_count = len(person_uuids) - resolved_count+ if unresolved_count == 0:+ return+ unresolved_share = unresolved_count / len(person_uuids)+ logger.warning(+ "experiment_freeze_exposure_unresolved_persons",+ team_id=self.team.pk,+ exposed_count=len(person_uuids),+ unresolved_count=unresolved_count,+ )+ if unresolved_share > FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE:+ raise ValidationError(+ f"{unresolved_count:,} of this experiment's {len(person_uuids):,} exposed users "+ f"({unresolved_share:.0%}) are anonymous or deleted, so they have no person profile and "+ "cannot be held in a cohort. Freezing would remove their variant. Freezing exposure "+ "requires an experiment whose exposed users are identified."+ )++ def _create_exposure_snapshot_cohort(self, experiment: Experiment, person_uuids: list[str]) -> Cohort:+ """Create a static cohort frozen to the given already-exposed persons (synchronous, no Celery).++ Static is required — behavioral cohorts are rejected by feature-flag validation, and a static+ snapshot is exactly what freezes enrollment.+ """+ cohort = Cohort.objects.create(+ team=self.team,+ name=f'{FREEZE_EXPOSURE_SNAPSHOT_NAME_PREFIX}"{experiment.name}"'[:400],+ is_static=True,+ created_by=self.user,+ )+ try:+ # raise_on_error: the batching helper otherwise swallows mid-batch failures and returns+ # normally, and a partially populated snapshot would evict every user missing from it.+ cohort.insert_users_list_by_uuid(person_uuids, team_id=self.team.id, raise_on_error=True)+ except Exception:+ # The cohort row exists but isn't referenced by anything yet — drop it so a failed+ # population doesn't leave an empty static cohort behind.+ cohort.delete()+ raise+ return cohort++ @staticmethod+ def _transform_filters_for_frozen_exposure(current_filters: dict, cohort_id: int) -> dict:+ """AND a static-cohort condition into every release group and stamp the freeze key.++ AND (not a new group): groups are OR'd, so a separate group would *widen* access.+ AND (not replace): the original per-group ``properties``/``rollout_percentage`` are+ preserved so a future unfreeze or manual revert strips back to exactly the original.+ The frozen state lives in the structured EXPOSURE_FROZEN_GROUP_KEY on each group;+ the marker is merely prepended to the (preserved) ``description`` as a human-readable+ note. Everything else (``multivariate``, ``payloads``, aggregation index) is left+ byte-for-byte.+ """+ cohort_condition = {"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}++ new_groups = []+ for group in current_filters.get("groups", []):+ # One deepcopy per group so the new filters never alias the original flag's dicts.+ new_group = deepcopy(group)+ new_group["properties"] = [*new_group.get("properties", []), cohort_condition]+ new_group[EXPOSURE_FROZEN_GROUP_KEY] = True+ new_group[EXPOSURE_FROZEN_COHORT_KEY] = cohort_id+ existing_description = new_group.get("description")+ new_group["description"] = (+ f"{EXPOSURE_FROZEN_GROUP_MARKER} {existing_description}"+ if existing_description+ else EXPOSURE_FROZEN_GROUP_MARKER+ )+ new_groups.append(new_group)+ return {**current_filters, "groups": new_groups}++ @staticmethod+ def _strip_frozen_exposure_from_filters(current_filters: dict) -> tuple[dict, list[int]]:+ """Inverse of _transform_filters_for_frozen_exposure: remove the freeze stamps from every+ release group — the AND'd snapshot-cohort condition (identified via the per-group+ EXPOSURE_FROZEN_COHORT_KEY, so user-added cohort conditions survive), the two structured+ keys, and the description marker note. Groups without the freeze key pass through untouched.++ Returns the stripped filters plus the snapshot cohort ids that were referenced, so callers+ can clean up the then-orphaned cohorts once the stripped filters are persisted — and only+ then: deleting earlier would yank the cohort from under a still-frozen flag if the save fails.+ """+ new_groups = []+ cohort_ids: list[int] = []+ for group in current_filters.get("groups", []):+ new_group = deepcopy(group)+ if new_group.get(EXPOSURE_FROZEN_GROUP_KEY) is not True:+ new_groups.append(new_group)+ continue+ new_group.pop(EXPOSURE_FROZEN_GROUP_KEY, None)+ cohort_id = new_group.pop(EXPOSURE_FROZEN_COHORT_KEY, None)+ if cohort_id is not None:+ cohort_ids.append(cohort_id)+ new_group["properties"] = [+ condition+ for condition in new_group.get("properties", [])+ if not (+ condition.get("type") == "cohort"+ and condition.get("key") == "id"+ and condition.get("value") == cohort_id+ )+ ]+ description = new_group.get("description")+ if isinstance(description, str) and EXPOSURE_FROZEN_GROUP_MARKER in description:+ stripped_description = description.replace(EXPOSURE_FROZEN_GROUP_MARKER, "").strip()+ if stripped_description:+ new_group["description"] = stripped_description+ else:+ # The freeze added the description outright — restore its absence.+ del new_group["description"]+ new_groups.append(new_group)+ return {**current_filters, "groups": new_groups}, list(dict.fromkeys(cohort_ids))++ def _delete_orphaned_snapshot_cohorts(self, cohort_ids: list[int]) -> None:+ """Soft-delete freeze snapshot cohorts whose flag reference was just removed.++ The ids come from the EXPOSURE_FROZEN_COHORT_KEY stamps in the flag's filters, which+ round-trip through the flag API and are therefore user-editable — treat them as claims,+ not facts. Only delete a cohort verifiable as an orphaned freeze snapshot: named like one,+ and no longer referenced by any active flag (the same protection the cohort API enforces+ on delete). Anything failing verification is skipped rather than fatal — a leftover+ cohort is cheaper than a blocked lifecycle action or a hijacked deletion.+ """+ for cohort in Cohort.objects.filter(team=self.team, pk__in=cohort_ids, is_static=True, deleted=False):+ if not cohort.name.startswith(FREEZE_EXPOSURE_SNAPSHOT_NAME_PREFIX):+ logger.warning(+ "experiment_freeze_snapshot_cleanup_skipped",+ cohort_id=cohort.pk,+ team_id=self.team.pk,+ reason="not_a_freeze_snapshot_name",+ )+ continue+ if get_active_flags_using_cohort(cohort):+ logger.warning(+ "experiment_freeze_snapshot_cleanup_skipped",+ cohort_id=cohort.pk,+ team_id=self.team.pk,+ reason="still_referenced_by_active_flags",+ )+ continue+ cohort.deleted = True+ cohort.save(update_fields=["deleted"])++ def _report_experiment_exposure_frozen(+ self,+ experiment: Experiment,+ *,+ request: Any | None = None,+ ) -> None:+ if request is None:+ return++ report_user_action(+ self.user,+ "experiment exposure frozen",+ experiment.get_analytics_metadata(),+ team=experiment.team,+ request=request,+ )+# ------------------------------------------------------------------# End# ------------------------------------------------------------------@@ -2000,13 +2473,17 @@ class ExperimentService:def reset_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:"""Reset an experiment back to draft state so it can be re-run.- The feature flag stays unchanged — users continue to see their assigned- variants. Only the experiment dates, conclusion, and archived flag are- cleared, moving the experiment back to draft state.+ The feature flag's user-configured targeting stays unchanged — users continue+ to see their assigned variants. The one exception is a frozen exposure: the+ machine-added snapshot-cohort narrowing is stripped and the snapshot cohort+ deleted, because a re-launched experiment would otherwise be born frozen+ against a stale snapshot and could never enroll anyone."""if experiment.is_draft:raise ValidationError("Experiment is already in draft state.")+ self._clear_frozen_exposure(experiment, request=request)+experiment.start_date = Noneexperiment.end_date = Noneexperiment.archived = False@@ -2019,6 +2496,52 @@ class ExperimentService:return experiment+ def _clear_frozen_exposure(self, experiment: Experiment, *, request: Any | None) -> None:+ """Strip the exposure-freeze narrowing (if any) off the experiment's flag and drop the+ snapshot cohorts.++ Checks the group stamps rather than ``is_exposure_frozen`` on purpose: stale stamps on a+ stopped or paused experiment's flag must be cleared too, or the relaunch is born frozen.++ Reads the flag under ``select_for_update`` (the caller runs in a transaction) so a reset+ serializes with freeze_exposure's phase 2: a freeze committing mid-reset would otherwise+ stamp the flag after this method saw it stamp-free, leaving a draft experiment born frozen.+ """+ flag = (+ FeatureFlag.objects.select_for_update()+ .filter(pk=experiment.feature_flag_id, team_id=experiment.team_id)+ .first()+ )+ if flag is None or flag.deleted:+ return+ stripped_filters, cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters or {})+ if stripped_filters == (flag.filters or {}):+ return++ if request is not None:+ flag_serializer = FeatureFlagSerializer(+ flag,+ data={"filters": stripped_filters},+ partial=True,+ context={+ "request": request,+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ },+ )+ flag_serializer.is_valid(raise_exception=True)+ flag_serializer.save()+ else:+ # FeatureFlagSerializer needs a real request for its context; for non-HTTP callers+ # write directly — flag caches still refresh via model save signals, only the flag's+ # activity-log entry is skipped.+ flag.filters = stripped_filters+ flag.save(update_fields=["filters"])++ flag.refresh_from_db()+ experiment.feature_flag = flag+ self._delete_orphaned_snapshot_cohorts(cohort_ids)+def _report_experiment_reset(self,experiment: Experiment,@@ -2090,8 +2613,14 @@ class ExperimentService:if not any(v["key"] == variant_key for v in variants):raise ValidationError(f"Variant '{variant_key}' not found on feature flag.")+ # A frozen experiment's release groups carry a machine-added snapshot-cohort condition.+ # Shipping a winner ends the enrollment freeze by definition, so strip it in the same flag+ # write: preserved, it would lock the shipped variant to the stale snapshot forever in the+ # default mode, and linger as dead weight below the catch-all in release_to_everyone mode.+ base_filters, frozen_cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters)+new_filters = self._transform_filters_for_winning_variant(- flag.filters, variant_key, release_to_everyone=release_to_everyone+ base_filters, variant_key, release_to_everyone=release_to_everyone)# Update the flag through the serializer to preserve the approval@@ -2116,6 +2645,12 @@ class ExperimentService:# the updated filters when serialized in the response.flag.refresh_from_db()+ # Only now that the stripped filters are persisted: the freeze snapshot cohorts are no+ # longer referenced by the flag, so clean them up. A failed save above (e.g.+ # ApprovalRequired) leaves the flag frozen and still serving from the cohorts.+ if frozen_cohort_ids:+ self._delete_orphaned_snapshot_cohorts(frozen_cohort_ids)+# End the experiment only if it's still runningwas_running = experiment.is_runningif was_running:@@ -2951,26 +3486,43 @@ class ExperimentService:status_enum = Noneif status_enum and status_enum != ExperimentQueryStatus.ALL:+ launched_unfinished = Q(status=Experiment.Status.RUNNING) | Q(+ status__isnull=True, start_date__isnull=False, end_date__isnull=True+ )+ # Frozen means EVERY release group is stamped (mirrors Experiment.is_exposure_frozen);+ # JSONB containment only tests "some group", so require that no group lacks the stamp.+ # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql+ all_groups_stamped = RawSQL(+ """EXISTS (+ SELECT 1 FROM posthog_featureflag ff+ WHERE ff.id = posthog_experiment.feature_flag_id+ AND jsonb_typeof(ff.filters -> 'groups') = 'array'+ AND jsonb_array_length(ff.filters -> 'groups') > 0+ AND NOT EXISTS (+ SELECT 1 FROM jsonb_array_elements(ff.filters -> 'groups') AS grp+ WHERE NOT (grp @> jsonb_build_object(%s, true))+ )+ )""",+ [EXPOSURE_FROZEN_GROUP_KEY],+ output_field=BooleanField(),+ )+ queryset = queryset.annotate(_all_groups_stamped=all_groups_stamped)+ exposure_frozen = Q(_all_groups_stamped=True)+if status_enum == ExperimentQueryStatus.DRAFT:queryset = queryset.filter(Q(status=Experiment.Status.DRAFT) | Q(status__isnull=True, start_date__isnull=True))elif status_enum == ExperimentQueryStatus.RUNNING:queryset = queryset.filter(- Q(feature_flag__active=True)- & (- Q(status=Experiment.Status.RUNNING)- | Q(status__isnull=True, start_date__isnull=False, end_date__isnull=True)- )+ Q(feature_flag__active=True) & launched_unfinished & ~exposure_frozen)elif status_enum == ExperimentQueryStatus.PAUSED:- queryset = queryset.filter(- Q(feature_flag__active=False)- & (- Q(status=Experiment.Status.RUNNING)- | Q(status__isnull=True, start_date__isnull=False, end_date__isnull=True)- )- )+ # Paused takes precedence over frozen (same as Experiment.is_exposure_frozen):+ # a deactivated flag serves no one, freeze stamps or not.+ queryset = queryset.filter(Q(feature_flag__active=False) & launched_unfinished)+ elif status_enum == ExperimentQueryStatus.EXPOSURE_FROZEN:+ queryset = queryset.filter(Q(feature_flag__active=True) & launched_unfinished & exposure_frozen)elif status_enum == ExperimentQueryStatus.STOPPED:queryset = queryset.filter(Q(status=Experiment.Status.STOPPED) | Q(status__isnull=True, end_date__isnull=False)diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.pyindex 5553f3cadce9..48494653c7e5 100644--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py@@ -248,6 +248,26 @@ def _build_property_filters(return [ast.And(exprs=property_filters)] if property_filters else []+def build_exposure_event_conditions(+ exposure_criteria: Union[ExperimentExposureCriteria, dict, None],+ team: Team,+ feature_flag_key: Optional[str],+) -> list[ast.Expr]:+ """+ Builds the event/action and property filters that define what counts as an exposure event —+ the exposure-identity subset of build_common_exposure_conditions, without the analysis-only+ conditions (date range, variant filter, test-account exclusion). Used directly by consumers+ that need "who was exposed" for serving decisions rather than metric analysis, such as the+ freeze-exposure snapshot scan.+ """+ criteria = normalize_to_exposure_criteria(exposure_criteria)+ exposure_config = criteria.exposure_config if criteria else None+ return [+ *_build_event_filters(exposure_config, team, feature_flag_key),+ *_build_property_filters(exposure_config, team),+ ]++def build_common_exposure_conditions(feature_flag_variant_property: str,variants: list[str],@@ -268,7 +288,6 @@ def build_common_exposure_conditions(feature_flag_key: Feature flag key (required for $feature_flag_called events)"""criteria = normalize_to_exposure_criteria(exposure_criteria)- exposure_config = criteria.exposure_config if criteria else Nonereturn [# Date range filters@@ -290,10 +309,8 @@ def build_common_exposure_conditions(),# Test accounts filter*get_test_accounts_filter(team, criteria),- # Event/action filters- *_build_event_filters(exposure_config, team, feature_flag_key),- # Property filters- *_build_property_filters(exposure_config, team),+ # Event/action and property filters+ *build_exposure_event_conditions(criteria, team, feature_flag_key),]diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex fb81f2555b12..1c1e184410f9 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -16,6 +16,22 @@ if TYPE_CHECKING:from posthog.models.team import Team+# Structured key stamped on each feature-flag release group when an experiment's exposure is frozen.+# Frozen-exposure state is derived from this key, not stored on the experiment — the same spirit as+# is_paused being derived from feature_flag.active rather than persisted. Unknown group keys pass+# through flag validation and are ignored by the Rust flag matcher, so this is additive metadata;+# that pass-through contract is pinned by test_flag_update_after_freeze_preserves_frozen_state.+EXPOSURE_FROZEN_GROUP_KEY = "exposure_frozen"++# Companion key recording which snapshot cohort the freeze AND-ed into the group, so unfreezing+# can remove exactly that condition even if users added their own cohort conditions meanwhile.+EXPOSURE_FROZEN_COHORT_KEY = "exposure_frozen_cohort"++# Human-readable note prepended to each release group's `description` when freezing. Purely+# informational — the description stays user-editable prose and carries no state.+EXPOSURE_FROZEN_GROUP_MARKER = "Added automatically when the experiment exposure was frozen to stop new enrollment."++class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):class ExperimentType(models.TextChoices):WEB = "web", "web"@@ -143,6 +159,24 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.# Pause is not stored on the experiment — it is the running state with the linked flag deactivated.return self.is_running and self.feature_flag_id is not None and not self.feature_flag.active+ @property+ def is_exposure_frozen(self) -> bool:+ # Frozen exposure is not stored on the experiment — it is the running state with the linked flag's+ # release groups narrowed to a static snapshot of the already-exposed cohort. We detect it from the+ # structured key stamped on each group when the cohort condition was AND'd in — the same predicate+ # the experiments list endpoint uses.+ if not self.is_running or self.feature_flag_id is None:+ return False+ # Paused takes precedence: a deactivated flag serves no one, so reporting "frozen" would+ # misdescribe the experiment and hide the pause/resume lifecycle (Resume only renders for+ # paused). The group stamps survive, so resuming lands back in the frozen state.+ if not self.feature_flag.active:+ return False+ # Enrollment is closed only when EVERY release group is stamped, so that add/edit groups+ # surfaces as the experiment reverting to "running".+ groups = (self.feature_flag.filters or {}).get("groups", [])+ return bool(groups) and all(group.get(EXPOSURE_FROZEN_GROUP_KEY) is True for group in groups)+@propertydef computed_status(self) -> "Experiment.Status":if self.is_stopped:@@ -153,8 +187,10 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.@propertydef status_label(self) -> str:- """Public status string (draft/running/paused/stopped) — single source for the API+ """Public status string (draft/running/paused/exposure_frozen/stopped) — single source for the APIserializer and dashboard widgets."""+ if self.is_exposure_frozen:+ return "exposure_frozen"if self.is_paused:return "paused"return self.status or self.computed_status.valuediff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 96963f3761fb..bbbcb734b64c 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -215,7 +215,9 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Modhelp_text=("Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature ""flag), 'paused' (running with feature flag deactivated — virtual state derived from "- "feature_flag.active, not stored), 'stopped' (ended)."+ "feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the "+ "already-exposed cohort while metrics keep flowing — virtual state derived from the flag's "+ "release groups, not stored), 'stopped' (ended)."),)is_legacy = serializers.SerializerMethodField(@@ -226,7 +228,7 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Mod),)- @extend_schema_field({"type": "string", "enum": ["draft", "running", "paused", "stopped"]})+ @extend_schema_field({"type": "string", "enum": ["draft", "running", "paused", "exposure_frozen", "stopped"]})def get_status(self, instance: Experiment) -> str:return instance.status_labeldiff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex e6381959202b..a0c9671af39f 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -213,12 +213,13 @@ def _slugify_feature_flag_key(name: str, *, team_id: int) -> str:name="status",location=OpenApiParameter.QUERY,type=str,- enum=["draft", "running", "paused", "stopped", "complete", "all"],+ enum=["draft", "running", "paused", "exposure_frozen", "stopped", "complete", "all"],description=(- 'Filter by experiment status. "running" and "paused" are mutually exclusive: "running" returns '- 'launched experiments with an active feature flag, "paused" returns launched experiments whose '- 'feature flag is deactivated. "complete" is an alias for "stopped". "all" disables status '- "filtering."+ 'Filter by experiment status. "running", "paused", and "exposure_frozen" are mutually exclusive: '+ '"running" returns launched experiments with an active feature flag, "paused" returns launched '+ 'experiments whose feature flag is deactivated, and "exposure_frozen" returns launched '+ "experiments whose exposure was frozen to the already-enrolled cohort while metrics keep "+ 'flowing. "complete" is an alias for "stopped". "all" disables status filtering.'),required=False,),@@ -620,6 +621,30 @@ class EnterpriseExperimentsViewSet(resumed_experiment = service.resume_experiment(experiment, request=request)return Response(ExperimentSerializer(resumed_experiment, context=self.get_serializer_context()).data)+ @extend_schema(+ request=None,+ responses=ExperimentSerializer,+ )+ @action(methods=["POST"], detail=True, required_scopes=["experiment:write"])+ def freeze_exposure(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """+ Freeze exposure on a running experiment while metrics keep flowing.++ Snapshots the already-exposed users into a static cohort and narrows the+ linked feature flag so only those users keep matching — new users can no+ longer enter the experiment. ``end_date`` is left null so long-term metrics+ (revenue/LTV/renewals/retention) keep accumulating. Enrolled users keep+ their assigned variant. The serialized status becomes 'exposure_frozen'.++ Returns 400 if the experiment is not running, exposure is already frozen,+ the experiment is group-aggregated (group flags cannot be frozen with a+ person cohort), or the exposed set is too large to snapshot synchronously.+ """+ experiment: Experiment = self.get_object()+ service = ExperimentService(team=self.team, user=request.user)+ frozen_experiment = service.freeze_exposure(experiment, request=request)+ return Response(ExperimentSerializer(frozen_experiment, context=self.get_serializer_context()).data)+@extend_schema(request=None,responses=ExperimentSerializer,diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex c3de069592d6..b075c5354ee0 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -1,4 +1,5 @@import json+from contextlib import contextmanagerfrom copy import deepcopyfrom datetime import timedeltafrom decimal import Decimal@@ -20,14 +21,23 @@ from posthog.schema import EventsNode, ExperimentMetricfrom posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSource+from posthog.exceptions import (+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+)from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.actions.backend.models.action import Action+from products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.models.experiment import (+ EXPOSURE_FROZEN_COHORT_KEY,+ EXPOSURE_FROZEN_GROUP_KEY,+ EXPOSURE_FROZEN_GROUP_MARKER,Experiment,ExperimentHoldout,ExperimentMetricResult,@@ -3048,6 +3058,568 @@ class TestExperimentService(APIBaseTest):with self.assertRaises(ValidationError):service.resume_experiment(experiment)+ # ------------------------------------------------------------------+ # Freeze exposure+ # ------------------------------------------------------------------++ def _stamp_exposure_frozen_marker(self, flag: FeatureFlag) -> None:+ filters = deepcopy(flag.filters)+ for group in filters.get("groups", []):+ group[EXPOSURE_FROZEN_GROUP_KEY] = True+ group["description"] = EXPOSURE_FROZEN_GROUP_MARKER+ flag.filters = filters+ flag.save()++ def _update_flag_filters(self, flag: FeatureFlag, filters: dict) -> None:+ serializer = FeatureFlagSerializer(+ flag,+ data={"filters": filters},+ partial=True,+ context={"request": self._make_request(), "team_id": self.team.id, "project_id": self.team.project_id},+ )+ serializer.is_valid(raise_exception=True)+ serializer.save()+ flag.refresh_from_db()++ @contextmanager+ def _stub_freeze_population(self, exposed_uuids: list[str] | None = None):+ uuids = exposed_uuids if exposed_uuids is not None else ["00000000-0000-0000-0000-000000000001"]+ with (+ patch.object(ExperimentService, "_fetch_exposed_person_uuids", return_value=uuids),+ # The stubbed uuids have no real persons behind them; treat them all as resolvable so+ # the personless guard doesn't reject these unrelated scenarios.+ patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ ),+ patch(+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0+ ) as mock_insert,+ ):+ yield mock_insert++ @parameterized.expand(+ [+ ("running_with_marker", "running", True, True),+ ("running_without_marker", "running", False, False),+ ("draft_with_marker", "draft", True, False),+ ("stopped_with_marker", "stopped", True, False),+ # Paused takes precedence: a deactivated flag serves no one, so "frozen" would+ # misdescribe the experiment and hide the pause/resume lifecycle in the UI.+ ("paused_with_marker", "paused", True, False),+ ]+ )+ def test_is_exposure_frozen_property(self, _name: str, state: str, marker: bool, expected: bool) -> None:+ if state == "draft":+ experiment = self._create_launchable_experiment(name="Exp Frozen Draft", feature_flag_key=f"ef-{_name}")+ elif state == "stopped":+ experiment = self._create_ended_experiment(name="Exp Frozen Stopped", feature_flag_key=f"ef-{_name}")+ else:+ experiment = self._create_running_experiment(name="Exp Frozen Running", feature_flag_key=f"ef-{_name}")++ if state == "paused":+ flag = experiment.feature_flag+ flag.active = False+ flag.save()++ if marker:+ self._stamp_exposure_frozen_marker(experiment.feature_flag)++ experiment.refresh_from_db()+ assert experiment.is_exposure_frozen is expected++ def test_freeze_exposure_success(self):+ experiment = self._create_running_experiment(name="Freeze Exposure", feature_flag_key="freeze-exposure-flag")+ original_variants = deepcopy(experiment.feature_flag.filters["multivariate"])++ with self._stub_freeze_population() as mock_insert:+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())++ frozen.feature_flag.refresh_from_db()++ # A static snapshot cohort was created and populated synchronously from the exposed set.+ cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Freeze Exposure"')+ assert cohort.is_static is True+ mock_insert.assert_called_once()++ # The cohort condition + freeze key + marker note were AND'd into every release group.+ groups = frozen.feature_flag.filters["groups"]+ assert len(groups) >= 1+ for group in groups:+ assert {"key": "id", "type": "cohort", "value": cohort.id, "operator": "in"} in group["properties"]+ assert group[EXPOSURE_FROZEN_GROUP_KEY] is True+ assert group[EXPOSURE_FROZEN_COHORT_KEY] == cohort.id+ assert EXPOSURE_FROZEN_GROUP_MARKER in group["description"]++ # Variants left byte-for-byte unchanged so enrolled users keep their variant.+ assert frozen.feature_flag.filters["multivariate"] == original_variants++ # Metrics keep flowing — not ended.+ assert frozen.end_date is None+ assert frozen.is_running is True+ assert frozen.is_exposure_frozen is True++ def test_freeze_exposure_multi_group_flag(self):+ experiment = self._create_running_experiment(name="Freeze Multi", feature_flag_key="freeze-multi-flag")+ flag = experiment.feature_flag++ # A catch-all group plus an internal test-user group (heterogeneous, like real experiment flags).+ catch_all = {"properties": [], "rollout_percentage": 100}+ internal_group = {+ "properties": [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}],+ "rollout_percentage": 100,+ "description": "Internal test users",+ }+ self._update_flag_filters(flag, {**flag.filters, "groups": [catch_all, internal_group]})++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ frozen.feature_flag.refresh_from_db()+ cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Freeze Multi"')++ groups = frozen.feature_flag.filters["groups"]+ assert len(groups) == 2+ cohort_condition = {"key": "id", "type": "cohort", "value": cohort.id, "operator": "in"}++ # Catch-all group: only the cohort condition added; description is just the marker note.+ assert groups[0]["properties"] == [cohort_condition]+ assert groups[0]["rollout_percentage"] == 100+ assert groups[0][EXPOSURE_FROZEN_GROUP_KEY] is True+ assert groups[0]["description"] == EXPOSURE_FROZEN_GROUP_MARKER++ # Internal group: original property preserved, cohort condition appended last, and the+ # user-authored description survives with the marker note prepended.+ assert len(groups[1]["properties"]) == 2+ assert groups[1]["properties"][-1] == cohort_condition+ assert groups[1]["properties"][0]["key"] == "email"+ assert groups[1]["rollout_percentage"] == 100+ assert groups[1][EXPOSURE_FROZEN_GROUP_KEY] is True+ assert groups[1]["description"] == f"{EXPOSURE_FROZEN_GROUP_MARKER} Internal test users"++ @parameterized.expand(+ [+ ("draft", "not been launched"),+ ("stopped", "already ended"),+ ("paused", "freeze a paused"),+ ("already_frozen", "already frozen"),+ ("group_aggregated", "Group-aggregated"),+ ("deleted_flag", "has been deleted"),+ ("no_groups", "no release conditions"),+ # Holdout assignment and early-access enrollment (super_groups) are evaluated by the+ # flag matcher before release conditions, so narrowing the release groups to a cohort+ # cannot stop enrollment through them — freezing must be rejected, not silently partial.+ ("holdout_linked", "holdout"),+ ("flag_holdout", "holdout"),+ ("flag_holdout_groups_legacy", "holdout"),+ ("flag_super_groups", "early access"),+ ]+ )+ def test_freeze_exposure_guards_raise(self, state: str, expected_error: str):+ service = self._service()+ if state == "draft":+ experiment = self._create_launchable_experiment(name="FE Draft", feature_flag_key=f"fe-{state}-flag")+ elif state == "stopped":+ experiment = self._create_ended_experiment(name="FE Stopped", feature_flag_key=f"fe-{state}-flag")+ else:+ experiment = self._create_running_experiment(name="FE Running", feature_flag_key=f"fe-{state}-flag")++ if state == "paused":+ # Paused = running with the flag deactivated; freezing must be rejected.+ flag = experiment.feature_flag+ flag.active = False+ flag.save()+ experiment.refresh_from_db()+ elif state == "already_frozen":+ self._stamp_exposure_frozen_marker(experiment.feature_flag)+ experiment.refresh_from_db()+ elif state == "group_aggregated":+ flag = experiment.feature_flag+ flag.filters = {**flag.filters, "aggregation_group_type_index": 0}+ flag.save()+ experiment.refresh_from_db()+ elif state == "deleted_flag":+ flag = experiment.feature_flag+ flag.deleted = True+ flag.save()+ experiment.refresh_from_db()+ elif state == "no_groups":+ flag = experiment.feature_flag+ flag.filters = {**flag.filters, "groups": []}+ flag.save()+ experiment.refresh_from_db()+ elif state == "holdout_linked":+ holdout = ExperimentHoldout.objects.create(+ team=self.team,+ name="FE Holdout",+ filters=[{"properties": [], "rollout_percentage": 10, "variant": "holdout"}],+ created_by=self.user,+ )+ experiment.holdout = holdout+ experiment.save()+ elif state == "flag_holdout":+ flag = experiment.feature_flag+ flag.filters = {**flag.filters, "holdout": {"id": 123, "exclusion_percentage": 10}}+ flag.save()+ experiment.refresh_from_db()+ elif state == "flag_holdout_groups_legacy":+ flag = experiment.feature_flag+ flag.filters = {**flag.filters, "holdout_groups": [{"properties": [], "rollout_percentage": 10}]}+ flag.save()+ experiment.refresh_from_db()+ elif state == "flag_super_groups":+ flag = experiment.feature_flag+ flag.filters = {**flag.filters, "super_groups": [{"properties": [], "rollout_percentage": 100}]}+ flag.save()+ experiment.refresh_from_db()++ # Population stubbed so any state that (wrongly) passes the guards would freeze successfully+ # instead of failing later for an unrelated reason like an empty exposed set.+ with self._stub_freeze_population():+ with self.assertRaises(ValidationError) as ctx:+ service.freeze_exposure(experiment, request=self._make_request())+ assert expected_error.lower() in str(ctx.exception).lower()++ def test_flag_update_after_freeze_preserves_frozen_state(self):+ experiment = self._create_running_experiment(name="Freeze Then Edit", feature_flag_key="freeze-edit-flag")+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ flag = frozen.feature_flag+ flag.refresh_from_db()++ # The frozen state rides on a non-schema group key, so it only survives as long as flag+ # validation keeps passing unknown group keys through. Pin that contract: an unrelated+ # flag edit sent the way the flag UI sends it — full filters payload included — must not+ # strip the freeze key. If this fails, someone added group-key whitelisting to+ # FeatureFlagSerializer and freezing needs a schema-level home for its state.+ edited_filters = deepcopy(flag.filters)+ edited_filters["groups"][0]["rollout_percentage"] = 50+ self._update_flag_filters(flag, edited_filters)++ frozen.refresh_from_db()+ assert flag.filters["groups"][0][EXPOSURE_FROZEN_GROUP_KEY] is True+ assert frozen.is_exposure_frozen is True++ def test_flag_update_adding_unstamped_group_reopens_exposure(self):+ experiment = self._create_running_experiment(name="Freeze Then Add Group", feature_flag_key="freeze-add-flag")+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ flag = frozen.feature_flag+ flag.refresh_from_db()++ # Release groups are OR'd, so a manually-added group without the freeze stamp (and without the+ # snapshot-cohort condition) lets new users enroll again. Freezing stamps every group, so the+ # experiment must report unfrozen the moment one unstamped group exists — otherwise the badge+ # keeps saying "exposure frozen" while enrollment is actually open.+ edited_filters = deepcopy(flag.filters)+ edited_filters["groups"].append({"properties": [], "rollout_percentage": 100})+ self._update_flag_filters(flag, edited_filters)++ frozen.refresh_from_db()+ # The original group keeps its stamp — only the freshly added group is unstamped.+ assert flag.filters["groups"][0][EXPOSURE_FROZEN_GROUP_KEY] is True+ assert EXPOSURE_FROZEN_GROUP_KEY not in flag.filters["groups"][1]+ assert frozen.is_exposure_frozen is False++ @parameterized.expand(+ [+ ("timeout", ClickHouseQueryTimeOut),+ ("memory_limit", ClickHouseQueryMemoryLimitExceeded),+ ("estimated_too_long", ClickHouseEstimatedQueryExecutionTimeTooLong),+ ]+ )+ def test_freeze_exposure_rejects_when_scan_is_too_big(self, _name: str, exception_class: type[Exception]):+ experiment = self._create_running_experiment(+ name=f"Freeze {_name}", feature_flag_key=f"freeze-{_name}-flag".replace("_", "-")+ )+ original_filters = deepcopy(experiment.feature_flag.filters)++ # All three "scan too big" ClickHouse errors must map to a friendly 400, not a 500.+ with patch(+ "products.experiments.backend.experiment_service.execute_hogql_query",+ side_effect=exception_class(),+ ):+ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert "too much exposure data" in str(ctx.exception)++ # Nothing was created or changed when the exposed-set scan times out.+ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == original_filters+ assert experiment.is_exposure_frozen is False++ @patch("products.experiments.backend.experiment_service.FREEZE_EXPOSURE_MAX_EXPOSED_USERS", 2)+ def test_freeze_exposure_rejects_when_too_many_exposed_users(self):+ experiment = self._create_running_experiment(name="Freeze Toobig", feature_flag_key="freeze-toobig-flag")+ original_filters = deepcopy(experiment.feature_flag.filters)++ # Cap patched to 2; the scan returns 3 distinct persons → rejected before any cohort is created.+ with patch(+ "products.experiments.backend.experiment_service.execute_hogql_query",+ return_value=MagicMock(results=[["a"], ["b"], ["c"]]),+ ):+ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert "too many exposed users" in str(ctx.exception)++ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == original_filters+ assert experiment.is_exposure_frozen is False++ def test_freeze_exposure_deletes_orphan_cohort_on_flag_save_failure(self):+ experiment = self._create_running_experiment(name="Freeze Failure", feature_flag_key="freeze-failure-flag")+ original_filters = deepcopy(experiment.feature_flag.filters)+ static_cohorts_before = Cohort.objects.filter(team=self.team, is_static=True).count()++ # Any failure persisting the narrowed flag must not leave the snapshot cohort behind.+ with self._stub_freeze_population():+ with patch.object(FeatureFlagSerializer, "save", side_effect=ValidationError("boom")):+ with self.assertRaises(ValidationError):+ self._service().freeze_exposure(experiment, request=self._make_request())++ # The orphaned snapshot cohort was cleaned up; the flag and experiment are untouched.+ assert Cohort.objects.filter(team=self.team, is_static=True).count() == static_cohorts_before+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == original_filters+ assert experiment.is_exposure_frozen is False++ def test_freeze_exposure_rejects_when_no_users_exposed(self):+ experiment = self._create_running_experiment(name="Freeze Empty", feature_flag_key="freeze-empty-flag")+ original_filters = deepcopy(experiment.feature_flag.filters)++ # An empty snapshot cohort ANDed into every release group would un-enroll every user with a+ # 200 response — the freeze must reject instead.+ with patch.object(ExperimentService, "_fetch_exposed_person_uuids", return_value=[]):+ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert "no users have been exposed" in str(ctx.exception).lower()++ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == original_filters+ assert experiment.is_exposure_frozen is False++ @parameterized.expand(+ [+ # 4 of 100 unresolvable: within the deletion-noise tolerance, the freeze proceeds.+ ("under_threshold", 4, False),+ # 6 of 100 unresolvable: a material personless share, the freeze must fail closed.+ ("over_threshold", 6, True),+ ]+ )+ def test_freeze_exposure_personless_share_guard(self, _name: str, unresolved: int, expect_rejection: bool):+ experiment = self._create_running_experiment(+ name=f"Freeze Personless {_name}", feature_flag_key=f"freeze-personless-{_name}"+ )+ uuids = [f"00000000-0000-0000-0000-{i:012d}" for i in range(100)]++ # Anonymous (personless) users have exposure events with a person_id but no person row, so+ # they can never match the snapshot cohort: a freeze whose exposed set is materially+ # personless would silently drop those users' variants and must be rejected instead.+ with (+ patch.object(ExperimentService, "_fetch_exposed_person_uuids", return_value=uuids),+ patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, batch: batch[unresolved:],+ ),+ patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),+ ):+ if expect_rejection:+ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert "anonymous or deleted" in str(ctx.exception)+ # Rejected before any snapshot was built: no cohort to clean up, flag untouched.+ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.is_exposure_frozen is False+ else:+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ assert frozen.is_exposure_frozen is True++ def test_freeze_exposure_fails_and_cleans_up_when_cohort_population_fails(self):+ experiment = self._create_running_experiment(name="Freeze Insert Fail", feature_flag_key="freeze-insert-flag")+ original_filters = deepcopy(experiment.feature_flag.filters)++ # A transient store failure mid-insert is swallowed by the cohort batching helper unless the+ # caller opts into raise_on_error. Fail the innermost batch write (not the public method) so+ # the real swallow path runs: the freeze must surface the failure and leave nothing behind,+ # never narrow the flag to a partially populated snapshot.+ with (+ patch.object(+ ExperimentService,+ "_fetch_exposed_person_uuids",+ return_value=["00000000-0000-0000-0000-000000000001"],+ ),+ patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ ),+ patch(+ "products.cohorts.backend.models.cohort.Cohort._insert_batch_via_personhog",+ side_effect=RuntimeError("clickhouse insert failed"),+ ),+ ):+ with self.assertRaises(RuntimeError):+ self._service().freeze_exposure(experiment, request=self._make_request())++ # The partially populated snapshot cohort was cleaned up; the flag and experiment are untouched.+ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == original_filters+ assert experiment.is_exposure_frozen is False++ def test_freeze_exposure_not_blocked_by_flag_approval_policy(self):+ experiment = self._create_running_experiment(name="Freeze Policy", feature_flag_key="freeze-policy-flag")++ # Flag approval policies are intentionally scoped to active/rollout_percentage changes.+ # Freezing exposure only edits group properties, so a flag-update approval policy must NOT+ # gate it — the freeze applies directly and no change request is raised.+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.update",+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())++ assert ChangeRequest.objects.filter(team=self.team).count() == 0+ frozen.feature_flag.refresh_from_db()+ assert frozen.is_exposure_frozen is True++ @patch("products.experiments.backend.experiment_service.report_user_action")+ def test_freeze_exposure_reports_analytics(self, mock_report: MagicMock):+ experiment = self._create_running_experiment(name="Freeze Analytics", feature_flag_key="freeze-analytics-flag")++ with self._stub_freeze_population():+ self._service().freeze_exposure(experiment, request=self._make_request())++ assert any(call.args[1] == "experiment exposure frozen" for call in mock_report.call_args_list)++ def test_pause_and_resume_frozen_experiment(self):+ experiment = self._create_running_experiment(name="Freeze Pause", feature_flag_key="freeze-pause-flag")+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ assert frozen.status_label == "exposure_frozen"++ # Pausing a frozen experiment must not wedge it: with the flag deactivated nothing is+ # served, so "paused" (with a working Resume) is the truthful state — a sticky "frozen"+ # label would hide the Resume action and leave Pause 400-ing with "already paused".+ paused = self._service().pause_experiment(frozen, request=self._make_request())+ assert paused.is_exposure_frozen is False+ assert paused.status_label == "paused"++ # The freeze stamps survive the roundtrip: resuming lands back in frozen, not running.+ resumed = self._service().resume_experiment(paused, request=self._make_request())+ assert resumed.is_exposure_frozen is True+ assert resumed.status_label == "exposure_frozen"++ def test_freeze_exposure_retains_cohort_and_second_freeze_raises(self):+ experiment = self._create_running_experiment(name="Freeze Retain", feature_flag_key="freeze-retain-flag")++ with self._stub_freeze_population():+ self._service().freeze_exposure(experiment, request=self._make_request())+ experiment.refresh_from_db()++ cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Freeze Retain"')+ filters_after_first = deepcopy(experiment.feature_flag.filters)++ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert "already frozen" in str(ctx.exception)++ # The snapshot cohort and frozen flag state are left intact (non-destructive).+ assert Cohort.objects.filter(pk=cohort.pk).exists()+ experiment.feature_flag.refresh_from_db()+ assert experiment.feature_flag.filters == filters_after_first++ @parameterized.expand(+ [+ ("concurrently_frozen", "already frozen"),+ ("flag_deleted", "has been deleted"),+ ("experiment_ended", "already ended"),+ ]+ )+ def test_freeze_exposure_rechecks_state_under_lock_and_cleans_up(self, race: str, expected_error: str):+ experiment = self._create_running_experiment(name=f"Freeze Race {race}", feature_flag_key=f"fr-{race}-flag")+ flag_id = experiment.feature_flag_id++ # The exposure scan + cohort build take long enough for another request to land in between.+ # Simulate that writer committing mid-scan: the guards must be re-run against the fresh rows+ # under the flag lock, and a failed freeze must clean up its own snapshot cohort.+ def concurrent_change_then_return(_experiment: Experiment) -> list[str]:+ if race == "concurrently_frozen":+ self._stamp_exposure_frozen_marker(FeatureFlag.objects.get(pk=flag_id))+ elif race == "flag_deleted":+ FeatureFlag.objects.filter(pk=flag_id).update(deleted=True)+ else:+ Experiment.objects.filter(pk=experiment.pk).update(end_date=timezone.now())+ return ["00000000-0000-0000-0000-000000000001"]++ with (+ patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_change_then_return),+ patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ ),+ patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),+ ):+ with self.assertRaises(ValidationError) as ctx:+ self._service().freeze_exposure(experiment, request=self._make_request())+ assert expected_error in str(ctx.exception)++ # The orphaned snapshot cohort was cleaned up and the flag was never narrowed to it.+ assert not Cohort.objects.filter(team=self.team, is_static=True).exists()+ flag = FeatureFlag.objects_including_soft_deleted.get(pk=flag_id)+ for group in flag.filters.get("groups", []):+ assert EXPOSURE_FROZEN_COHORT_KEY not in group++ def test_freeze_exposure_applies_to_filters_edited_during_snapshot_build(self):+ experiment = self._create_running_experiment(name="Freeze Race Edit", feature_flag_key="freeze-race-edit-flag")+ flag = experiment.feature_flag+ edited_filters = deepcopy(flag.filters)+ edited_filters["groups"] = [+ {+ "properties": [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}],+ "rollout_percentage": 50,+ }+ ]++ # A flag edit committing while the (slow) exposure scan runs must not be clobbered by a+ # transform computed from the pre-scan filters — the freeze must narrow the fresh groups.+ def concurrent_edit_then_return(_experiment: Experiment) -> list[str]:+ FeatureFlag.objects.filter(pk=flag.pk).update(filters=edited_filters)+ return ["00000000-0000-0000-0000-000000000001"]++ with (+ patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_edit_then_return),+ patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ ),+ patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),+ ):+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())++ cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Freeze Race Edit"')+ frozen.feature_flag.refresh_from_db()+ groups = frozen.feature_flag.filters["groups"]+ assert len(groups) == 1+ # The concurrent edit's condition and rollout survive, with the freeze ANDed on top.+ assert groups[0]["rollout_percentage"] == 50+ assert {"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"} in groups[0][+ "properties"+ ]+ assert {"key": "id", "type": "cohort", "value": cohort.id, "operator": "in"} in groups[0]["properties"]+ assert groups[0][EXPOSURE_FROZEN_GROUP_KEY] is True+# ------------------------------------------------------------------# Reset# ------------------------------------------------------------------@@ -3086,6 +3658,75 @@ class TestExperimentService(APIBaseTest):reset.feature_flag.refresh_from_db()assert reset.feature_flag.active is True+ @parameterized.expand(+ [+ ("running_frozen",),+ ("stopped_frozen",),+ ]+ )+ def test_reset_experiment_clears_freeze(self, state: str):+ experiment = self._create_running_experiment(name=f"Reset {state}", feature_flag_key=f"reset-{state}-flag")+ original_groups = deepcopy(experiment.feature_flag.filters["groups"])++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ cohort = Cohort.objects.get(team=self.team, name=f'Exposure snapshot for experiment "Reset {state}"')+ if state == "stopped_frozen":+ # Ending intentionally leaves the flag untouched, so the stamps are still on the+ # groups even though the stopped experiment no longer reports exposure_frozen —+ # reset must strip them regardless, or the relaunch is born frozen.+ self._service().end_experiment(frozen, request=self._make_request())++ reset = self._service().reset_experiment(frozen, request=self._make_request())++ # A re-launched experiment must start fresh: left frozen against the stale snapshot,+ # it could never enroll anyone.+ assert reset.is_draft+ reset.feature_flag.refresh_from_db()+ assert reset.feature_flag.filters["groups"] == original_groups+ cohort.refresh_from_db()+ assert cohort.deleted is True++ @parameterized.expand(+ [+ ("referenced_by_another_flag", 'Exposure snapshot for experiment "Victim"'),+ ("not_a_snapshot_name", "Payment-tier customers"),+ ]+ )+ def test_reset_does_not_delete_stamped_foreign_cohorts(self, case: str, victim_name: str):+ experiment = self._create_running_experiment(name=f"Reset Stamp {case}", feature_flag_key=f"rs-{case}-flag")+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())++ # The freeze stamps round-trip through the flag API, so a flag editor can point them at+ # any cohort. Cleanup must verify ownership instead of deleting whatever id is stamped.+ victim = Cohort.objects.create(team=self.team, name=victim_name, is_static=True, created_by=self.user)+ if case == "referenced_by_another_flag":+ FeatureFlag.objects.create(+ team=self.team,+ key=f"other-flag-{case}",+ created_by=self.user,+ active=True,+ filters={+ "groups": [+ {+ "properties": [{"key": "id", "type": "cohort", "value": victim.pk, "operator": "in"}],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ flag = frozen.feature_flag+ tampered = deepcopy(flag.filters)+ tampered["groups"][0][EXPOSURE_FROZEN_COHORT_KEY] = victim.pk+ flag.filters = tampered+ flag.save()++ self._service().reset_experiment(frozen, request=self._make_request())++ victim.refresh_from_db()+ assert victim.deleted is False+def test_reset_draft_experiment_raises(self):experiment = self._create_launchable_experiment(name="Reset Draft", feature_flag_key="reset-draft-flag")@@ -3169,6 +3810,76 @@ class TestExperimentService(APIBaseTest):assert "Added automatically" in groups[0].get("description", "")assert groups[1:] == original_groups+ @parameterized.expand(+ [+ ("preserve_targeting", False),+ ("release_to_everyone", True),+ ]+ )+ def test_ship_variant_on_frozen_experiment_strips_freeze(self, _name: str, release_to_everyone: bool):+ experiment = self._create_running_experiment(+ name=f"Ship Frozen {_name}", feature_flag_key=f"ship-frozen-{_name}-flag"+ )+ flag = experiment.feature_flag++ # Heterogeneous groups (like real experiment flags) so the round-trip below proves the+ # freeze's cohort condition, structured keys, and description marker are all stripped+ # while user-authored properties and descriptions survive.+ catch_all = {"properties": [], "rollout_percentage": 100}+ internal_group = {+ "properties": [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}],+ "rollout_percentage": 100,+ "description": "Internal test users",+ }+ self._update_flag_filters(flag, {**flag.filters, "groups": [catch_all, internal_group]})+ original_groups = deepcopy(flag.filters["groups"])++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ cohort = Cohort.objects.get(team=self.team, name=f'Exposure snapshot for experiment "Ship Frozen {_name}"')++ shipped = self._service().ship_variant(+ frozen,+ variant_key="test",+ release_to_everyone=release_to_everyone,+ request=self._make_request(),+ )+ shipped.feature_flag.refresh_from_db()++ groups = shipped.feature_flag.filters["groups"]+ if release_to_everyone:+ assert groups[0]["properties"] == []+ assert groups[0]["rollout_percentage"] == 100+ # The frozen snapshot condition below the catch-all is stripped, not left as dead weight.+ assert groups[1:] == original_groups+ else:+ # Shipping ends the enrollment freeze: the winner reaches the original audience, not+ # just the stale snapshot cohort.+ assert groups == original_groups++ # The snapshot cohort is no longer referenced by anything the freeze created — cleaned up.+ cohort.refresh_from_db()+ assert cohort.deleted is True++ def test_ship_variant_on_frozen_experiment_keeps_cohort_when_flag_save_fails(self):+ experiment = self._create_running_experiment(name="Ship Frozen Fail", feature_flag_key="ship-frozen-fail-flag")+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Ship Frozen Fail"')+ filters_when_frozen = deepcopy(frozen.feature_flag.filters)++ # If persisting the shipped flag fails (e.g. ApprovalRequired surfacing as a 409), the flag+ # is still frozen and serving from the snapshot — the cohort must not be deleted from under it.+ with patch.object(FeatureFlagSerializer, "save", side_effect=ValidationError("boom")):+ with self.assertRaises(ValidationError):+ self._service().ship_variant(frozen, variant_key="test", request=self._make_request())++ cohort.refresh_from_db()+ assert cohort.deleted is not True+ frozen.feature_flag.refresh_from_db()+ assert frozen.feature_flag.filters == filters_when_frozen+ assert frozen.is_exposure_frozen is True+def test_ship_variant_default_preserves_scoped_release_condition(self):experiment = self._create_running_experiment(name="Ship Scoped", feature_flag_key="ship-scoped-flag")diff --git a/products/experiments/backend/test/test_freeze_exposure_clickhouse.py b/products/experiments/backend/test/test_freeze_exposure_clickhouse.pynew file mode 100644index 000000000000..28f70c17abd3--- /dev/null+++ b/products/experiments/backend/test/test_freeze_exposure_clickhouse.py@@ -0,0 +1,181 @@+from datetime import datetime, timedelta++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch++from django.utils import timezone++from rest_framework.exceptions import ValidationError++from posthog.models.person import Person++from products.experiments.backend.experiment_service import ExperimentService+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++# ClickHouse-backed correctness proof for the bounded exposed-set scan (`_fetch_exposed_person_uuids`),+# the one freeze_exposure path the unit tests stub. The matching side of the freeze (a static-cohort+# condition gates new users while enrolled users keep their variant) is owned by the Rust flags service —+# see test_static_cohort_matching_* in rust/feature-flags/src/flags/test_flag_matching.rs.+class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):+ def _create_running_experiment(self, flag_key: str, exposure_criteria: dict | None = None) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=flag_key,+ name=f"Flag {flag_key}",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ )+ return Experiment.objects.create(+ name=f"Experiment {flag_key}",+ team=self.team,+ feature_flag=flag,+ start_date=timezone.now() - timedelta(days=7),+ created_by=self.user,+ exposure_criteria=exposure_criteria or {},+ )++ def _expose_person(+ self,+ distinct_id: str,+ flag_key: str,+ timestamp: datetime,+ *,+ event: str = "$feature_flag_called",+ variant: str | None = "test",+ extra_properties: dict | None = None,+ ) -> Person:+ """Create a person plus an exposure event shaped like the real SDK payloads:+ $feature_flag_called carries $feature_flag/$feature_flag_response, any other+ (custom exposure) event carries the $feature/<key> enrollment property."""+ person = _create_person(team=self.team, distinct_ids=[distinct_id])+ if event == "$feature_flag_called":+ properties: dict = {"$feature_flag": flag_key}+ if variant is not None:+ properties["$feature_flag_response"] = variant+ else:+ properties = {f"$feature/{flag_key}": variant} if variant is not None else {}+ _create_event(+ team=self.team,+ event=event,+ distinct_id=distinct_id,+ properties={**properties, **(extra_properties or {})},+ timestamp=timestamp,+ )+ return person++ def _service(self) -> ExperimentService:+ return ExperimentService(team=self.team, user=self.user)++ def test_fetch_exposed_person_uuids_returns_only_the_exposed_set(self) -> None:+ experiment = self._create_running_experiment("freeze-fetch-flag")+ assert experiment.start_date is not None+ exposed_at = experiment.start_date + timedelta(days=1)++ exposed_1 = self._expose_person("exposed-1", "freeze-fetch-flag", exposed_at, variant="control")+ exposed_2 = self._expose_person("exposed-2", "freeze-fetch-flag", exposed_at)+ # Exposure to a different flag doesn't count.+ self._expose_person("other-flag-user", "some-other-flag", exposed_at)+ # Exposure before the experiment started doesn't count.+ self._expose_person("pre-start-user", "freeze-fetch-flag", experiment.start_date - timedelta(days=1))+ # A $feature_flag_called that landed no variant (user outside the rollout) is not an+ # enrollment — mirroring the metrics exposure definition.+ self._expose_person("no-variant-user", "freeze-fetch-flag", exposed_at, variant=None)+ flush_persons_and_events()++ uuids = self._service()._fetch_exposed_person_uuids(experiment)++ assert sorted(uuids) == sorted([str(exposed_1.uuid), str(exposed_2.uuid)])++ def test_fetch_exposed_person_uuids_honors_custom_exposure_criteria(self) -> None:+ experiment = self._create_running_experiment(+ "freeze-custom-flag",+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ },+ )+ assert experiment.start_date is not None+ exposed_at = experiment.start_date + timedelta(days=1)++ exposed = self._expose_person("custom-exposed", "freeze-custom-flag", exposed_at, event="checkout started")+ # With a custom exposure event configured, plain $feature_flag_called events don't count —+ # teams configure this exactly because those events are absent or unreliable for them.+ self._expose_person("flag-called-only", "freeze-custom-flag", exposed_at)+ # A custom exposure event fired outside the experiment (no enrollment property) doesn't count.+ self._expose_person(+ "custom-no-variant", "freeze-custom-flag", exposed_at, event="checkout started", variant=None+ )+ flush_persons_and_events()++ uuids = self._service()._fetch_exposed_person_uuids(experiment)++ assert uuids == [str(exposed.uuid)]++ def test_fetch_exposed_person_uuids_ignores_test_account_filters(self) -> None:+ # filterTestAccounts shapes which exposures are *analyzed*; the snapshot decides who keeps+ # being *served* a variant. Applying it here would evict the team's own users at freeze+ # time, so the scan must ignore it even when the criteria enable it.+ self.team.test_account_filters = [+ {"key": "$host", "type": "event", "operator": "not_icontains", "value": "localhost"}+ ]+ self.team.save()+ experiment = self._create_running_experiment(+ "freeze-testacct-flag", exposure_criteria={"filterTestAccounts": True}+ )+ assert experiment.start_date is not None+ exposed_at = experiment.start_date + timedelta(days=1)++ internal = self._expose_person(+ "internal-user", "freeze-testacct-flag", exposed_at, extra_properties={"$host": "localhost:8010"}+ )+ flush_persons_and_events()++ uuids = self._service()._fetch_exposed_person_uuids(experiment)++ assert uuids == [str(internal.uuid)]++ def test_fetch_exposed_person_uuids_is_not_clamped_by_default_query_limit(self) -> None:+ experiment = self._create_running_experiment("freeze-clamp-flag")+ assert experiment.start_date is not None+ exposed_at = experiment.start_date + timedelta(days=1)++ exposed = [self._expose_person(f"exposed-{i}", "freeze-clamp-flag", exposed_at) for i in range(4)]+ flush_persons_and_events()++ # Under the default limit context the HogQL printer rewrites any top-level LIMIT to+ # min(limit, MAX_SELECT_RETURNED_ROWS) — patched to 2 here so a clamp would truncate the+ # snapshot to half the enrolled users without any error. The scan must bypass that clamp:+ # a silently truncated snapshot evicts every user not in it the moment the flag narrows.+ with patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 2):+ uuids = self._service()._fetch_exposed_person_uuids(experiment)++ assert sorted(uuids) == sorted(str(person.uuid) for person in exposed)++ @patch("products.experiments.backend.experiment_service.FREEZE_EXPOSURE_MAX_EXPOSED_USERS", 2)+ def test_fetch_exposed_person_uuids_rejects_over_cap_exposed_set(self) -> None:+ experiment = self._create_running_experiment("freeze-overcap-flag")+ assert experiment.start_date is not None+ exposed_at = experiment.start_date + timedelta(days=1)++ for i in range(4):+ self._expose_person(f"exposed-{i}", "freeze-overcap-flag", exposed_at)+ flush_persons_and_events()++ # End-to-end proof that the real query returns cap+1 rows so the over-cap guard can fire —+ # the unit-level guard test mocks the query response, so it can't catch a LIMIT regression.+ with self.assertRaises(ValidationError) as ctx:+ self._service()._fetch_exposed_person_uuids(experiment)+ assert "too many exposed users" in str(ctx.exception)diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 54bd289351f3..afff0ec56fb7 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -28,6 +28,8 @@ from products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import (+ EXPOSURE_FROZEN_GROUP_KEY,+ EXPOSURE_FROZEN_GROUP_MARKER,Experiment,ExperimentHoldout,ExperimentSavedMetric,@@ -147,6 +149,8 @@ class TestExperimentCRUD(APILicensedTest):[("draft", "draft"),("running", "running"),+ ("exposure_frozen", "exposure_frozen"),+ ("paused", "paused"),("stopped", "stopped"),("complete", "stopped"),]@@ -179,6 +183,48 @@ class TestExperimentCRUD(APILicensedTest):"parameters": None,},)+ # A running experiment with the freeze marker on its flag groups: must show up only under+ # exposure_frozen — and its presence proves the running filter excludes frozen experiments.+ self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Frozen experiment",+ "feature_flag_key": "frozen-filter-flag",+ "start_date": "2021-12-01T10:23",+ "parameters": None,+ },+ )+ frozen_flag = FeatureFlag.objects.get(team=self.team, key="frozen-filter-flag")+ frozen_flag.filters = {+ **frozen_flag.filters,+ "groups": [+ {**group, EXPOSURE_FROZEN_GROUP_KEY: True, "description": EXPOSURE_FROZEN_GROUP_MARKER}+ for group in frozen_flag.filters.get("groups", [])+ ],+ }+ frozen_flag.save()+ # A frozen experiment that was then paused (flag deactivated, stamps still on the groups):+ # paused takes precedence, so it must show up under paused — not under exposure_frozen,+ # where it would misreport a flag that serves no one as still holding variants.+ self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Paused frozen experiment",+ "feature_flag_key": "paused-frozen-filter-flag",+ "start_date": "2021-12-01T10:23",+ "parameters": None,+ },+ )+ paused_frozen_flag = FeatureFlag.objects.get(team=self.team, key="paused-frozen-filter-flag")+ paused_frozen_flag.filters = {+ **paused_frozen_flag.filters,+ "groups": [+ {**group, EXPOSURE_FROZEN_GROUP_KEY: True, "description": EXPOSURE_FROZEN_GROUP_MARKER}+ for group in paused_frozen_flag.filters.get("groups", [])+ ],+ }+ paused_frozen_flag.active = False+ paused_frozen_flag.save()response = self.client.get(f"/api/projects/{self.team.id}/experiments/?status={status_filter}")@@ -186,6 +232,44 @@ class TestExperimentCRUD(APILicensedTest):self.assertEqual(response.json()["count"], 1)self.assertEqual(response.json()["results"][0]["status"], expected_status)+ def test_status_filter_treats_partially_stamped_flag_as_running(self) -> None:+ # A frozen flag with a manually-added unstamped group reopens enrollment through that group.+ # The status filter must classify it the same way Experiment.is_exposure_frozen does (all groups+ # stamped, not just some): running, not exposure_frozen. Guards the list query against regressing+ # to a "some group is stamped" JSONB-containment match.+ create_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Reopened experiment",+ "feature_flag_key": "reopened-filter-flag",+ "start_date": "2021-12-01T10:23",+ "parameters": None,+ },+ )+ experiment_id = create_response.json()["id"]+ flag = FeatureFlag.objects.get(team=self.team, key="reopened-filter-flag")+ flag.filters = {+ **flag.filters,+ "groups": [+ *(+ {**group, EXPOSURE_FROZEN_GROUP_KEY: True, "description": EXPOSURE_FROZEN_GROUP_MARKER}+ for group in flag.filters.get("groups", [])+ ),+ {"properties": [], "rollout_percentage": 100},+ ],+ }+ flag.save()++ frozen_ids = [e["id"] for e in self._status_filter_results("exposure_frozen")]+ running_ids = [e["id"] for e in self._status_filter_results("running")]+ assert experiment_id not in frozen_ids+ assert experiment_id in running_ids++ def _status_filter_results(self, status_filter: str) -> list[dict[str, Any]]:+ response = self.client.get(f"/api/projects/{self.team.id}/experiments/?status={status_filter}")+ assert response.status_code == status.HTTP_200_OK+ return response.json()["results"]+def _create_experiment_with_metric_event(self, name: str, flag_key: str, event: str) -> Experiment:flag = FeatureFlag.objects.create(team=self.team,@@ -5528,6 +5612,69 @@ class TestExperimentCRUD(APILicensedTest):)self.assertEqual(pause_response.status_code, status.HTTP_400_BAD_REQUEST)+ @patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0)+ @patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ )+ @patch(+ "products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",+ return_value=["00000000-0000-0000-0000-000000000001"],+ )+ def test_freeze_exposure_endpoint(self, mock_fetch: MagicMock, mock_insert: MagicMock) -> None:+ data = self._create_running_experiment(name="Freeze Endpoint", flag_key="freeze-endpoint-flag")+ experiment_id = data["id"]++ freeze_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/freeze_exposure/",+ )+ self.assertEqual(freeze_response.status_code, status.HTTP_200_OK)+ body = freeze_response.json()+ # Frozen exposure is still running under the hood — precedence puts exposure_frozen first.+ self.assertEqual(body["status"], "exposure_frozen")+ # Unlike pause, the flag stays active; unlike end, end_date stays null so metrics keep flowing.+ self.assertIsNone(body["end_date"])+ self.assertTrue(body["feature_flag"]["active"])++ # A frozen-but-still-running experiment also serializes as exposure_frozen on GET.+ get_response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)+ self.assertEqual(get_response.json()["status"], "exposure_frozen")++ @patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0)+ @patch(+ "products.experiments.backend.experiment_service.validate_person_uuids_exist",+ new=lambda team_id, uuids: uuids,+ )+ @patch(+ "products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",+ return_value=["00000000-0000-0000-0000-000000000001"],+ )+ def test_freeze_exposure_already_frozen_returns_400(self, mock_fetch: MagicMock, mock_insert: MagicMock) -> None:+ data = self._create_running_experiment(name="Double Freeze", flag_key="double-freeze-flag")+ experiment_id = data["id"]++ self.client.post(f"/api/projects/{self.team.id}/experiments/{experiment_id}/freeze_exposure/")++ second_freeze = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/freeze_exposure/",+ )+ self.assertEqual(second_freeze.status_code, status.HTTP_400_BAD_REQUEST)++ def test_freeze_exposure_draft_returns_400(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {"name": "Freeze Draft", "feature_flag_key": "freeze-draft-flag"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ experiment_id = response.json()["id"]++ freeze_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/freeze_exposure/",+ )+ self.assertEqual(freeze_response.status_code, status.HTTP_400_BAD_REQUEST)+def test_end_experiment_endpoint(self):data = self._create_running_experiment(name="End Endpoint", flag_key="end-endpoint-flag")experiment_id = data["id"]diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 622c80b38993..507f6c504235 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -726,6 +726,7 @@ export const ExperimentStatusEnumApi = {Draft: 'draft',Running: 'running',Paused: 'paused',+ ExposureFrozen: 'exposure_frozen',Stopped: 'stopped',} as const@@ -803,7 +804,7 @@ export interface ExperimentBasicApi {* @nullable*/conclusion_comment?: string | null- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean@@ -1434,7 +1435,7 @@ export interface ExperimentWriteApi {only_count_matured_users?: boolean/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean@@ -1540,7 +1541,7 @@ export interface ExperimentApi {only_count_matured_users?: boolean/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean@@ -1642,7 +1643,7 @@ export interface PatchedExperimentWriteApi {only_count_matured_users?: boolean/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnumApi/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy?: boolean@@ -2123,7 +2124,7 @@ export type ExperimentsListParams = {*/search?: string/**- * Filter by experiment status. "running" and "paused" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated. "complete" is an alias for "stopped". "all" disables status filtering.+ * Filter by experiment status. "running", "paused", and "exposure_frozen" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated, and "exposure_frozen" returns launched experiments whose exposure was frozen to the already-enrolled cohort while metrics keep flowing. "complete" is an alias for "stopped". "all" disables status filtering.*/status?: ExperimentsListStatus}@@ -2134,6 +2135,7 @@ export const ExperimentsListStatus = {All: 'all',Complete: 'complete',Draft: 'draft',+ ExposureFrozen: 'exposure_frozen',Paused: 'paused',Running: 'running',Stopped: 'stopped',diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 35e5ec633b61..dfa0c1bd2d55 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -540,6 +540,34 @@ export const experimentsEndCreate = async (})}+export const getExperimentsFreezeExposureCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/freeze_exposure/`+}++/**+ * Freeze exposure on a running experiment while metrics keep flowing.+ *+ * Snapshots the already-exposed users into a static cohort and narrows the+ * linked feature flag so only those users keep matching — new users can no+ * longer enter the experiment. ``end_date`` is left null so long-term metrics+ * (revenue/LTV/renewals/retention) keep accumulating. Enrolled users keep+ * their assigned variant. The serialized status becomes 'exposure_frozen'.+ *+ * Returns 400 if the experiment is not running, exposure is already frozen,+ * the experiment is group-aggregated (group flags cannot be frozen with a+ * person cohort), or the exposed set is too large to snapshot synchronously.+ */+export const experimentsFreezeExposureCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentApi> => {+ return apiMutator<ExperimentApi>(getExperimentsFreezeExposureCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getExperimentsLaunchCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/launch/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex aea8895b9931..1bf3f6f102a2 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -339,11 +339,13 @@ tools:user's reference first.- Returns the full experiment object including: status (draft/running/paused/stopped — "paused" is a virtual- value returned when the experiment is launched but its feature flag has been deactivated), start_date and- end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays,- conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and- recommended_running_time), stats_config, and type (web/product).+ Returns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped —+ "paused" is a virtual value returned when the experiment is launched but its feature flag has been+ deactivated, "exposure_frozen" when its flag's release groups are narrowed to the already-exposed cohort so+ enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with+ variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if+ ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, and type+ (web/product).param_overrides:id:cast: string-int@@ -539,17 +541,18 @@ tools:the finding-experiments skill for guidance on searching by name, status, recency, or description.- Supports filtering by status ("draft", "running", "paused", "stopped", "complete" which maps to stopped, or- "all"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on- name. Supports ordering by an allowlisted set of fields (model fields plus computed "duration" and- "status"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics- summary. Use the returned ID for get/update/lifecycle tools.+ Supports filtering by status ("draft", "running", "paused", "exposure_frozen", "stopped", "complete" which+ maps to stopped, or "all"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and+ free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed+ "duration" and "status"). Returns paginated results with each experiment's status, dates, feature flag key,+ and metrics summary. Use the returned ID for get/update/lifecycle tools.param_overrides:status:description: >Filter by experiment status. Values: "draft" (not yet launched), "running" (launched, flag active),- "paused" (launched, flag deactivated — mutually exclusive with running), "stopped" or "complete"- (both mean ended), "all" (no filter). Defaults to all non-archived experiments.+ "paused" (launched, flag deactivated — mutually exclusive with running), "exposure_frozen"+ (launched, enrollment frozen to the already-exposed cohort while metrics keep flowing), "stopped" or+ "complete" (both mean ended), "all" (no filter). Defaults to all non-archived experiments.limit:cast: string-intoffset:@@ -1031,6 +1034,9 @@ tools:experiments-eligible-feature-flags:operation: experiments_eligible_feature_flags_retrieveenabled: false+ experiments-freeze-exposure-create:+ operation: experiments_freeze_exposure_create+ enabled: falseexperiments-metrics-recalculation-create:operation: experiments_metrics_recalculation_createenabled: falsediff --git a/products/experiments/skills/diagnosing-experiment-results/SKILL.md b/products/experiments/skills/diagnosing-experiment-results/SKILL.mdindex e1b8c34dda97..fd81f040d71e 100644--- a/products/experiments/skills/diagnosing-experiment-results/SKILL.md+++ b/products/experiments/skills/diagnosing-experiment-results/SKILL.md@@ -27,7 +27,7 @@ Call `experiment-get` and pull these fields. They are inputs for almost every di- `exposure_criteria.multiple_variant_handling` — defaults to `"exclude"` if absent- `exposure_criteria.exposure_event` — `null` means default `$feature_flag_called`- `exposure_criteria.filterTestAccounts` — defaults to `true`-- `feature_flag.active`, status (`draft` / `running` / `paused` / `stopped`), `start_date`, `end_date`+- `feature_flag.active`, status (`draft` / `running` / `paused` / `exposure_frozen` / `stopped`), `start_date`, `end_date`- `feature_flag.filters.groups[]` — for each group read `variant`, `properties`, and`rollout_percentage`. Any non-null `variant` is a forced-variant override on the matched cohort(release-condition assignment, not randomized) — surfaces A7. Watch for the severe shape (A7b): adiff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex f9cd4441feea..30c2fc7c1a53 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -2916,6 +2916,162 @@ mod tests {);}+ fn flag_with_group(+ team_id: TeamId,+ group: FlagPropertyGroup,+ multivariate: MultivariateFlagOptions,+ ) -> FeatureFlag {+ mock!(FeatureFlag,+ team_id: team_id,+ key: "freeze-flag".mock_into(),+ filters: FlagFilters {+ groups: vec![group],+ multivariate: Some(multivariate),+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: None,+ extra: Default::default(),+ }+ )+ }++ async fn evaluate_flag(+ context: &TestContext,+ team_id: TeamId,+ cohort_cache: &Arc<CohortCacheManager>,+ distinct_id: &str,+ flag: &FeatureFlag,+ ) -> FeatureFlagMatch {+ let mut matcher = FeatureFlagMatcher::new(+ distinct_id.to_string(),+ None,+ team_id,+ context.create_postgres_router(),+ cohort_cache.clone(),+ empty_group_type_cache(),+ None,+ );+ matcher+ .prepare_flag_evaluation_state(&[flag])+ .await+ .unwrap();+ matcher.get_match(flag, None, None, None, &None).unwrap()+ }++ #[tokio::test]+ async fn test_frozen_exposure_flag_keeps_enrolled_variant_and_excludes_new_user() {+ // Correctness proof for the experiments "freeze exposure" action against the real matcher.+ // Freezing AND-s a static-cohort condition into every existing multivariate release group+ // (products/experiments/backend/experiment_service.py::_transform_filters_for_frozen_exposure).+ // The user-facing guarantee: an already-exposed user (in the snapshot cohort) keeps matching+ // AND keeps the exact same variant, while a brand-new user (not in the cohort) no longer matches.+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let cohort = context+ .insert_cohort(+ team.id,+ Some("Exposure snapshot".to_string()),+ json!({}),+ true,+ )+ .await+ .unwrap();++ // The enrolled user is in the snapshot cohort; the new user is not.+ let enrolled_id = "enrolled_user".to_string();+ let new_id = "new_user".to_string();+ for distinct_id in [&enrolled_id, &new_id] {+ context+ .insert_person(team.id, distinct_id.clone(), None)+ .await+ .unwrap();+ }+ let enrolled_person_id = context+ .get_person_id_by_distinct_id(team.id, &enrolled_id)+ .await+ .unwrap();+ context+ .add_person_to_cohort(cohort.id, enrolled_person_id)+ .await+ .unwrap();++ // Both flags share this 50/50 split; freezing must not perturb it.+ let multivariate = MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ name: Some("Control".to_string()),+ key: "control".to_string(),+ rollout_percentage: 50.0,+ },+ MultivariateFlagVariant {+ name: Some("Test".to_string()),+ key: "test".to_string(),+ rollout_percentage: 50.0,+ },+ ],+ };++ // Open flag: one catch-all group at 100%, everyone matches.+ let open_group = FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ ..Default::default()+ };++ // Frozen flag: the freeze transform appends the snapshot-cohort condition to that same group+ // (mirroring _transform_filters_for_frozen_exposure) and leaves everything else untouched.+ let mut frozen_group = open_group.clone();+ frozen_group+ .properties+ .get_or_insert_with(Vec::new)+ .push(PropertyFilter {+ key: "id".to_string(),+ value: Some(json!(cohort.id)),+ operator: Some(OperatorType::In),+ prop_type: PropertyType::Cohort,+ group_type_index: None,+ negation: Some(false),+ compiled_regex: None,+ extra: Default::default(),+ });++ let open_flag = flag_with_group(team.id, open_group, multivariate.clone());+ let frozen_flag = flag_with_group(team.id, frozen_group, multivariate);++ // Variants each user receives while the flag is still open to everyone.+ let enrolled_open =+ evaluate_flag(&context, team.id, &cohort_cache, &enrolled_id, &open_flag).await;+ let new_open = evaluate_flag(&context, team.id, &cohort_cache, &new_id, &open_flag).await;+ assert!(enrolled_open.matches && enrolled_open.variant.is_some());+ assert!(new_open.matches);++ // After freezing: the enrolled user still matches and keeps the exact same variant...+ let enrolled_frozen =+ evaluate_flag(&context, team.id, &cohort_cache, &enrolled_id, &frozen_flag).await;+ assert!(enrolled_frozen.matches, "enrolled user should still match");+ assert_eq!(+ enrolled_frozen.variant, enrolled_open.variant,+ "enrolled user's variant must be unchanged by freezing"+ );++ // ...and the brand-new user no longer matches — enrollment is frozen.+ let new_frozen =+ evaluate_flag(&context, team.id, &cohort_cache, &new_id, &frozen_flag).await;+ assert!(+ !new_frozen.matches,+ "new user should be excluded after freeze"+ );+ }+#[tokio::test]async fn test_static_cohort_matching_user_not_in_cohort() {let context = TestContext::new(None).await;diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 99d4eee505b1..2f6f23c43d05 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3024,7 +3024,7 @@}},"experiment-get": {- "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, and type (web/product).",+ "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, and type (web/product).","category": "Experiments","feature": "experiments","summary": "Get experiment details",@@ -3122,7 +3122,7 @@}},"experiment-list": {- "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",+ "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.","category": "Experiments","feature": "experiments","summary": "Get all experiments",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 93a871afff89..f518203c0870 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3194,7 +3194,7 @@}},"experiment-get": {- "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, and type (web/product).",+ "description": "Get a single experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and recommended_running_time), stats_config, and type (web/product).","category": "Experiments","feature": "experiments","summary": "Get experiment details",@@ -3306,7 +3306,7 @@}},"experiment-list": {- "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.",+ "description": "List experiments in the current project. This is the primary tool for resolving experiment references — load the finding-experiments skill for guidance on searching by name, status, recency, or description.\n\nSupports filtering by status (\"draft\", \"running\", \"paused\", \"exposure_frozen\", \"stopped\", \"complete\" which maps to stopped, or \"all\"), archived state (defaults to non-archived), feature_flag_id, created_by_id, and free-text search on name. Supports ordering by an allowlisted set of fields (model fields plus computed \"duration\" and \"status\"). Returns paginated results with each experiment's status, dates, feature flag key, and metrics summary. Use the returned ID for get/update/lifecycle tools.","category": "Experiments","feature": "experiments","summary": "Get all experiments",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2ed3e544c30e..04d96587b48f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4489,6 +4489,7 @@ export namespace Schemas {Draft: 'draft',Running: 'running',Paused: 'paused',+ ExposureFrozen: 'exposure_frozen',Stopped: 'stopped',All: 'all',} as const;@@ -22467,6 +22468,7 @@ export namespace Schemas {Draft: 'draft',Running: 'running',Paused: 'paused',+ ExposureFrozen: 'exposure_frozen',Stopped: 'stopped',} as const;@@ -22565,7 +22567,7 @@ export namespace Schemas {only_count_matured_users?: boolean;/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean;- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean;@@ -22650,7 +22652,7 @@ export namespace Schemas {* @nullable*/conclusion_comment?: string | null;- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean;@@ -22672,6 +22674,10 @@ export namespace Schemas {export interface FeatureFlagGroupType {aggregation_group_type_index?: number | null;description?: string | null;+ /** Stamped by the experiment exposure freeze: the group carries a machine-added snapshot-cohort condition. */+ exposure_frozen?: boolean | null;+ /** Snapshot cohort the exposure freeze AND'd into this group's properties. */+ exposure_frozen_cohort?: number | null;properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | WorkflowVariablePropertyFilter)[] | null;rollout_percentage?: number | null;sort_key?: string | null;@@ -23163,7 +23169,7 @@ export namespace Schemas {only_count_matured_users?: boolean;/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean;- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy: boolean;@@ -39309,7 +39315,7 @@ export namespace Schemas {only_count_matured_users?: boolean;/** When true, sync the flag config sent in this request (via the `feature_flag` object, or the deprecated `parameters` keys) to the linked feature flag. Draft experiments always sync regardless. On a running experiment, `feature_flag` config without this flag is rejected. */update_feature_flag_params?: boolean;- /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'exposure_frozen' (running with enrollment frozen to the already-exposed cohort while metrics keep flowing — virtual state derived from the flag's release groups, not stored), 'stopped' (ended). */readonly status?: ExperimentStatusEnum;/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */readonly is_legacy?: boolean;@@ -66012,7 +66018,7 @@ export namespace Schemas {*/search?: string;/**- * Filter by experiment status. "running" and "paused" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated. "complete" is an alias for "stopped". "all" disables status filtering.+ * Filter by experiment status. "running", "paused", and "exposure_frozen" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated, and "exposure_frozen" returns launched experiments whose exposure was frozen to the already-enrolled cohort while metrics keep flowing. "complete" is an alias for "stopped". "all" disables status filtering.*/status?: ExperimentsListStatus;};@@ -66024,6 +66030,7 @@ export namespace Schemas {All: 'all',Complete: 'complete',Draft: 'draft',+ ExposureFrozen: 'exposure_frozen',Paused: 'paused',Running: 'running',Stopped: 'stopped',diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 7e601ec14d02..b261c5c54897 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -576,7 +576,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault)@@ -1661,7 +1661,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault).describe('Experiment status filter.'),createdBy: zod@@ -2443,7 +2443,7 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod).describe('Sort direction for orderBy.'),status: zod- .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all']).default(dashboardsUpdateWidgetsBatchBodyWidgetsItemFourConfigOneStatusDefault).describe('Experiment status filter.'),createdBy: zoddiff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex fad8e0a5af6c..0603782594b0 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -720,10 +720,10 @@ export const ExperimentsListQueryParams = /* @__PURE__ */ zod.object({),search: zod.string().optional().describe('Free-text search applied to the experiment name (case-insensitive).'),status: zod- .enum(['all', 'complete', 'draft', 'paused', 'running', 'stopped'])+ .enum(['all', 'complete', 'draft', 'exposure_frozen', 'paused', 'running', 'stopped']).optional().describe(- 'Filter by experiment status. "running" and "paused" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated. "complete" is an alias for "stopped". "all" disables status filtering.'+ 'Filter by experiment status. "running", "paused", and "exposure_frozen" are mutually exclusive: "running" returns launched experiments with an active feature flag, "paused" returns launched experiments whose feature flag is deactivated, and "exposure_frozen" returns launched experiments whose exposure was frozen to the already-enrolled cohort while metrics keep flowing. "complete" is an alias for "stopped". "all" disables status filtering.'),})diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex c774e6ba7376..ed55c23cf4dc 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -533,7 +533,7 @@ const experimentLaunch = (): ToolBase<typeof ExperimentLaunchSchema, WithPostHogconst ExperimentListSchema = ExperimentsListQueryParams.extend({status: ExperimentsListQueryParams.shape['status'].describe(- 'Filter by experiment status. Values: "draft" (not yet launched), "running" (launched, flag active), "paused" (launched, flag deactivated — mutually exclusive with running), "stopped" or "complete" (both mean ended), "all" (no filter). Defaults to all non-archived experiments.'+ 'Filter by experiment status. Values: "draft" (not yet launched), "running" (launched, flag active), "paused" (launched, flag deactivated — mutually exclusive with running), "exposure_frozen" (launched, enrollment frozen to the already-exposed cohort while metrics keep flowing), "stopped" or "complete" (both mean ended), "all" (no filter). Defaults to all non-archived experiments.'),limit: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['limit']).optional(),offset: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['offset']).optional(),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.jsonindex 08bef1168056..fbc4124862ea 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json@@ -695,7 +695,14 @@"status": {"default": "all","description": "Experiment status filter.",- "enum": ["draft", "running", "paused", "stopped", "all"],+ "enum": [+ "draft",+ "running",+ "paused",+ "exposure_frozen",+ "stopped",+ "all"+ ],"type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.jsonindex eac72a91a8fa..fff980dd29f5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json@@ -819,7 +819,7 @@"status": {"default": "all","description": "Experiment status filter.",- "enum": ["draft", "running", "paused", "stopped", "all"],+ "enum": ["draft", "running", "paused", "exposure_frozen", "stopped", "all"],"type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.jsonindex a6d8c57375e3..9013256bc9bf 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json@@ -669,7 +669,7 @@"status": {"default": "all","description": "Experiment status filter.",- "enum": ["draft", "running", "paused", "stopped", "all"],+ "enum": ["draft", "running", "paused", "exposure_frozen", "stopped", "all"],"type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.jsonindex 7671593fbf8e..890c3a3738b8 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json@@ -38,8 +38,8 @@"type": "string"},"status": {- "description": "Filter by experiment status. Values: \"draft\" (not yet launched), \"running\" (launched, flag active), \"paused\" (launched, flag deactivated — mutually exclusive with running), \"stopped\" or \"complete\" (both mean ended), \"all\" (no filter). Defaults to all non-archived experiments.",- "enum": ["all", "complete", "draft", "paused", "running", "stopped"],+ "description": "Filter by experiment status. Values: \"draft\" (not yet launched), \"running\" (launched, flag active), \"paused\" (launched, flag deactivated — mutually exclusive with running), \"exposure_frozen\" (launched, enrollment frozen to the already-exposed cohort while metrics keep flowing), \"stopped\" or \"complete\" (both mean ended), \"all\" (no filter). Defaults to all non-archived experiments.",+ "enum": ["all", "complete", "draft", "exposure_frozen", "paused", "running", "stopped"],"type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.jsonindex 7671593fbf8e..890c3a3738b8 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json@@ -38,8 +38,8 @@"type": "string"},"status": {- "description": "Filter by experiment status. Values: \"draft\" (not yet launched), \"running\" (launched, flag active), \"paused\" (launched, flag deactivated — mutually exclusive with running), \"stopped\" or \"complete\" (both mean ended), \"all\" (no filter). Defaults to all non-archived experiments.",- "enum": ["all", "complete", "draft", "paused", "running", "stopped"],+ "description": "Filter by experiment status. Values: \"draft\" (not yet launched), \"running\" (launched, flag active), \"paused\" (launched, flag deactivated — mutually exclusive with running), \"exposure_frozen\" (launched, enrollment frozen to the already-exposed cohort while metrics keep flowing), \"stopped\" or \"complete\" (both mean ended), \"all\" (no filter). Defaults to all non-archived experiments.",+ "enum": ["all", "complete", "draft", "exposure_frozen", "paused", "running", "stopped"],"type": "string"}},