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): log feature-flag cleanup when an experiment ends (#67091)

Juraj Majerik670ce88711c2
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 6afb073ae5e8..42330c931034 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -16,6 +16,7 @@ from django.utils import timezone
import pydantic
import structlog
+import posthoganalytics
from rest_framework.exceptions import PermissionDenied, ValidationError
from posthog.schema import (
@@ -40,6 +41,7 @@ from posthog.utils import str_to_bool
from products.actions.backend.models.action import Action
from products.approvals.backend.policies import PolicyEngine
from products.cohorts.backend.models.cohort import Cohort
+from products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan
from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
@@ -79,6 +81,9 @@ from ee.hogai.context.experiment.format import ExperimentTimeseriesFormatter
logger = structlog.get_logger(__name__)
+# Gates the (log-only for now) experiment-end -> cleanup-PR trigger; enable it per-project in the app.
+EXPERIMENT_CLEANUP_PR_FLAG = "experiment-flag-cleanup-pr"
+
DEFAULT_ROLLOUT_PERCENTAGE = 100
ExperimentCreationMode = Literal["new", "duplicate", "copy_to_project"]
@@ -1712,6 +1717,46 @@ class ExperimentService:
return experiment
+ def _log_cleanup_pr_preview(self, experiment: Experiment) -> None:
+ """Behind a team feature flag, log the cleanup-PR instructions we would open (no PR yet).
+
+ Log-only first step of the experiment-end -> cleanup-PR feature: lets us see, on real
+ experiments, whether the trigger fires and whether the generated instructions look right,
+ before wiring up the coding agent. Never raises — a preview must not break ending an experiment.
+ """
+ try:
+ enabled = posthoganalytics.feature_enabled(
+ EXPERIMENT_CLEANUP_PR_FLAG,
+ str(self.team.id),
+ groups={"project": str(self.team.id)},
+ group_properties={"project": {"id": str(self.team.id)}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ conclusion = experiment.conclusion or ""
+ if not enabled or not conclusion:
+ return
+
+ flag_key = experiment.get_feature_flag_key()
+ plan = cleanup_plan(conclusion, experiment.feature_flag.variants or [])
+ # Build the prompt to catch render errors on real data, but don't log its body: it
+ # embeds the experiment name and full instructions, and these logs are exported widely.
+ # The structured fields below are enough to confirm the trigger fired and the decision.
+ title, _ = build_cleanup_prompt(experiment, flag_key, plan)
+ logger.info(
+ "experiment_cleanup_pr_preview",
+ experiment_id=experiment.id,
+ team_id=experiment.team_id,
+ flag_key=flag_key,
+ conclusion=conclusion,
+ keep_variant=plan.keep_variant,
+ remove_variants=plan.remove_variants,
+ confident=plan.confident,
+ pr_title=title,
+ )
+ except Exception:
+ logger.exception("experiment_cleanup_pr_preview_failed", experiment_id=experiment.id)
+
def _report_experiment_ended(
self,
experiment: Experiment,
@@ -1721,6 +1766,8 @@ class ExperimentService:
if request is None:
return
+ self._log_cleanup_pr_preview(experiment)
+
completed_metadata = experiment.get_analytics_metadata()
completed_metadata["end_date"] = experiment.end_date.isoformat() if experiment.end_date else None
completed_metadata["parameters"] = experiment.parameters
diff --git a/products/experiments/backend/flag_cleanup.py b/products/experiments/backend/flag_cleanup.py
new file mode 100644
index 000000000000..0ed349e15479
--- /dev/null
+++ b/products/experiments/backend/flag_cleanup.py
@@ -0,0 +1,148 @@
+"""Decide how to tidy up an experiment's feature-flag code, and build the agent's cleanup prompt.
+
+Pure logic shared by the manual command and (later) the automatic experiment-end trigger:
+from an experiment's outcome and its flag variants, pick which variant's code path to keep,
+then render the instructions handed to the coding agent.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from products.experiments.backend.models.experiment import Experiment
+
+
+CONCLUSION_LABELS = {
+ "won": "won",
+ "lost": "lost",
+ "inconclusive": "inconclusive",
+ "stopped_early": "stopped early",
+ "invalid": "invalid",
+}
+
+# PostHog SDK calls that read a flag, across languages — what the agent greps for.
+FLAG_SDK_CALLS = (
+ "isFeatureEnabled, getFeatureFlag, getFeatureFlagPayload, useFeatureFlag, useActiveFeatureFlags, "
+ "onFeatureFlags, posthog.isFeatureEnabled, posthog.getFeatureFlag, feature_enabled, get_feature_flag"
+)
+
+
+@dataclass(frozen=True)
+class CleanupPlan:
+ keep_variant: str | None
+ remove_variants: list[str]
+ rationale: str
+ confident: bool
+
+
+def variant_keys(variants: list[dict]) -> list[str]:
+ return [v["key"] for v in variants if v.get("key")]
+
+
+def _fully_rolled_out_variant(variants: list[dict]) -> str | None:
+ """After "ship a variant", the winner sits at 100% — return it if exactly one does."""
+ at_100 = [v["key"] for v in variants if v.get("rollout_percentage") == 100 and v.get("key")]
+ return at_100[0] if len(at_100) == 1 else None
+
+
+def cleanup_plan(conclusion: str, variants: list[dict]) -> CleanupPlan:
+ """Decide which variant's code path to keep, from the outcome and the flag's variants.
+
+ "won" keeps the shipped variant (the one rolled out to 100%); a plain win with nothing
+ shipped falls back to the single non-control variant as a best guess. Every other
+ outcome rolls back to the baseline ("control"). Anything uncertain is marked so the
+ operator (and the PR) flag it for human review rather than guessing silently.
+ """
+ keys = variant_keys(variants)
+ non_control = [k for k in keys if k != "control"]
+ has_control = "control" in keys
+
+ def plan(keep: str | None, rationale: str, confident: bool) -> CleanupPlan:
+ return CleanupPlan(
+ keep_variant=keep,
+ remove_variants=[k for k in keys if k != keep],
+ rationale=rationale,
+ confident=confident,
+ )
+
+ if conclusion == "won":
+ shipped = _fully_rolled_out_variant(variants)
+ if shipped:
+ return plan(
+ shipped,
+ f'The experiment won and variant "{shipped}" was shipped (100% rollout). Keep it as the new default.',
+ True,
+ )
+ if len(non_control) == 1:
+ return plan(
+ non_control[0],
+ f'The experiment won but no variant is at 100% rollout. Best guess: keep the winning variant "{non_control[0]}". Confirm which variant you kept in the PR.',
+ False,
+ )
+ return plan(
+ None,
+ "The experiment won, but the winning variant can't be determined automatically (more than one non-control variant). Decide per code site and explain your choice in the PR.",
+ False,
+ )
+
+ keep = "control" if has_control else (keys[0] if keys else None)
+ if conclusion in ("lost", "invalid"):
+ return plan(
+ keep,
+ f'The experiment {CONCLUSION_LABELS.get(conclusion, conclusion)}. Roll back to the baseline: keep "{keep}" and remove the feature.',
+ True,
+ )
+ return plan(
+ keep,
+ f'The experiment was {CONCLUSION_LABELS.get(conclusion, conclusion)}. Defaulting to the baseline "{keep}" — confirm this is the rollback you want.',
+ False,
+ )
+
+
+def build_cleanup_prompt(experiment: Experiment, flag_key: str, plan: CleanupPlan) -> tuple[str, str]:
+ """Return (title, description) — the task title and the agent's full instructions."""
+ title = f"Clean up feature flag {flag_key} after experiment {experiment.id}"
+ remove = ", ".join(f'"{k}"' for k in plan.remove_variants) or "(none)"
+ keep_line = (
+ f'- Keep the code path for variant "{plan.keep_variant}".'
+ if plan.keep_variant
+ else "- Keep the winning variant's code path (decide per site — see the note below)."
+ )
+ variants = ", ".join(variant_keys(experiment.feature_flag.variants or [])) or "(boolean / none)"
+
+ description = "\n".join(
+ [
+ "Remove the scaffolding for a PostHog experiment feature flag that is no longer needed, and open a draft pull request.",
+ "",
+ f'Experiment: "{experiment.name}" (id {experiment.id})',
+ f"Outcome: {CONCLUSION_LABELS.get(experiment.conclusion or '', experiment.conclusion or 'unknown')}",
+ f'Feature flag key: "{flag_key}"',
+ f"Flag variants: {variants}",
+ "",
+ "## What to change",
+ f'Remove all references to the feature flag "{flag_key}" from this codebase and keep the correct code path.',
+ keep_line,
+ f"- Remove the code paths for variant(s): {remove}.",
+ f'- Remove every check of the flag "{flag_key}" itself.',
+ "",
+ f"Why: {plan.rationale}",
+ "",
+ "## How to find the references",
+ f'Search the repo for the flag key "{flag_key}" and for PostHog SDK calls that read flags, e.g.:',
+ f" {FLAG_SDK_CALLS}",
+ "Cover every language used in the repo (JS/TS, Python, Go, Ruby, PHP, etc.).",
+ "",
+ "## Rules",
+ "- For the kept variant: keep that branch's body, delete the surrounding flag check and the other branches.",
+ "- Boolean-style checks: keep the enabled path's body and drop the if-check (and any else branch).",
+ "- Remove the now-dead code you create: orphaned branches, unused imports, unused helpers.",
+ "- Code only. Do NOT change the flag in PostHog, and do NOT touch unrelated code.",
+ "- If the correct path is genuinely ambiguous at a site, leave it unchanged and list it in the PR description for a human to review.",
+ "",
+ "## Output",
+ f'Open a draft pull request titled "{title}". In the description, summarise what you removed and anything you left for manual review.',
+ ]
+ )
+ return title, description
diff --git a/products/experiments/backend/test/test_flag_cleanup.py b/products/experiments/backend/test/test_flag_cleanup.py
new file mode 100644
index 000000000000..d6929c74389b
--- /dev/null
+++ b/products/experiments/backend/test/test_flag_cleanup.py
@@ -0,0 +1,57 @@
+from unittest import TestCase
+
+from parameterized import parameterized
+
+from products.experiments.backend.flag_cleanup import cleanup_plan
+
+
+def _variants(*pairs: tuple[str, int]) -> list[dict]:
+ return [{"key": key, "rollout_percentage": pct} for key, pct in pairs]
+
+
+class TestCleanupPlan(TestCase):
+ @parameterized.expand(
+ [
+ # (name, conclusion, variants, keep, remove, confident)
+ ("won_shipped", "won", _variants(("control", 0), ("test", 100)), "test", {"control"}, True),
+ # A shipped variant (at 100%) wins even among several — precedence over the ambiguity branch below.
+ (
+ "won_shipped_among_many",
+ "won",
+ _variants(("control", 0), ("red", 0), ("blue", 100)),
+ "blue",
+ {"control", "red"},
+ True,
+ ),
+ # Won but nothing shipped: single non-control is a best guess, flagged low-confidence.
+ ("won_unshipped_single", "won", _variants(("control", 50), ("test", 50)), "test", {"control"}, False),
+ # Won but nothing shipped and multiple non-control: don't guess — keep nothing, low-confidence.
+ (
+ "won_unshipped_ambiguous",
+ "won",
+ _variants(("control", 34), ("red", 33), ("blue", 33)),
+ None,
+ {"control", "red", "blue"},
+ False,
+ ),
+ ("lost", "lost", _variants(("control", 50), ("test", 50)), "control", {"test"}, True),
+ ("invalid", "invalid", _variants(("control", 50), ("test", 50)), "control", {"test"}, True),
+ ("inconclusive", "inconclusive", _variants(("control", 50), ("test", 50)), "control", {"test"}, False),
+ ("stopped_early", "stopped_early", _variants(("control", 50), ("test", 50)), "control", {"test"}, False),
+ # No variant named "control": baseline falls back to the first variant.
+ (
+ "no_control_fallback",
+ "lost",
+ _variants(("baseline", 50), ("variant", 50)),
+ "baseline",
+ {"variant"},
+ True,
+ ),
+ ]
+ )
+ def test_cleanup_plan(self, _name, conclusion, variants, keep, remove, confident):
+ plan = cleanup_plan(conclusion, variants)
+
+ self.assertEqual(plan.keep_variant, keep)
+ self.assertEqual(set(plan.remove_variants), remove)
+ self.assertEqual(plan.confident, confident)