Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): opt-in cleanup PR checkbox in the end experiment modal (#68946)

Juraj Majerik8a92f94c9ae2
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 10f170cba183..e4db8b5512b7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -309,6 +309,7 @@ export const FEATURE_FLAGS = {
ERROR_TRACKING_SOURCE_MAPS_BANNER: 'error-tracking-source-maps-banner', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-tracking
EVENT_MEDIA_PREVIEWS: 'event-media-previews', // owner: @alexlider
+ EXPERIMENT_FLAG_CLEANUP_PR: 'experiment-flag-cleanup-pr', // owner: @jurajmajerik #team-experiments
EXPERIMENT_SESSION_REPLAYS_SKILL: 'experiment-session-replays-skill', // owner: @rodrigoi #team-experiments
EXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experiments
EXPERIMENTS_END_MODAL_CONCLUSION_FIRST: 'experiments-end-modal-conclusion-first', // owner: @ruby.c #team-experiments
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
index 5c204f485a51..a33018944e64 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
@@ -3,7 +3,16 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconCheckCircle, IconGlobe, IconList } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonLabel, LemonModal, LemonSelect, LemonTextArea, Link } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCheckbox,
+ LemonLabel,
+ LemonModal,
+ LemonSelect,
+ LemonTextArea,
+ Link,
+} from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -208,19 +217,32 @@ export function FinishExperimentModal(): JSX.Element {
const [selectedVariantKey, setSelectedVariantKey] = useState<string | null>()
const [releaseToEveryone, setReleaseToEveryone] = useState<boolean>(false)
+ const [openCleanupPr, setOpenCleanupPr] = useState<boolean>(false)
+
+ // The cleanup PR runs as a PostHog Code task, so the user needs Code access on top of the rollout flag.
+ const cleanupPrAvailable =
+ !!featureFlags[FEATURE_FLAGS.EXPERIMENT_FLAG_CLEANUP_PR] && !!featureFlags[FEATURE_FLAGS.TASKS]
const aggregationTargetName =
experiment.filters.aggregation_group_type_index != null
? aggregationLabel(experiment.filters.aggregation_group_type_index).plural
: 'users'
+ const handleClose = (): void => {
+ setOpenCleanupPr(false)
+ restoreUnmodifiedExperiment()
+ closeFinishExperimentModal()
+ }
+
const handleEndExperiment = (): void => {
+ const withCleanupPr = cleanupPrAvailable && openCleanupPr
if (isSingleVariantShipped || !selectedVariantKey) {
- endExperimentWithoutShipping()
+ endExperimentWithoutShipping(withCleanupPr)
} else {
finishExperiment({
selectedVariantKey,
releaseToEveryone,
+ openCleanupPr: withCleanupPr,
})
}
}
@@ -246,21 +268,12 @@ export function FinishExperimentModal(): JSX.Element {
<>
<LemonModal
isOpen={isFinishExperimentModalOpen}
- onClose={() => {
- restoreUnmodifiedExperiment()
- closeFinishExperimentModal()
- }}
+ onClose={handleClose}
width={600}
title="End experiment"
footer={
<div className="flex items-center gap-2">
- <LemonButton
- type="secondary"
- onClick={() => {
- restoreUnmodifiedExperiment()
- closeFinishExperimentModal()
- }}
- >
+ <LemonButton type="secondary" onClick={handleClose}>
Cancel
</LemonButton>
<LemonButton
@@ -375,6 +388,18 @@ export function FinishExperimentModal(): JSX.Element {
</>
)}
{!conclusionFirst && <ConclusionForm />}
+ {cleanupPrAvailable && (
+ <LemonCheckbox
+ checked={openCleanupPr}
+ onChange={setOpenCleanupPr}
+ data-attr="experiment-open-cleanup-pr"
+ label={
+ <span>
+ Open a draft PR removing <code>{experiment.feature_flag?.key}</code> from your code
+ </span>
+ }
+ />
+ )}
{!isSingleVariantShipped && (
<LemonBanner type="info" className="mb-4">
For more precise control over your release, adjust the rollout percentage and release
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 5d9913e39a9b..7c297adcc9e9 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -1399,6 +1399,7 @@ describe('experimentLogic', () => {
expect(createSpy).toHaveBeenCalledWith(expect.stringContaining(`/experiments/${experiment.id}/end`), {
conclusion: 'won',
conclusion_comment: 'Test variant won clearly',
+ open_cleanup_pr: false,
})
// Post-condition: experiment is ended
@@ -1493,6 +1494,7 @@ describe('experimentLogic', () => {
release_to_everyone: false,
conclusion: 'won',
conclusion_comment: 'Test variant won clearly',
+ open_cleanup_pr: false,
}
)
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 83270dd3871a..275e3de3ffa9 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -593,15 +593,17 @@ export const experimentLogic = kea<experimentLogicType>([
changeExperimentStartDate: (startDate: string) => ({ startDate }),
changeExperimentEndDate: (endDate: string) => ({ endDate }),
launchExperiment: true,
- endExperiment: true,
- endExperimentWithoutShipping: true,
+ endExperiment: (openCleanupPr: boolean = false) => ({ openCleanupPr }),
+ endExperimentWithoutShipping: (openCleanupPr: boolean = false) => ({ openCleanupPr }),
finishExperiment: ({
selectedVariantKey,
releaseToEveryone,
+ openCleanupPr,
}: {
selectedVariantKey: string
releaseToEveryone: boolean
- }) => ({ selectedVariantKey, releaseToEveryone }),
+ openCleanupPr?: boolean
+ }) => ({ selectedVariantKey, releaseToEveryone, openCleanupPr: openCleanupPr ?? false }),
pauseExperiment: true,
resumeExperiment: true,
archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),
@@ -1399,7 +1401,7 @@ export const experimentLogic = kea<experimentLogicType>([
values.experiment && eventUsageLogic.actions.reportExperimentEndDateChange(values.experiment, endDate)
actions.refreshExperimentResults(true, 'config_change')
},
- endExperiment: async () => {
+ endExperiment: async ({ openCleanupPr }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -1407,6 +1409,7 @@ export const experimentLogic = kea<experimentLogicType>([
{
conclusion: values.experiment.conclusion,
conclusion_comment: values.experiment.conclusion_comment,
+ open_cleanup_pr: openCleanupPr,
}
)
actions.setExperiment(response)
@@ -1417,8 +1420,8 @@ export const experimentLogic = kea<experimentLogicType>([
actions.setEndExperimentLoading(false)
}
},
- endExperimentWithoutShipping: async () => {
- actions.endExperiment()
+ endExperimentWithoutShipping: async ({ openCleanupPr }) => {
+ actions.endExperiment(openCleanupPr)
actions.closeFinishExperimentModal()
lemonToast.success('Experiment ended successfully')
@@ -1697,7 +1700,7 @@ export const experimentLogic = kea<experimentLogicType>([
})
}
},
- finishExperiment: async ({ selectedVariantKey, releaseToEveryone }) => {
+ finishExperiment: async ({ selectedVariantKey, releaseToEveryone, openCleanupPr }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -1707,6 +1710,7 @@ export const experimentLogic = kea<experimentLogicType>([
release_to_everyone: releaseToEveryone,
conclusion: values.experiment.conclusion,
conclusion_comment: values.experiment.conclusion_comment,
+ open_cleanup_pr: openCleanupPr,
}
)
actions.setExperiment(response)
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 07a46c0dcd9a..c5d9da526c23 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -771,7 +771,8 @@ class EndExperimentSerializer(serializers.Serializer):
default=False,
help_text=(
"When true, open a draft pull request that removes the experiment's feature-flag code "
- "from the linked repository. Only acts for allowlisted teams; ignored otherwise."
+ "from the linked repository. Requires the requesting user to have access to PostHog Code "
+ "(403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
)
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index beaa6e4bf0b8..e4edc63c6257 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -19,7 +19,7 @@ from django.utils.text import slugify
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from opentelemetry import trace
from rest_framework import serializers, viewsets
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -88,6 +88,7 @@ from products.feature_flags.backend.models.evaluation_context import FeatureFlag
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
+from products.tasks.backend.facade.access import has_tasks_access
from ee.clickhouse.queries.experiments.utils import requires_flag_warning
@@ -369,6 +370,13 @@ class EnterpriseExperimentsViewSet(
return scopes
return None
+ def _check_cleanup_pr_access(self, request: Request) -> None:
+ """Opening a cleanup PR starts a Code task on the user's behalf. The task:write
+ scope only gates token auth (see dangerously_get_required_scopes); session auth
+ has no scopes, so gate every caller on PostHog Code product access instead."""
+ if not has_tasks_access(cast(User, request.user)):
+ raise PermissionDenied("Opening a flag cleanup PR requires access to PostHog Code.")
+
def _token_can_write_feature_flag(self, request: Request) -> bool:
"""Whether the request's token carries feature_flag:write.
@@ -507,6 +515,8 @@ class EnterpriseExperimentsViewSet(
experiment: Experiment = self.get_object()
request_serializer = EndExperimentSerializer(data=request.data)
request_serializer.is_valid(raise_exception=True)
+ if request_serializer.validated_data["open_cleanup_pr"]:
+ self._check_cleanup_pr_access(request)
service = ExperimentService(team=self.team, user=request.user)
ended_experiment = service.end_experiment(
experiment,
@@ -550,6 +560,8 @@ class EnterpriseExperimentsViewSet(
experiment: Experiment = self.get_object()
request_serializer = ShipVariantSerializer(data=request.data)
request_serializer.is_valid(raise_exception=True)
+ if request_serializer.validated_data["open_cleanup_pr"]:
+ self._check_cleanup_pr_access(request)
service = ExperimentService(team=self.team, user=request.user)
shipped_experiment = service.ship_variant(
experiment,
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 164890daa93b..446973e96054 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -5570,8 +5570,9 @@ class TestExperimentCRUD(APILicensedTest):
)
self.assertEqual(end_response.status_code, status.HTTP_400_BAD_REQUEST)
+ @patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=True)
@patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=False)
- def test_end_endpoint_cleanup_pr_requires_task_write_scope(self, _mock_flag):
+ def test_end_endpoint_cleanup_pr_requires_task_write_scope(self, _mock_flag, _mock_access):
exp_deny = self._create_running_experiment(name="Cleanup Deny", flag_key="cleanup-deny-flag")["id"]
exp_no_opt = self._create_running_experiment(name="Cleanup No Opt", flag_key="cleanup-no-opt-flag")["id"]
exp_allow = self._create_running_experiment(name="Cleanup Allow", flag_key="cleanup-allow-flag")["id"]
@@ -5612,6 +5613,54 @@ class TestExperimentCRUD(APILicensedTest):
)
self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ @patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=False)
+ def test_cleanup_pr_requires_code_access_for_session_users(self, _mock_flag):
+ exp_end = self._create_running_experiment(name="Cleanup Session End", flag_key="cleanup-session-end-flag")["id"]
+ exp_ship = self._create_running_experiment(name="Cleanup Session Ship", flag_key="cleanup-session-ship-flag")[
+ "id"
+ ]
+
+ # Scopes don't apply to session auth — without Code access, opting in must be rejected
+ # on both actions that can open a cleanup PR.
+ with patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=False):
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_end}/end/",
+ {"conclusion": "won", "open_cleanup_pr": True},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_ship}/ship_variant/",
+ {"variant_key": "test", "conclusion": "won", "open_cleanup_pr": True},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+
+ # Not opting in still ends the experiment without Code access.
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_end}/end/",
+ {"conclusion": "won", "open_cleanup_pr": False},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
+ # With Code access, opting in succeeds on both actions ("end first, ship later" flow).
+ with patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=True):
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_ship}/end/",
+ {"conclusion": "won", "open_cleanup_pr": True},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_ship}/ship_variant/",
+ {"variant_key": "test", "conclusion": "won", "open_cleanup_pr": True},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
def test_ship_variant_endpoint_default_preserves_groups(self):
data = self._create_running_experiment(name="Ship Endpoint", flag_key="ship-endpoint-flag")
experiment_id = data["id"]
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 018533c6f992..83992135be11 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1515,7 +1515,7 @@ export interface EndExperimentApi {
* @nullable
*/
conclusion_comment?: string | null
- /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise. */
+ /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean
}
@@ -1723,7 +1723,7 @@ export interface ShipVariantApi {
* @nullable
*/
conclusion_comment?: string | null
- /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise. */
+ /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean
/** The key of the variant to ship. */
variant_key: string
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 0d4596c025b5..7ec19a7ba672 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -985,7 +985,7 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(experimentsEndCreateBodyOpenCleanupPrDefault)
.describe(
- "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise."
+ "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
})
@@ -1084,7 +1084,7 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(experimentsShipVariantCreateBodyOpenCleanupPrDefault)
.describe(
- "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise."
+ "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 92c5238fd935..281bddfbb18c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19045,7 +19045,7 @@ export namespace Schemas {
* @nullable
*/
conclusion_comment?: string | null;
- /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise. */
+ /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean;
}
@@ -49941,7 +49941,7 @@ export namespace Schemas {
* @nullable
*/
conclusion_comment?: string | null;
- /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise. */
+ /** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean;
/** The key of the variant to ship. */
variant_key: string;
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index b04424097079..e3146c1193a6 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -11107,7 +11107,7 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(experimentsEndCreateBodyOpenCleanupPrDefault)
.describe(
- "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise."
+ "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
})
@@ -11242,7 +11242,7 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(experimentsShipVariantCreateBodyOpenCleanupPrDefault)
.describe(
- "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise."
+ "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
index fd26d57d2988..b16810ac942f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
@@ -32,7 +32,7 @@
},
"open_cleanup_pr": {
"default": false,
- "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise.",
+ "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise.",
"type": "boolean"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
index def9ca20a43b..db46b53a976b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
@@ -32,7 +32,7 @@
},
"open_cleanup_pr": {
"default": false,
- "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Only acts for allowlisted teams; ignored otherwise.",
+ "description": "When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Code (403 otherwise). Only acts for allowlisted teams; ignored otherwise.",
"type": "boolean"
},
"release_to_everyone": {