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.

fix(experiments): harden flag cleanup task surfacing (#72558)

Juraj Majerik01197a88ce80
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6c2049d91728..f2eb681dcac7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5561,7 +5561,7 @@ snapshots:
scenes-app-dashboards--show-with-post-hog-ai-button-label--narrow--dark:
hash: v1.k794b7964.4ea07e704d46a0495dbae82890a560c28670e24a9b71c6d63cdb1580151a5121.b_5FvU7MoXFArf7g9EhkXw0JiH3d-_Vmnbm3IR6gIcA
scenes-app-dashboards--show-with-post-hog-ai-button-label--narrow--light:
- hash: v1.k794b7964.e6a99deaafbd0220dbe5b084e809b2c09113f273c108b48ec57b6e37720edd52.0BGQiapG0F1x-wxc3GDV0H-f2u2BnuvjmryXRmFAG-U
+ hash: v1.k794b7964.8b1d5f4429205bae6f3c4e64504ccd9b955562bec56305007e6c1fb51e6ffe5b.QySWRC-c3Mv7MNu-en264VVr5fVutfuibWDszuJ8tW0
scenes-app-dashboards--show-with-post-hog-ai-button-label--superwide--dark:
hash: v1.k794b7964.68a378f55241be720f381165043d30d595927581e0cb8a397e937bdaa25f78fc.Yk-xHi3W1TbkCiOLeqgTb_kYvzodmeG3UbvGlz56vj4
scenes-app-dashboards--show-with-post-hog-ai-button-label--superwide--light:
@@ -5577,7 +5577,7 @@ snapshots:
scenes-app-dashboards--show-without-post-hog-ai-button-label--narrow--dark:
hash: v1.k794b7964.88687d2cc1bbd12296214f07d5f6bb2548705ae3baae37985858225116896a10.YogXGZXR1uFB4qD8nOjCfWyWL--g1SLKNxz0gZvEoWw
scenes-app-dashboards--show-without-post-hog-ai-button-label--narrow--light:
- hash: v1.k794b7964.e73cea1e916b6bc329aea490ca111439f3bebfa3dbae2d54ad54e5a174651057.7cswn9IwKIF60hyao0mI2skKmlWjur4GWI1cCisomlE
+ hash: v1.k794b7964.a9b595c0772470f298a96673401017972ef63e86c9d8f7a27a322fc2816b657f.o9Q27Snb2Dq5jfLqR_31n-mIpRmNJ8AXsge7mRbXads
scenes-app-dashboards--show-without-post-hog-ai-button-label--superwide--dark:
hash: v1.k794b7964.cad32a04659183c6bfecbc34e5ae23c08c095f70df65ef0ee7d863d2103a124d.2bYQoklhY3opedkpy5pUC52pEvCwdnEfKowjCBPaDb8
scenes-app-dashboards--show-without-post-hog-ai-button-label--superwide--light:
diff --git a/frontend/src/scenes/experiments/ExperimentView/Info.tsx b/frontend/src/scenes/experiments/ExperimentView/Info.tsx
index a74c863664e8..cce6e6dabdbd 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Info.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Info.tsx
@@ -32,13 +32,11 @@ function FlagCleanupLine({ experimentId, taskId }: { experimentId: number; taskI
}
let text = 'Preparing cleanup PR…'
- let linkText = 'View task'
- let to = urls.taskDetail(taskId)
+ let prUrl: string | null = null
if (cleanupTask.is_terminal) {
if (cleanupTask.run_status === 'completed' && cleanupTask.pr_url) {
text = 'Cleanup PR opened'
- linkText = 'View on GitHub'
- to = cleanupTask.pr_url
+ prUrl = cleanupTask.pr_url
} else if (cleanupTask.run_status === 'completed') {
text = 'Cleanup found no flag code to remove'
} else if (cleanupTask.run_status === 'failed') {
@@ -48,16 +46,31 @@ function FlagCleanupLine({ experimentId, taskId }: { experimentId: number; taskI
}
}
+ const isExternalLink = prUrl !== null
+ // The task page 404s for everyone but the task's creator — hide the internal link from others.
+ const showLink = isExternalLink || cleanupTask.can_view_task
+
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>
+ {text}
+ {showLink && (
+ <>
+ ·
+ <Link
+ target={isExternalLink ? '_blank' : undefined}
+ className="flex items-center gap-0.5"
+ to={prUrl ?? urls.taskDetail(taskId)}
+ >
+ {isExternalLink ? (
+ <>
+ View on GitHub <IconOpenInNew fontSize="12" />
+ </>
+ ) : (
+ 'View task'
+ )}
+ </Link>
+ </>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
index 08230c28e683..a8c9614160e6 100644
--- a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTaskLogic.test.ts
@@ -28,12 +28,14 @@ describe('flagCleanupTaskLogic', () => {
run_status: 'in_progress',
is_terminal: false,
pr_url: null,
+ can_view_task: true,
})
.mockResolvedValue({
task_id: 'a',
run_status: 'completed',
is_terminal: true,
pr_url: 'https://github.com/PostHog/posthog/pull/1',
+ can_view_task: true,
})
const logic = flagCleanupTaskLogic({ experimentId: 1 })
@@ -59,6 +61,7 @@ describe('flagCleanupTaskLogic', () => {
run_status: 'completed',
is_terminal: true,
pr_url: null,
+ can_view_task: true,
})
const logic = flagCleanupTaskLogic({ experimentId: 1 })
@@ -75,4 +78,19 @@ describe('flagCleanupTaskLogic', () => {
await jest.advanceTimersByTimeAsync(120000)
expect(mockRetrieve).toHaveBeenCalledTimes(3)
})
+
+ it('stops polling after three consecutive failures', async () => {
+ mockRetrieve.mockRejectedValue(new Error('502'))
+
+ const logic = flagCleanupTaskLogic({ experimentId: 1 })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(0)
+ await jest.advanceTimersByTimeAsync(30000)
+ await jest.advanceTimersByTimeAsync(30000)
+ expect(mockRetrieve).toHaveBeenCalledTimes(3)
+
+ // Persistent failure — the interval is disposed, no further requests.
+ await jest.advanceTimersByTimeAsync(120000)
+ expect(mockRetrieve).toHaveBeenCalledTimes(3)
+ })
})
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.ambr
index aa7cc192810b..47000436c4f7 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
@@ -68,6 +68,7 @@
'created_at',
'deleted',
'end_date',
+ 'flag_cleanup_task_id',
'start_date',
'status',
'updated_at',
@@ -211,7 +212,6 @@
'exposure_criteria',
'feature_flag_auto_archived',
'filters',
- 'flag_cleanup_task_id',
'metrics',
'metrics_secondary',
'name',
@@ -698,6 +698,7 @@
'experimenttosavedmetric_set',
'exposure_cohort_id',
'feature_flag_id',
+ 'flag_cleanup_task_id',
'freeze_exposure_blocker',
'get_analytics_metadata',
'get_conclusion_display',
diff --git a/posthog/models/resource_transfer/visitors/experiment.py b/posthog/models/resource_transfer/visitors/experiment.py
index 64fe9fa02afc..a497c433ff1c 100644
--- a/posthog/models/resource_transfer/visitors/experiment.py
+++ b/posthog/models/resource_transfer/visitors/experiment.py
@@ -28,6 +28,7 @@ class ExperimentVisitor(
"status",
"conclusion",
"conclusion_comment",
+ "flag_cleanup_task_id",
"created_at",
"updated_at",
],
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 36a628e502e1..126474448b6f 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -2375,7 +2375,9 @@ class ExperimentService:
interaction_origin="experiments",
ai_stage="implementation",
)
- Experiment.objects.filter(id=experiment_id, team_id=team.id).update(
+ # A concurrent reset may have already returned the experiment to draft —
+ # only attach the pointer while it is still ended.
+ Experiment.objects.filter(id=experiment_id, team_id=team.id, end_date__isnull=False).update(
flag_cleanup_task_id=created.task_id
)
# on_commit runs before the view serializes the response — reflect the id on the
@@ -2519,6 +2521,9 @@ class ExperimentService:
experiment.archived = False
experiment.conclusion = None
experiment.conclusion_comment = None
+ # The cleanup task belongs to the ended run — keeping the pointer would resurrect a
+ # stale "Cleanup PR opened" line after the experiment is re-ended without opting in.
+ experiment.flag_cleanup_task_id = None
experiment.save()
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 533d3a7fc983..a2233982f273 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1035,6 +1035,12 @@ class ExperimentFlagCleanupTaskSerializer(serializers.Serializer):
allow_null=True,
help_text="URL of the pull request the task opened, when it opened one.",
)
+ can_view_task = serializers.BooleanField(
+ help_text=(
+ "Whether the requesting user can open the task in PostHog Code. Cleanup tasks are "
+ "visible to their creator only, so other viewers should not be shown a task link."
+ ),
+ )
class ArchiveExperimentSerializer(serializers.Serializer):
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 642e86376ba2..7b8116f83865 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -589,6 +589,11 @@ class EnterpriseExperimentsViewSet(
run = tasks_facade.get_latest_run_by_task([experiment.flag_cleanup_task_id]).get(
str(experiment.flag_cleanup_task_id)
)
+ # get_latest_run_by_task filters by task id only. After a project transfer the
+ # experiment can point at a task in the old team — treat that run as absent rather
+ # than leaking its status across teams.
+ if run is not None and run.team_id != experiment.team_id:
+ run = None
# 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
@@ -600,6 +605,11 @@ class EnterpriseExperimentsViewSet(
"run_status": run.status if run else "queued",
"is_terminal": run.is_terminal if run else False,
"pr_url": pr_url,
+ # Whether the tasks API would let this user open the task page — cleanup
+ # tasks are creator-visible there today, so hide the link from everyone else.
+ "can_view_task": tasks_facade.task_visible(
+ experiment.flag_cleanup_task_id, self.team.pk, cast(User, request.user).id
+ ),
}
)
return Response(response_serializer.data)
@@ -697,8 +707,9 @@ class EnterpriseExperimentsViewSet(
"""
Reset an experiment back to draft state.
- Clears start/end dates, conclusion, and archived flag. The feature
- flag is left unchanged — users continue to see their assigned variants.
+ Clears start/end dates, conclusion, archived flag, and any flag-cleanup
+ task pointer. The feature flag is left unchanged — users continue to see
+ their assigned variants.
Previously collected events still exist but won't be included in
results unless the start date is manually adjusted after re-launch.
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index b806b95b71fb..7103f50f0445 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -4,7 +4,7 @@ from copy import deepcopy
from datetime import timedelta
from decimal import Decimal
from typing import Any
-from uuid import UUID
+from uuid import UUID, uuid4
import pytest
from posthog.test.base import APIBaseTest
@@ -4193,6 +4193,8 @@ class TestExperimentService(APIBaseTest):
else:
experiment = self._create_ended_experiment(name="Reset Ended", feature_flag_key=f"reset-{state}-flag")
assert experiment.is_stopped
+ experiment.flag_cleanup_task_id = uuid4()
+ experiment.save()
reset = self._service().reset_experiment(experiment)
@@ -4203,6 +4205,7 @@ class TestExperimentService(APIBaseTest):
assert reset.archived is False
assert reset.conclusion is None
assert reset.conclusion_comment is None
+ assert reset.flag_cleanup_task_id is None
def test_reset_experiment_leaves_feature_flag_unchanged(self):
experiment = self._create_running_experiment(name="Reset Flag", feature_flag_key="reset-flag-unchanged")
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index b16a9d0ddbb3..4933f6b1d8fc 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -5718,10 +5718,17 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
status="completed",
is_terminal=True,
pr_url="https://github.com/PostHog/posthog/pull/123",
+ team_id=self.team.id,
)
- with patch(
- "products.experiments.backend.presentation.views.tasks_facade.get_latest_run_by_task",
- return_value={str(task_id): run},
+ with (
+ patch(
+ "products.experiments.backend.presentation.views.tasks_facade.get_latest_run_by_task",
+ return_value={str(task_id): run},
+ ),
+ patch(
+ "products.experiments.backend.presentation.views.tasks_facade.task_visible",
+ return_value=True,
+ ) as mock_task_visible,
):
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)
@@ -5732,17 +5739,47 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
"run_status": "completed",
"is_terminal": True,
"pr_url": "https://github.com/PostHog/posthog/pull/123",
+ "can_view_task": True,
},
)
+ mock_task_visible.assert_called_once_with(task_id, self.team.pk, self.user.id)
+
+ # No Task row exists for this id, so the real visibility check reports False.
+ 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.assertFalse(resp.json()["can_view_task"])
# 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")
+ run = SimpleNamespace(
+ status="completed", is_terminal=True, pr_url="http://evil.example.com/pr/1", team_id=self.team.id
+ )
+ 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"])
+
+ # A run in another team (experiment transferred across projects) is treated as absent.
+ run = SimpleNamespace(
+ status="completed",
+ is_terminal=True,
+ pr_url="https://github.com/PostHog/posthog/pull/123",
+ team_id=self.team.id + 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.assertEqual(resp.json()["run_status"], "queued")
+ self.assertFalse(resp.json()["is_terminal"])
self.assertIsNone(resp.json()["pr_url"])
# Task recorded but no run row yet: reported as queued, non-terminal.
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index d70c42a7d54b..86281ffc4840 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1766,6 +1766,8 @@ export interface ExperimentFlagCleanupTaskApi {
* @nullable
*/
pr_url: string | null
+ /** Whether the requesting user can open the task in PostHog Code. Cleanup tasks are visible to their creator only, so other viewers should not be shown a task link. */
+ can_view_task: boolean
}
/**
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 915311226080..c64bc9d141f4 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -755,8 +755,9 @@ export const getExperimentsResetCreateUrl = (projectId: string, id: number) => {
/**
* Reset an experiment back to draft state.
*
- * Clears start/end dates, conclusion, and archived flag. The feature
- * flag is left unchanged — users continue to see their assigned variants.
+ * Clears start/end dates, conclusion, archived flag, and any flag-cleanup
+ * task pointer. The feature flag is left unchanged — users continue to see
+ * their assigned variants.
*
* Previously collected events still exist but won't be included in
* results unless the start date is manually adjusted after re-launch.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 19843256c0e4..7ea601bb3be3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26837,6 +26837,8 @@ export namespace Schemas {
* @nullable
*/
pr_url: string | null;
+ /** Whether the requesting user can open the task in PostHog Code. Cleanup tasks are visible to their creator only, so other viewers should not be shown a task link. */
+ can_view_task: boolean;
}
/**
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index d37a9bbb0db7..54d5f10bc3c3 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -11642,8 +11642,9 @@ export const ExperimentsPauseCreateParams = /* @__PURE__ */ zod.object({
/**
* Reset an experiment back to draft state.
*
- * Clears start/end dates, conclusion, and archived flag. The feature
- * flag is left unchanged — users continue to see their assigned variants.
+ * Clears start/end dates, conclusion, archived flag, and any flag-cleanup
+ * task pointer. The feature flag is left unchanged — users continue to see
+ * their assigned variants.
*
* Previously collected events still exist but won't be included in
* results unless the start date is manually adjusted after re-launch.