: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 unfreeze-exposure lifecycle action (#68229)
Marcel Poelker515caa6f3e11
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsxindex 8df0e1d5e4e1..d4946c94e1f3 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentSceneMenuBar.tsx@@ -12,6 +12,7 @@ import {IconPlusSmall,IconRefresh,IconTrash,+ IconUnlock,} from '@posthog/icons'import { LemonDialog } from '@posthog/lemon-ui'@@ -47,10 +48,11 @@ import {confirmArchiveExperiment,confirmDeleteExperiment,confirmFreezeExposure,+ confirmUnfreezeExposure,hasFrozenExposureStamps,} from '../experimentActions'import { experimentLogic } from '../experimentLogic'-import { isExperimentPaused } from '../experimentsLogic'+import { isExperimentExposureFrozen, isExperimentPaused } from '../experimentsLogic'import { modalsLogic } from '../modalsLogic'import { isLegacyExperiment } from '../utils'@@ -72,6 +74,7 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {isExperimentStopped,isCreatingExperimentDashboard,freezeExposureLoading,+ unfreezeExposureLoading,showDebugPanel,} = useValues(experimentLogic)const {@@ -81,6 +84,7 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {createExperimentDashboard,resetRunningExperiment,freezeExposure,+ unfreezeExposure,toggleDebugPanel,} = useActions(experimentLogic)const { currentProjectId } = useValues(projectLogic)@@ -310,6 +314,18 @@ function ExperimentSceneMenuBarInner(): JSX.Element | null {Freeze exposure</SceneMenuBarItem>)}+ {isExperimentExposureFrozen(experiment) && (+ <SceneMenuBarItem+ opensFloatingUi+ onClick={() => confirmUnfreezeExposure(unfreezeExposure)}+ disabled={unfreezeExposureLoading}+ tooltip={unfreezeExposureLoading ? 'Unfreezing exposure…' : undefined}+ data-attr={`${RESOURCE_TYPE}-menubar-unfreeze-exposure`}+ >+ <IconUnlock />+ Unfreeze exposure+ </SceneMenuBarItem>+ )}<SceneMenuBarItemopensFloatingUivariant="destructive"diff --git a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsxindex eb09225a07f9..8100ffb66d88 100644--- a/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/PageHeader.tsx@@ -13,6 +13,7 @@ import {IconPlusSmall,IconRefresh,IconTrash,+ IconUnlock,} from '@posthog/icons'import { LemonButton, LemonDialog, LemonDivider, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'@@ -42,10 +43,11 @@ import {confirmArchiveExperiment,confirmDeleteExperiment,confirmFreezeExposure,+ confirmUnfreezeExposure,hasFrozenExposureStamps,} from '../experimentActions'import { experimentLogic } from '../experimentLogic'-import { isExperimentPaused } from '../experimentsLogic'+import { isExperimentExposureFrozen, isExperimentPaused } from '../experimentsLogic'import { modalsLogic } from '../modalsLogic'import { isLegacyExperiment } from '../utils'import { FinishExperimentModal, PauseExperimentModal, ResumeExperimentModal } from './ExperimentModals'@@ -62,6 +64,7 @@ export function PageHeaderCustom(): JSX.Element {experimentLoading,launchExperimentLoading,freezeExposureLoading,+ unfreezeExposureLoading,} = useValues(experimentLogic)const {launchExperiment,@@ -72,6 +75,7 @@ export function PageHeaderCustom(): JSX.Element {updateExperiment,setHogfettiTrigger,freezeExposure,+ unfreezeExposure,} = useActions(experimentLogic)const { currentProjectId } = useValues(projectLogic)const { currentOrganization } = useValues(organizationLogic)@@ -271,6 +275,18 @@ export function PageHeaderCustom(): JSX.Element {<IconLock /> Freeze exposure</ButtonPrimitive>)}+ {isExperimentExposureFrozen(experiment) && (+ <ButtonPrimitive+ menuItem+ data-attr="unfreeze-exposure"+ onClick={() => confirmUnfreezeExposure(unfreezeExposure)}+ disabledReasons={{+ 'Unfreezing exposure...': unfreezeExposureLoading,+ }}+ >+ <IconUnlock /> Unfreeze exposure+ </ButtonPrimitive>+ )}<ButtonPrimitivevariant="danger"menuItemdiff --git a/frontend/src/scenes/experiments/experimentActions.tsx b/frontend/src/scenes/experiments/experimentActions.tsxindex b90060d521f0..9f7cb857d909 100644--- a/frontend/src/scenes/experiments/experimentActions.tsx+++ b/frontend/src/scenes/experiments/experimentActions.tsx@@ -60,7 +60,10 @@ export function confirmFreezeExposure(onConfirm: () => void): void {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>+ <p>+ From a frozen state you can end an experiment or ship a variant at any time. You can unfreeze as+ well to reopen enrollment.+ </p></div>),primaryButton: {@@ -77,6 +80,35 @@ export function confirmFreezeExposure(onConfirm: () => void): void {})}+export function confirmUnfreezeExposure(onConfirm: () => void): void {+ LemonDialog.open({+ title: 'Unfreeze exposure?',+ content: (+ <div className="text-sm text-secondary max-w-md">+ <p>+ New users can <b>enroll again</b> under the flag's original release conditions. Everyone already+ enrolled keeps their variant, and the snapshot cohort is removed.+ </p>+ <p>+ Heads up: users enrolled before the freeze and after the unfreeze joined at different times, which+ can mix populations and cause bias in your results.+ </p>+ </div>+ ),+ primaryButton: {+ children: 'Unfreeze 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 e4e9ab194927..e2072402d898 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -1326,6 +1326,32 @@ describe('experimentLogic', () => {})})+ describe('unfreezeExposure', () => {+ it('calls unfreeze_exposure endpoint, updates experiment, and toggles the loading guard', async () => {+ const unfrozenResponse = { ...experiment, status: 'running' }+ const createSpy = jest.spyOn(api, 'create').mockResolvedValue(unfrozenResponse)++ const keyed = experimentLogic({ experimentId: experiment.id })+ keyed.mount()+ keyed.actions.setExperiment({ ...experiment, status: 'exposure_frozen' } as Experiment)++ await expectLogic(keyed, () => {+ keyed.actions.unfreezeExposure()+ })+ .toDispatchActions(['unfreezeExposure', 'setUnfreezeExposureLoading', 'setExperiment'])+ .toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledWith(+ expect.stringContaining(`/experiments/${experiment.id}/unfreeze_exposure`)+ )+ expect(keyed.values.experiment.status).toBe('running')+ expect(keyed.values.unfreezeExposureLoading).toBe(false)++ createSpy.mockRestore()+ keyed.unmount()+ })+ })+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 0c2d39d5e0ee..869c2c138e79 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -611,6 +611,8 @@ export const experimentLogic = kea<experimentLogicType>([resumeExperiment: true,freezeExposure: true,setFreezeExposureLoading: (loading: boolean) => ({ loading }),+ unfreezeExposure: true,+ setUnfreezeExposureLoading: (loading: boolean) => ({ loading }),archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),unarchiveExperiment: true,resetRunningExperiment: true,@@ -1177,6 +1179,12 @@ export const experimentLogic = kea<experimentLogicType>([setFreezeExposureLoading: (_, { loading }) => loading,},],+ unfreezeExposureLoading: [+ false,+ {+ setUnfreezeExposureLoading: (_, { loading }) => loading,+ },+ ],hogfettiTrigger: [null as (() => void) | null,{@@ -1491,6 +1499,24 @@ export const experimentLogic = kea<experimentLogicType>([actions.setFreezeExposureLoading(false)}},+ unfreezeExposure: async () => {+ if (values.unfreezeExposureLoading) {+ return+ }+ actions.setUnfreezeExposureLoading(true)+ try {+ const response: Experiment = await api.create(+ `/api/projects/${values.currentProjectId}/experiments/${values.experimentId}/unfreeze_exposure`+ )+ actions.setExperiment(response)+ refreshTreeItem('experiment', String(values.experimentId))+ lemonToast.success('Exposure unfrozen — new users can enroll again')+ } catch (error: any) {+ lemonToast.error(error.detail || 'Failed to unfreeze exposure')+ } finally {+ actions.setUnfreezeExposureLoading(false)+ }+ },archiveExperiment: async ({ disableFeatureFlag }) => {try {const response: Experiment = await api.create(diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex a13cb4dd48e1..56872a3a2e32 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -2270,6 +2270,69 @@ class ExperimentService:request=request,)+ def unfreeze_exposure(self, experiment: Experiment, *, request: Any) -> Experiment:+ """Reopen enrollment on an exposure-frozen experiment.++ Inverse of freeze_exposure: strips the snapshot-cohort condition, the freeze keys, and+ the marker note from every frozen release group, restoring the flag's original targeting+ — enrolled users keep their variant by deterministic hash, new users can enroll again.+ Edits made to the frozen groups while frozen (e.g. extra conditions) are preserved; only+ the snapshot-cohort condition and freeze stamps are removed. Adding a brand-new unstamped+ group instead reopens enrollment, so that experiment reads as "running" and never reaches+ this path (see Experiment.is_exposure_frozen). The snapshot cohort is soft-deleted after+ the flag save so it doesn't accumulate as clutter.+ """+ if experiment.is_draft:+ raise ValidationError("Experiment has not been launched yet.")+ if experiment.is_stopped:+ raise ValidationError("Experiment has already ended.")+ if not experiment.is_exposure_frozen:+ raise ValidationError("Experiment exposure is not frozen.")++ flag = experiment.feature_flag+ new_filters, cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters or {})++ flag_serializer = FeatureFlagSerializer(+ 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()++ # Refresh so the experiment's nested flag reflects the restored filters when serialized.+ flag.refresh_from_db()+ experiment.feature_flag = flag++ # Only after the flag no longer references them: soft-delete the now-orphaned snapshots.+ self._delete_orphaned_snapshot_cohorts(cohort_ids)++ self._report_experiment_exposure_unfrozen(experiment, request=request)++ return experiment++ def _report_experiment_exposure_unfrozen(+ self,+ experiment: Experiment,+ *,+ request: Any | None = None,+ ) -> None:+ if request is None:+ return++ report_user_action(+ self.user,+ "experiment exposure unfrozen",+ experiment.get_analytics_metadata(),+ team=experiment.team,+ request=request,+ )+# ------------------------------------------------------------------# End# ------------------------------------------------------------------diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex a0c9671af39f..4f6e2834da4c 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -645,6 +645,27 @@ class EnterpriseExperimentsViewSet(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,+ )+ @action(methods=["POST"], detail=True, required_scopes=["experiment:write"])+ def unfreeze_exposure(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """+ Reopen enrollment on an exposure-frozen experiment.++ Removes the snapshot-cohort condition and freeze markers from every release+ group, restoring the flag's original targeting: new users can enroll again+ and already-enrolled users keep their assigned variant. The snapshot cohort+ is soft-deleted. The serialized status returns to 'running'.++ Returns 400 if the experiment is not running or its exposure is not frozen.+ """+ experiment: Experiment = self.get_object()+ service = ExperimentService(team=self.team, user=request.user)+ unfrozen_experiment = service.unfreeze_exposure(experiment, request=request)+ return Response(ExperimentSerializer(unfrozen_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 b075c5354ee0..a04719eb1778 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -3620,6 +3620,86 @@ class TestExperimentService(APIBaseTest):assert {"key": "id", "type": "cohort", "value": cohort.id, "operator": "in"} in groups[0]["properties"]assert groups[0][EXPOSURE_FROZEN_GROUP_KEY] is True+ # ------------------------------------------------------------------+ # Unfreeze exposure+ # ------------------------------------------------------------------++ def test_unfreeze_exposure_restores_original_filters(self) -> None:+ experiment = self._create_running_experiment(name="Unfreeze Test", feature_flag_key="unfreeze-flag")+ flag = experiment.feature_flag++ # Heterogeneous groups: one with a user-authored description, one bare.+ 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_filters = deepcopy(flag.filters)++ 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 "Unfreeze Test"')++ unfrozen = self._service().unfreeze_exposure(frozen, request=self._make_request())+ unfrozen.feature_flag.refresh_from_db()++ # The flag is byte-for-byte back to its pre-freeze state: cohort condition, freeze keys,+ # and marker note all removed; the user-authored description restored exactly.+ assert unfrozen.feature_flag.filters == original_filters+ assert unfrozen.is_exposure_frozen is False+ assert unfrozen.is_running is True+ assert unfrozen.end_date is None++ # The snapshot cohort is soft-deleted, not left as clutter.+ cohort.refresh_from_db()+ assert cohort.deleted is True++ def test_unfreeze_exposure_keeps_user_edits_made_while_frozen(self) -> None:+ experiment = self._create_running_experiment(name="Unfreeze Edits", feature_flag_key="unfreeze-edits-flag")++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ flag = frozen.feature_flag+ flag.refresh_from_db()++ # While frozen, a user adds their own condition to the frozen group. The group keeps its+ # freeze stamp, so the experiment stays frozen and can still be unfrozen. (Adding a brand-new+ # unstamped group instead reopens enrollment and reverts the experiment to "running" — see+ # test_flag_update_adding_unstamped_group_reopens_exposure.)+ edited = deepcopy(flag.filters)+ user_condition = {"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}+ edited["groups"][0]["properties"].append(user_condition)+ self._update_flag_filters(flag, edited)++ unfrozen = self._service().unfreeze_exposure(frozen, request=self._make_request())+ unfrozen.feature_flag.refresh_from_db()++ groups = unfrozen.feature_flag.filters["groups"]+ assert len(groups) == 1+ # Only the snapshot-cohort condition was removed from the frozen group — the user's stays.+ assert groups[0]["properties"] == [user_condition]+ assert EXPOSURE_FROZEN_GROUP_KEY not in groups[0]++ def test_unfreeze_exposure_when_not_frozen_raises(self) -> None:+ experiment = self._create_running_experiment(name="UF Not Frozen", feature_flag_key="uf-not-frozen-flag")++ with self.assertRaises(ValidationError) as ctx:+ self._service().unfreeze_exposure(experiment, request=self._make_request())+ assert "not frozen" in str(ctx.exception)++ @patch("products.experiments.backend.experiment_service.report_user_action")+ def test_unfreeze_exposure_reports_analytics(self, mock_report: MagicMock) -> None:+ experiment = self._create_running_experiment(name="Unfreeze Analytics", feature_flag_key="uf-analytics-flag")++ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())+ self._service().unfreeze_exposure(frozen, request=self._make_request())++ assert any(call.args[1] == "experiment exposure unfrozen" for call in mock_report.call_args_list)+# ------------------------------------------------------------------# Reset# ------------------------------------------------------------------diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex afff0ec56fb7..9e1d02e2f3ff 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -5661,6 +5661,33 @@ class TestExperimentCRUD(APILicensedTest):)self.assertEqual(second_freeze.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_unfreeze_exposure_endpoint(self, mock_fetch: MagicMock, mock_insert: MagicMock) -> None:+ data = self._create_running_experiment(name="Unfreeze Endpoint", flag_key="unfreeze-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)++ unfreeze_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/unfreeze_exposure/",+ )+ self.assertEqual(unfreeze_response.status_code, status.HTTP_200_OK)+ self.assertEqual(unfreeze_response.json()["status"], "running")++ # Not frozen anymore — a second unfreeze is rejected.+ second_unfreeze = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/unfreeze_exposure/",+ )+ self.assertEqual(second_unfreeze.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/",diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex dfa0c1bd2d55..7f5dcbbfa6a3 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -871,6 +871,31 @@ export const experimentsUnarchiveCreate = async (})}+export const getExperimentsUnfreezeExposureCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/unfreeze_exposure/`+}++/**+ * Reopen enrollment on an exposure-frozen experiment.+ *+ * Removes the snapshot-cohort condition and freeze markers from every release+ * group, restoring the flag's original targeting: new users can enroll again+ * and already-enrolled users keep their assigned variant. The snapshot cohort+ * is soft-deleted. The serialized status returns to 'running'.+ *+ * Returns 400 if the experiment is not running or its exposure is not frozen.+ */+export const experimentsUnfreezeExposureCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentApi> => {+ return apiMutator<ExperimentApi>(getExperimentsUnfreezeExposureCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getExperimentsCalculateRunningTimeCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/experiments/calculate_running_time/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 1bf3f6f102a2..8c4c4f5b5b6a 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -1055,6 +1055,9 @@ tools:experiments-requires-flag-implementation:operation: experiments_requires_flag_implementation_retrieveenabled: false+ experiments-unfreeze-exposure-create:+ operation: experiments_unfreeze_exposure_create+ enabled: falseexperiments-update:operation: experiments_updateenabled: false