: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
fix(flags): block bulk deleting a flag used in session replay (#80998)
Phil Haackb911ca14445a
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 945f9223c1d1..270f79e6bd95 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -114,7 +114,11 @@ from products.feature_flags.backend.flag_status import (from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filtersfrom products.feature_flags.backend.models.evaluation_context import normalize_context_namefrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards-from products.feature_flags.backend.session_recording_links import teams_linking_flag+from products.feature_flags.backend.session_recording_links import (+ REPLAY_LINKED_FLAG_DELETE_ERROR,+ replay_linked_flag_ids,+ teams_linking_flag,+)from products.feature_flags.backend.types import PropertyFilterTypefrom products.feature_flags.backend.user_blast_radius import get_user_blast_radiusfrom products.feature_flags.backend.version_history import (@@ -2057,9 +2061,7 @@ class FeatureFlagSerializer(# Check if flag is used in session replay settingsif teams_linking_flag(instance).exists():- raise exceptions.ValidationError(- "This feature flag is used in session replay settings. Please remove it from replay settings before deleting."- )+ raise exceptions.ValidationError(REPLAY_LINKED_FLAG_DELETE_ERROR)# If the flag is linked to any experiment, rename the key to free it up.# Append ID to the key when soft-deleting to prevent key conflicts.@@ -3752,6 +3754,8 @@ class FeatureFlagViewSet(# Batch query for dependent flagsdependent_flags_map = find_dependent_flags_batch(flags_list)+ replay_linked_ids = replay_linked_flag_ids(self.project_id, [flag.id for flag in flags_list])+deleted = []errors = []@@ -3820,6 +3824,18 @@ class FeatureFlagViewSet()continue+ # Deleting a flag a team gates recording on stops that team recording, and the+ # tombstone rename below fires no signal to relink them.+ if flag_id in replay_linked_ids:+ errors.append(+ {+ "id": flag_id,+ "key": flag.key,+ "reason": REPLAY_LINKED_FLAG_DELETE_ERROR,+ }+ )+ continue+# Flag passes validation - capture rollout state before deletionchecker = FeatureFlagStatusChecker(feature_flag=flag)rollout_info = _get_flag_rollout_info(flag, checker)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 3f070f722c8e..5680d32f2d95 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -12685,6 +12685,83 @@ class TestFeatureFlagBulkDelete(APIBaseTest):# Key is freed up for reuseassert flag.key == f"stopped_experiment_flag:deleted:{flag.id}"+ def test_bulk_delete_blocks_a_flag_used_in_session_replay(self):+ # bulk_delete bypasses the serializer, so it needs its own replay guard; without one,+ # this delete would silently stop the linking team's recording.+ linked_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay_gate")+ unlinked_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated")+ self.team.session_recording_linked_flag = {"id": linked_flag.id, "key": "replay_gate"}+ self.team.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",+ {"ids": [linked_flag.id, unlinked_flag.id]},+ )++ assert response.status_code == 200+ data = response.json()+ # The rest of the batch still deletes, so one linked flag does not block the whole call.+ assert {d["id"] for d in data["deleted"]} == {unlinked_flag.id}+ assert len(data["errors"]) == 1+ assert data["errors"][0]["id"] == linked_flag.id+ assert "session replay settings" in data["errors"][0]["reason"]++ linked_flag.refresh_from_db()+ unlinked_flag.refresh_from_db()+ assert linked_flag.deleted is False+ assert unlinked_flag.deleted is True++ def test_bulk_delete_blocks_a_flag_a_sibling_team_links(self):+ # Replay links are project-scoped: a team can gate recording on a flag owned by a sibling+ # team, so a team-scoped lookup would let this delete through.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay_gate")+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project)+ sibling_team.session_recording_linked_flag = {"id": flag.id, "key": "replay_gate"}+ sibling_team.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",+ {"ids": [flag.id]},+ )++ assert response.status_code == 200+ data = response.json()+ assert len(data["deleted"]) == 0+ assert len(data["errors"]) == 1+ flag.refresh_from_db()+ assert flag.deleted is False++ @parameterized.expand(+ [+ ("bool_id", lambda flag_id: {"id": True, "key": "replay_gate"}),+ ("string_id", lambda flag_id: {"id": "abc", "key": "replay_gate"}),+ ("missing_id", lambda flag_id: {"key": "replay_gate"}),+ # A text id matching the flag's number is malformed, not linked: the team API+ # normalizes numeric-string ids to ints at write time (see+ # validate_session_recording_linked_flag), so jsonb's type-sensitive equality+ # can safely ignore it, same as the single-flag guard's containment check.+ ("numeric_string_id", lambda flag_id: {"id": str(flag_id), "key": "replay_gate"}),+ ]+ )+ def test_bulk_delete_ignores_a_malformed_replay_link(self, _case, stored_link_factory):+ # One team's malformed stored link must not block or 500 the project's bulk deletes:+ # the guard's jsonb filter matches no flag for these shapes, so it ignores them.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated")+ self.team.session_recording_linked_flag = stored_link_factory(flag.id)+ self.team.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",+ {"ids": [flag.id]},+ )++ assert response.status_code == 200+ data = response.json()+ assert {d["id"] for d in data["deleted"]} == {flag.id}+ assert data["errors"] == []+ flag.refresh_from_db()+ assert flag.deleted is True+def test_bulk_delete_requires_filters_or_ids(self):"""Test validation error when neither filters nor ids provided."""response = self.client.post(diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.pyindex 7a9a17262fe8..7d8d07a5e9dd 100644--- a/products/feature_flags/backend/session_recording_links.py+++ b/products/feature_flags/backend/session_recording_links.py@@ -6,6 +6,7 @@ browser and React Native SDKs treat a linked flag they can't resolve as "do notstale key silently turns replay off for the team rather than surfacing an error anywhere."""+from collections.abc import Collectionfrom typing import Anyfrom django.db import transaction@@ -21,6 +22,10 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)+REPLAY_LINKED_FLAG_DELETE_ERROR = (+ "This feature flag is used in session replay settings. Please remove it from replay settings before deleting."+)+def teams_linking_flag(feature_flag: FeatureFlag) -> QuerySet[Team]:"""Every team gating session recording on this flag."""@@ -32,6 +37,25 @@ def teams_linking_flag(feature_flag: FeatureFlag) -> QuerySet[Team]:)+def replay_linked_flag_ids(project_id: int, flag_ids: Collection[int]) -> set[int]:+ """Which of the given flags a team in this project gates session recording on.++ The batch equivalent of `teams_linking_flag`, in one query. Matching ids inside jsonb keeps+ that check's comparison semantics, so the single-flag and bulk delete guards agree on what+ counts as linked; a malformed value like `{"id": true}` matches no flag, because jsonb never+ equates booleans with numbers.+ """+ if not flag_ids:+ return set()+ stored_ids = Team.objects.filter(+ project_id=project_id,+ session_recording_linked_flag__id__in=flag_ids,+ ).values_list("session_recording_linked_flag__id", flat=True)+ # jsonb also equates numbers regardless of representation, so a stored float id can match an+ # int flag id; normalize for the int membership checks callers do.+ return {int(stored_id) for stored_id in stored_ids}++def update_linked_flag_key(team: Team, expected_flag_id: int, new_key: str) -> None:"""Rewrite the stored key on a team's replay link, leaving teams that no longer need it alone."""# Locks the row and re-reads inside the lock, rather than trusting `team`'s in-memory copy: