: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): surface the flag cleanup task on the experiment page (#69975)
Juraj Majerik223b1a5fdf5a
diff --git a/frontend/src/scenes/experiments/ExperimentView/Info.tsx b/frontend/src/scenes/experiments/ExperimentView/Info.tsxindex ef1a799f228d..a74c863664e8 100644--- a/frontend/src/scenes/experiments/ExperimentView/Info.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/Info.tsx@@ -20,9 +20,48 @@ import { getExperimentStatus, isExperimentPaused } from '../experimentsLogic'import { modalsLogic } from '../modalsLogic'import { ExperimentDuration } from './ExperimentDuration'import { ExperimentReloadActionContainer } from './ExperimentReloadActionContainer'+import { flagCleanupTaskLogic } from './flagCleanupTaskLogic'import { RunningTime } from './RunningTime'import { StatusTag } from './StatusTag'+function FlagCleanupLine({ experimentId, taskId }: { experimentId: number; taskId: string }): JSX.Element | null {+ const { cleanupTask } = useValues(flagCleanupTaskLogic({ experimentId }))++ if (!cleanupTask) {+ return null+ }++ let text = 'Preparing cleanup PR…'+ let linkText = 'View task'+ let to = urls.taskDetail(taskId)+ if (cleanupTask.is_terminal) {+ if (cleanupTask.run_status === 'completed' && cleanupTask.pr_url) {+ text = 'Cleanup PR opened'+ linkText = 'View on GitHub'+ to = cleanupTask.pr_url+ } else if (cleanupTask.run_status === 'completed') {+ text = 'Cleanup found no flag code to remove'+ } else if (cleanupTask.run_status === 'failed') {+ text = 'Cleanup PR failed'+ } else {+ text = 'Cleanup PR cancelled'+ }+ }++ return (+ <div className="text-xs text-muted mt-1 mb-3 flex items-center gap-1">+ {text} ·+ <Link+ target={to === cleanupTask.pr_url ? '_blank' : undefined}+ className="flex items-center gap-0.5"+ to={to}+ >+ {linkText} <IconOpenInNew fontSize="12" />+ </Link>+ </div>+ )+}+export function Info(): JSX.Element {const {experiment,@@ -235,6 +274,12 @@ export function Info(): JSX.Element {</span></div><div>{experiment.conclusion_comment}</div>+ {experiment.flag_cleanup_task_id && typeof experiment.id === 'number' && (+ <FlagCleanupLine+ experimentId={experiment.id}+ taskId={experiment.flag_cleanup_task_id}+ />+ )}</div></div>)}diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.tsnew file mode 100644index 000000000000..08230c28e683--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts@@ -0,0 +1,78 @@+import { initKeaTests } from '~/test/init'++import { experimentsFlagCleanupTaskRetrieve } from 'products/experiments/frontend/generated/api'++import { flagCleanupTaskLogic } from './flagCleanupTaskLogic'++jest.mock('products/experiments/frontend/generated/api', () => ({+ experimentsFlagCleanupTaskRetrieve: jest.fn(),+}))++const mockRetrieve = experimentsFlagCleanupTaskRetrieve as jest.Mock++describe('flagCleanupTaskLogic', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ initKeaTests()+ mockRetrieve.mockReset()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('polls until the task run is terminal, then stops', async () => {+ mockRetrieve+ .mockResolvedValueOnce({+ task_id: 'a',+ run_status: 'in_progress',+ is_terminal: false,+ pr_url: null,+ })+ .mockResolvedValue({+ task_id: 'a',+ run_status: 'completed',+ is_terminal: true,+ pr_url: 'https://github.com/PostHog/posthog/pull/1',+ })++ const logic = flagCleanupTaskLogic({ experimentId: 1 })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ expect(mockRetrieve).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(30000)+ expect(mockRetrieve).toHaveBeenCalledTimes(2)+ expect(logic.values.cleanupTask?.pr_url).toBe('https://github.com/PostHog/posthog/pull/1')++ // Terminal — the interval is disposed, no further requests.+ await jest.advanceTimersByTimeAsync(120000)+ expect(mockRetrieve).toHaveBeenCalledTimes(2)+ })++ it('keeps polling through transient failures', async () => {+ mockRetrieve+ .mockRejectedValueOnce(new Error('502'))+ .mockRejectedValueOnce(new Error('timeout'))+ .mockResolvedValue({+ task_id: 'a',+ run_status: 'completed',+ is_terminal: true,+ pr_url: null,+ })++ const logic = flagCleanupTaskLogic({ experimentId: 1 })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ expect(mockRetrieve).toHaveBeenCalledTimes(1)++ // Two failures don't kill the poll — the third attempt succeeds and lands the result.+ await jest.advanceTimersByTimeAsync(30000)+ await jest.advanceTimersByTimeAsync(30000)+ expect(mockRetrieve).toHaveBeenCalledTimes(3)+ expect(logic.values.cleanupTask?.is_terminal).toBe(true)++ await jest.advanceTimersByTimeAsync(120000)+ expect(mockRetrieve).toHaveBeenCalledTimes(3)+ })+})diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.tsnew file mode 100644index 000000000000..3c2aac568364--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.ts@@ -0,0 +1,54 @@+import { afterMount, connect, kea, key, listeners, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import { projectLogic } from 'scenes/projectLogic'++import { experimentsFlagCleanupTaskRetrieve } from 'products/experiments/frontend/generated/api'+import type { ExperimentFlagCleanupTaskApi } from 'products/experiments/frontend/generated/api.schemas'++import type { flagCleanupTaskLogicType } from './flagCleanupTaskLogicType'++export interface FlagCleanupTaskLogicProps {+ experimentId: number+}++const POLL_INTERVAL_MS = 30000++export const flagCleanupTaskLogic = kea<flagCleanupTaskLogicType>([+ props({} as FlagCleanupTaskLogicProps),+ key((props) => props.experimentId),+ path((key) => ['scenes', 'experiments', 'flagCleanupTaskLogic', key]),+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),+ loaders(({ props, values }) => ({+ cleanupTask: [+ null as ExperimentFlagCleanupTaskApi | null,+ {+ loadCleanupTask: async () =>+ await experimentsFlagCleanupTaskRetrieve(String(values.currentProjectId), props.experimentId),+ },+ ],+ })),+ listeners(({ cache }) => ({+ loadCleanupTaskSuccess: ({ cleanupTask }) => {+ cache.pollFailures = 0+ if (cleanupTask?.is_terminal) {+ cache.disposables.dispose('cleanupTaskPoll')+ }+ },+ loadCleanupTaskFailure: () => {+ // Tolerate transient errors — the task may still finish. Stop only when the+ // endpoint fails persistently.+ cache.pollFailures = (cache.pollFailures ?? 0) + 1+ if (cache.pollFailures >= 3) {+ cache.disposables.dispose('cleanupTaskPoll')+ }+ },+ })),+ afterMount(({ actions, cache }) => {+ actions.loadCleanupTask()+ cache.disposables.add(() => {+ const id = setInterval(() => actions.loadCleanupTask(), POLL_INTERVAL_MS)+ return () => clearInterval(id)+ }, 'cleanupTaskPoll')+ }),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b4c827dc938d..34355fc51879 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4907,6 +4907,8 @@ export interface Experiment {_create_in_folder?: string | nullconclusion?: ExperimentConclusion | nullconclusion_comment?: string | null+ /** Code task opened to remove the experiment's flag code, when requested on end/ship. */+ flag_cleanup_task_id?: string | nulluser_access_level: AccessControlLevel}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 a8c3386ff01c..40964147722b 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@@ -213,6 +213,7 @@'exposure_criteria','feature_flag_auto_archived','filters',+ 'flag_cleanup_task_id','metrics','metrics_secondary','name',diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex f7195a53eceb..45bb10b789c1 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -566,6 +566,9 @@ SPECTACULAR_SETTINGS = {"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES","MCPInstallationScopeEnum": ["personal", "shared"],"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status",+ # Inline-choices variant of TaskRun.Status (labels == values), shared by+ # TaskRunUpdate.status and ExperimentFlagCleanupTask.run_status.+ "RunStatusEnum": ["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],"TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment","ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model","RecurrenceIntervalEnum": "products.reminders.backend.models.reminder.Reminder.RecurrenceInterval",diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 0e9d6af2317c..187e7430e3c1 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -2369,7 +2369,7 @@ class ExperimentService:def _open() -> None:try:- tasks_facade.create_and_run_task(+ created = tasks_facade.create_and_run_task(team=team,title=title,description=description,@@ -2380,6 +2380,12 @@ class ExperimentService:interaction_origin="experiments",ai_stage="implementation",)+ Experiment.objects.filter(id=experiment_id, team_id=team.id).update(+ flag_cleanup_task_id=created.task_id+ )+ # on_commit runs before the view serializes the response — reflect the id on the+ # in-memory instance so the end/ship response already carries it.+ experiment.flag_cleanup_task_id = created.task_idexcept Exception:logger.exception("experiment_cleanup_pr_task_failed", experiment_id=experiment_id)diff --git a/products/experiments/backend/migrations/0027_experiment_flag_cleanup_task_id.py b/products/experiments/backend/migrations/0027_experiment_flag_cleanup_task_id.pynew file mode 100644index 000000000000..96b977e45704--- /dev/null+++ b/products/experiments/backend/migrations/0027_experiment_flag_cleanup_task_id.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-10 11:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0026_strip_feature_flag_config_from_parameters"),+ ]++ operations = [+ migrations.AddField(+ model_name="experiment",+ name="flag_cleanup_task_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex da9d804e5dbf..4699de29c9af 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0026_strip_feature_flag_config_from_parameters+0027_experiment_flag_cleanup_task_iddiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 1edd10be458b..06f9e23c9640 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -138,6 +138,10 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.blank=True,)+ # Latest flag-cleanup Code task opened when this experiment ended. A bare UUID, not a FK —+ # tasks is an isolated product, so details are read through its facade.+ flag_cleanup_task_id = models.UUIDField(null=True, blank=True)+class Meta:db_table = "posthog_experiment"diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 1fd5dbeedd58..7f58cf2c02df 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -370,6 +370,15 @@ class ExperimentSerializer(ExperimentBaseSerializer):),)_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)+ flag_cleanup_task_id = serializers.UUIDField(+ read_only=True,+ allow_null=True,+ help_text=(+ "ID of the Code task opened to remove the experiment's feature-flag code, when one was "+ "requested via open_cleanup_pr on end/ship_variant. Read its status via the "+ "flag_cleanup_task action."+ ),+ )class Meta:model = Experiment@@ -406,6 +415,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):"_create_in_folder","conclusion","conclusion_comment",+ "flag_cleanup_task_id","primary_metrics_ordered_uuids","secondary_metrics_ordered_uuids","only_count_matured_users",@@ -1012,6 +1022,21 @@ class EndExperimentSerializer(serializers.Serializer):)+class ExperimentFlagCleanupTaskSerializer(serializers.Serializer):+ task_id = serializers.UUIDField(help_text="ID of the flag-cleanup Code task.")+ run_status = serializers.ChoiceField(+ choices=["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],+ help_text="Status of the task's latest run.",+ )+ is_terminal = serializers.BooleanField(+ help_text="Whether the run has finished (successfully or not). Stop polling once true."+ )+ pr_url = serializers.CharField(+ allow_null=True,+ help_text="URL of the pull request the task opened, when it opened one.",+ )++class ArchiveExperimentSerializer(serializers.Serializer):disable_feature_flag = serializers.BooleanField(default=False,diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 1a24d6d754d6..c80badb216ff 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -57,6 +57,7 @@ from products.experiments.backend.presentation.serializers import (CreateFromPromptInputSerializer,EndExperimentSerializer,ExperimentBasicSerializer,+ ExperimentFlagCleanupTaskSerializer,ExperimentMetricsRecalculationSerializer,ExperimentSerializer,ExperimentSessionContextResponseSerializer,@@ -91,6 +92,7 @@ from products.feature_flags.backend.models.evaluation_context import FeatureFlagfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey+from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.access import has_tasks_accesstracer = trace.get_tracer(__name__)@@ -567,6 +569,43 @@ class EnterpriseExperimentsViewSet()return Response(ExperimentSerializer(shipped_experiment, context=self.get_serializer_context()).data)+ @extend_schema(+ request=None,+ responses=ExperimentFlagCleanupTaskSerializer,+ )+ @action(methods=["GET"], detail=True, required_scopes=["experiment:read"])+ def flag_cleanup_task(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """+ Status of the flag-cleanup Code task opened for this experiment.++ When an experiment was ended or shipped with open_cleanup_pr=true, a Code task+ removes the experiment's feature-flag code and opens a draft pull request. This+ returns that task's latest run status and the PR URL once one is opened. Poll+ until is_terminal is true. Returns 404 when no cleanup task was opened.+ """+ experiment: Experiment = self.get_object()+ if not experiment.flag_cleanup_task_id:+ raise NotFound("No flag cleanup task was opened for this experiment.")+ # Read through the facade rather than the tasks API: cleanup tasks are creator-visible+ # there, but their status should be visible to everyone who can see the experiment.+ run = tasks_facade.get_latest_run_by_task([experiment.flag_cleanup_task_id]).get(+ str(experiment.flag_cleanup_task_id)+ )+ # The PR URL comes from the task run's output blob — only pass it through when it+ # actually points at GitHub, since the frontend renders it as a GitHub link.+ pr_url = run.pr_url if run else None+ if pr_url and not pr_url.startswith("https://github.com/"):+ pr_url = None+ response_serializer = ExperimentFlagCleanupTaskSerializer(+ {+ "task_id": experiment.flag_cleanup_task_id,+ "run_status": run.status if run else "queued",+ "is_terminal": run.is_terminal if run else False,+ "pr_url": pr_url,+ }+ )+ return Response(response_serializer.data)+@extend_schema(request=None,responses=ExperimentSerializer,diff --git a/products/experiments/backend/test/test_experiment_cleanup_pr.py b/products/experiments/backend/test/test_experiment_cleanup_pr.pyindex ea8608f4664e..f48f0831e363 100644--- a/products/experiments/backend/test/test_experiment_cleanup_pr.py+++ b/products/experiments/backend/test/test_experiment_cleanup_pr.py@@ -1,3 +1,6 @@+from types import SimpleNamespace+from uuid import uuid4+from posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -64,6 +67,8 @@ class TestExperimentCleanupPr(APIBaseTest):_mock_report,):mock_feature_enabled.return_value = flag_enabled+ task_id = uuid4()+ mock_create_task.return_value = SimpleNamespace(task_id=task_id)experiment = self._running_experiment()with self.captureOnCommitCallbacks(execute=True):@@ -74,11 +79,14 @@ class TestExperimentCleanupPr(APIBaseTest):request=self._make_request(),)+ experiment.refresh_from_db()if expect_task_created:mock_create_task.assert_called_once()kwargs = mock_create_task.call_args.kwargsself.assertEqual(kwargs["origin_product"], tasks_facade.TaskOriginProduct.EXPERIMENTS)self.assertEqual(kwargs["repository"], "PostHog/posthog")self.assertTrue(kwargs["create_pr"])+ self.assertEqual(experiment.flag_cleanup_task_id, task_id)else:mock_create_task.assert_not_called()+ self.assertIsNone(experiment.flag_cleanup_task_id)diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex f398e77e3428..0a1b499b9265 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -1,6 +1,7 @@from datetime import UTC, datetime, timedeltafrom types import SimpleNamespacefrom typing import Any, cast+from uuid import uuid4import unittestfrom freezegun import freeze_time@@ -5752,6 +5753,57 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):)self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ def test_flag_cleanup_task_endpoint(self):+ exp_id = self._create_running_experiment(name="Cleanup Status", flag_key="cleanup-status-flag")["id"]++ # No cleanup task opened yet.+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_task/")+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)++ task_id = uuid4()+ Experiment.objects.filter(id=exp_id).update(flag_cleanup_task_id=task_id)++ run = SimpleNamespace(+ status="completed",+ is_terminal=True,+ pr_url="https://github.com/PostHog/posthog/pull/123",+ )+ with patch(+ "products.experiments.backend.presentation.views.tasks_facade.get_latest_run_by_task",+ return_value={str(task_id): run},+ ):+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_task/")+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(+ resp.json(),+ {+ "task_id": str(task_id),+ "run_status": "completed",+ "is_terminal": True,+ "pr_url": "https://github.com/PostHog/posthog/pull/123",+ },+ )++ # A PR URL that doesn't point at GitHub is dropped rather than rendered as a link.+ run = SimpleNamespace(status="completed", is_terminal=True, pr_url="http://evil.example.com/pr/1")+ with patch(+ "products.experiments.backend.presentation.views.tasks_facade.get_latest_run_by_task",+ return_value={str(task_id): run},+ ):+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_task/")+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertIsNone(resp.json()["pr_url"])++ # Task recorded but no run row yet: reported as queued, non-terminal.+ with patch(+ "products.experiments.backend.presentation.views.tasks_facade.get_latest_run_by_task",+ return_value={},+ ):+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_task/")+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)+ self.assertEqual(resp.json()["run_status"], "queued")+ self.assertFalse(resp.json()["is_terminal"])+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.tsindex bc9d5f50b82f..8c166aace921 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1440,6 +1440,11 @@ export interface ExperimentWriteApi {* @nullable*/conclusion_comment?: string | null+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id: string | nullprimary_metrics_ordered_uuids?: unknownsecondary_metrics_ordered_uuids?: unknownonly_count_matured_users?: boolean@@ -1548,6 +1553,11 @@ export interface ExperimentApi {* @nullable*/conclusion_comment?: string | null+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id: string | nullprimary_metrics_ordered_uuids?: unknownsecondary_metrics_ordered_uuids?: unknownonly_count_matured_users?: boolean@@ -1652,6 +1662,11 @@ export interface PatchedExperimentWriteApi {* @nullable*/conclusion_comment?: string | null+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id?: string | nullprimary_metrics_ordered_uuids?: unknownsecondary_metrics_ordered_uuids?: unknownonly_count_matured_users?: boolean@@ -1703,6 +1718,46 @@ export interface EndExperimentApi {open_cleanup_pr?: boolean}+/**+ * * `not_started` - not_started+ * * `queued` - queued+ * * `in_progress` - in_progress+ * * `completed` - completed+ * * `failed` - failed+ * * `cancelled` - cancelled+ */+export type RunStatusEnumApi = (typeof RunStatusEnumApi)[keyof typeof RunStatusEnumApi]++export const RunStatusEnumApi = {+ NotStarted: 'not_started',+ Queued: 'queued',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+ Cancelled: 'cancelled',+} as const++export interface ExperimentFlagCleanupTaskApi {+ /** ID of the flag-cleanup Code task. */+ task_id: string+ /** Status of the task's latest run.+ *+ * * `not_started` - not_started+ * * `queued` - queued+ * * `in_progress` - in_progress+ * * `completed` - completed+ * * `failed` - failed+ * * `cancelled` - cancelled */+ run_status: RunStatusEnumApi+ /** Whether the run has finished (successfully or not). Stop polling once true. */+ is_terminal: boolean+ /**+ * URL of the pull request the task opened, when it opened one.+ * @nullable+ */+ pr_url: string | null+}+/*** * `manual` - Manual* * `cold_run` - Cold Rundiff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 56502ec80b73..7736419d92be 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -14,6 +14,7 @@ import type {CreateFromPromptInputApi,EndExperimentApi,ExperimentApi,+ ExperimentFlagCleanupTaskApi,ExperimentHoldoutApi,ExperimentHoldoutsListParams,ExperimentMetricsRecalculationApi,@@ -542,6 +543,29 @@ export const experimentsEndCreate = async (})}+export const getExperimentsFlagCleanupTaskRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/flag_cleanup_task/`+}++/**+ * Status of the flag-cleanup Code task opened for this experiment.+ *+ * When an experiment was ended or shipped with open_cleanup_pr=true, a Code task+ * removes the experiment's feature-flag code and opens a draft pull request. This+ * returns that task's latest run status and the PR URL once one is opened. Poll+ * until is_terminal is true. Returns 404 when no cleanup task was opened.+ */+export const experimentsFlagCleanupTaskRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentFlagCleanupTaskApi> => {+ return apiMutator<ExperimentFlagCleanupTaskApi>(getExperimentsFlagCleanupTaskRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getExperimentsFreezeExposureCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/freeze_exposure/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 2ca40c26ec90..d915cb052d6c 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -1036,6 +1036,9 @@ tools:experiments-eligible-feature-flags:operation: experiments_eligible_feature_flags_retrieveenabled: false+ experiments-flag-cleanup-task-retrieve:+ operation: experiments_flag_cleanup_task_retrieve+ enabled: falseexperiments-freeze-exposure-create:operation: experiments_freeze_exposure_createenabled: falsediff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 780adb48b4f3..930e914c9be3 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -1354,7 +1354,8 @@"posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",- "posthog_experiment"."conclusion_comment"+ "posthog_experiment"."conclusion_comment",+ "posthog_experiment"."flag_cleanup_task_id"FROM "posthog_experiment"WHERE "posthog_experiment"."exposure_cohort_id" = 99999'''@@ -1700,7 +1701,8 @@"posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",- "posthog_experiment"."conclusion_comment"+ "posthog_experiment"."conclusion_comment",+ "posthog_experiment"."flag_cleanup_task_id"FROM "posthog_experiment"WHERE (NOT "posthog_experiment"."deleted"AND "posthog_experiment"."feature_flag_id" IN (1,diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 4d56c3a7f616..fdeb341fea22 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1896,7 +1896,8 @@"posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",- "posthog_experiment"."conclusion_comment"+ "posthog_experiment"."conclusion_comment",+ "posthog_experiment"."flag_cleanup_task_id"FROM "posthog_experiment"WHERE ("posthog_experiment"."feature_flag_id" = 99999AND NOT "posthog_experiment"."deleted")@@ -1975,7 +1976,8 @@"posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",- "posthog_experiment"."conclusion_comment"+ "posthog_experiment"."conclusion_comment",+ "posthog_experiment"."flag_cleanup_task_id"FROM "posthog_experiment"WHERE ("posthog_experiment"."feature_flag_id" = 99999AND NOT "posthog_experiment"."deleted")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex b45469af8e4c..6f8eb7560239 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1664,9 +1664,9 @@ export interface TaskRunBootstrapCreateRequestApi {* * `failed` - failed* * `cancelled` - cancelled*/-export type TaskRunUpdateStatusEnumApi = (typeof TaskRunUpdateStatusEnumApi)[keyof typeof TaskRunUpdateStatusEnumApi]+export type RunStatusEnumApi = (typeof RunStatusEnumApi)[keyof typeof RunStatusEnumApi]-export const TaskRunUpdateStatusEnumApi = {+export const RunStatusEnumApi = {NotStarted: 'not_started',Queued: 'queued',InProgress: 'in_progress',@@ -1694,7 +1694,7 @@ export interface PatchedTaskRunUpdateApi {* * `completed` - completed* * `failed` - failed* * `cancelled` - cancelled */- status?: TaskRunUpdateStatusEnumApi+ status?: RunStatusEnumApi/*** Git branch name to associate with the task* @nullablediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8a2910a5458c..ac638aea3edc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24423,6 +24423,11 @@ export namespace Schemas {* @nullable*/conclusion_comment?: string | null;+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id: string | null;primary_metrics_ordered_uuids?: unknown;secondary_metrics_ordered_uuids?: unknown;only_count_matured_users?: boolean;@@ -24687,6 +24692,47 @@ export namespace Schemas {ensure_experience_continuity?: boolean | null;}+ /**+ * * `not_started` - not_started+ * * `queued` - queued+ * * `in_progress` - in_progress+ * * `completed` - completed+ * * `failed` - failed+ * * `cancelled` - cancelled+ */+ export type RunStatusEnum = typeof RunStatusEnum[keyof typeof RunStatusEnum];+++ export const RunStatusEnum = {+ NotStarted: 'not_started',+ Queued: 'queued',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+ Cancelled: 'cancelled',+ } as const;++ export interface ExperimentFlagCleanupTask {+ /** ID of the flag-cleanup Code task. */+ task_id: string;+ /** Status of the task's latest run.+ *+ * * `not_started` - not_started+ * * `queued` - queued+ * * `in_progress` - in_progress+ * * `completed` - completed+ * * `failed` - failed+ * * `cancelled` - cancelled */+ run_status: RunStatusEnum;+ /** Whether the run has finished (successfully or not). Stop polling once true. */+ is_terminal: boolean;+ /**+ * URL of the pull request the task opened, when it opened one.+ * @nullable+ */+ pr_url: string | null;+ }+/*** * `categorical` - categorical* * `numeric` - numeric@@ -25070,6 +25116,11 @@ export namespace Schemas {* @nullable*/conclusion_comment?: string | null;+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id: string | null;primary_metrics_ordered_uuids?: unknown;secondary_metrics_ordered_uuids?: unknown;only_count_matured_users?: boolean;@@ -43233,6 +43284,11 @@ export namespace Schemas {* @nullable*/conclusion_comment?: string | null;+ /**+ * ID of the Code task opened to remove the experiment's feature-flag code, when one was requested via open_cleanup_pr on end/ship_variant. Read its status via the flag_cleanup_task action.+ * @nullable+ */+ readonly flag_cleanup_task_id?: string | null;primary_metrics_ordered_uuids?: unknown;secondary_metrics_ordered_uuids?: unknown;only_count_matured_users?: boolean;@@ -47454,26 +47510,6 @@ export namespace Schemas {output?: unknown;}- /**- * * `not_started` - not_started- * * `queued` - queued- * * `in_progress` - in_progress- * * `completed` - completed- * * `failed` - failed- * * `cancelled` - cancelled- */- export type TaskRunUpdateStatusEnum = typeof TaskRunUpdateStatusEnum[keyof typeof TaskRunUpdateStatusEnum];--- export const TaskRunUpdateStatusEnum = {- NotStarted: 'not_started',- Queued: 'queued',- InProgress: 'in_progress',- Completed: 'completed',- Failed: 'failed',- Cancelled: 'cancelled',- } as const;-/*** * `local` - local*/@@ -47493,7 +47529,7 @@ export namespace Schemas {* * `completed` - completed* * `failed` - failed* * `cancelled` - cancelled */- status?: TaskRunUpdateStatusEnum;+ status?: RunStatusEnum;/*** Git branch name to associate with the task* @nullable