: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): bump the row version when bulk deleting config version 2 flags (#109422)
Andersf5f725cb8663
diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex eb7aafabce89..d258e54dda0d 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -167,6 +167,13 @@ def as_drf_validation_error(error: FieldedValidationError) -> ValidationError:return ValidationError(error.message)+def first_error_message(detail: Any) -> str:+ """The first message in a DRF error detail, which nests messages in dicts and lists."""+ while isinstance(detail, (dict, list)) and detail:+ detail = next(iter(detail.values())) if isinstance(detail, dict) else detail[0]+ return str(detail)++class ExceptionContext(TypedDict):request: HttpRequestdiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex fe052be24e92..2ab033ee1d40 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -67,7 +67,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.constants import FlagRequestTypefrom posthog.dataclasses import frozenfrom posthog.event_usage import report_user_action-from posthog.exceptions import Conflict+from posthog.exceptions import Conflict, first_error_messagefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.dashboard_templates import add_enriched_insights_to_feature_flag_dashboardfrom posthog.helpers.impersonation import is_impersonated@@ -1846,8 +1846,9 @@ class FeatureFlagSerializer(def _drop_echoed_v2_fields(self, attrs: dict) -> set[str]:"""Remove every submitted value equal to the stored one and return their names.- An echo is neither judged nor written: PUT must repeat `key`, and a bulk delete does not- bump `version`, so a written `deleted: false` could undo one.+ An echo is neither judged nor written: PUT must repeat `key`, and a soft delete from outside+ this serializer (the file-system trash) does not bump `version`, so a written+ `deleted: false` could undo one."""assert isinstance(self.instance, FeatureFlag)echoed = {@@ -2704,8 +2705,9 @@ class FeatureFlagSerializer(# Every read and the save below use the locked row, not the instance loaded# before the lock. `save()` writes every field, so applying this request to the# stale copy would restore whatever another writer changed in the meantime for- # a field this request never sent. A bulk delete leaves `version` untouched, so- # the version check above cannot catch it and the flag came back undeleted.+ # a field this request never sent. A soft delete from outside this serializer (the+ # file-system trash, or a bulk delete of a config version 1 flag) leaves `version`+ # untouched, so the version check above cannot catch it and the flag came back undeleted.old_key = locked_instance.key# Clear any soft-deleted tombstone on `new_key` so the (team, key)@@ -5072,8 +5074,9 @@ class FeatureFlagViewSet(Returns same format as bulk_delete for UI compatibility.- Uses bulk operations for efficiency: database updates are batched and cache- invalidation happens once at the end rather than per-flag.+ Config version 1 flags are deleted with batched updates, and cache invalidation+ runs once at the end. Config version 2 flags are deleted one at a time through+ ``update_flag``. Each one bumps its ``version`` and commits on its own."""from django.utils import timezone@@ -5190,6 +5193,7 @@ class FeatureFlagViewSet(# Also track which need key renames (have deleted experiments)flags_to_delete_normal: list[FeatureFlag] = []flags_to_delete_with_rename: list[FeatureFlag] = []+ v2_flags: list[tuple[FeatureFlag, dict]] = []activity_log_entries: list[LogActivityEntry] = []current_user = request.user if request.user.is_authenticated else None@@ -5255,6 +5259,11 @@ class FeatureFlagViewSet(checker = FeatureFlagStatusChecker(feature_flag=flag)rollout_info = _get_flag_rollout_info(flag, checker)old_key = flag.key+ entry = {"id": flag_id, "key": old_key, **rollout_info}++ if detect_config_format(flag.filters).kind == "v2":+ v2_flags.append((flag, entry))+ continue# Rename the key if the flag is linked to any experiment, to free it up.# Use the prefetched experiment_set cache (see queryset above) rather than@@ -5279,7 +5288,7 @@ class FeatureFlagViewSet())- deleted.append({"id": flag_id, "key": old_key, **rollout_info})+ deleted.append(entry)# Perform bulk database updates# Using queryset.update() instead of individual saves means Django signals don't fire.@@ -5325,6 +5334,26 @@ class FeatureFlagViewSet(transaction.on_commit(invalidate_caches)+ # Outside the transaction above: the facade requires gated writes like `update_flag` to run+ # outside any transaction, so each config version 2 flag commits on its own.+ if v2_flags:+ from products.feature_flags.backend.facade.api import update_flag++ for flag, entry in v2_flags:+ try:+ update_flag(+ flag,+ {"deleted": True, "version": flag.version or 0},+ team=flag.team,+ user=request.user,+ request=FlagLifecycleWriteRequest(request),+ serializer_context=self.get_serializer_context(),+ )+ except exceptions.APIException as exc:+ errors.append({"id": flag.id, "key": flag.key, "reason": first_error_message(exc.detail)})+ else:+ deleted.append(entry)+return Response({"deleted": deleted,diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.pyindex 01bbc68632fd..11449c0708e8 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py@@ -2,6 +2,8 @@work with both writer flags off; creating and enabling need the project's flags on."""+from unittest.mock import patch+from django.conf import settingsfrom django.test import override_settings@@ -10,11 +12,16 @@ from rest_framework import statusfrom rest_framework.exceptions import ValidationErrorfrom posthog.api.utils import ServiceRequest+from posthog.exceptions import Conflictfrom posthog.models import Teamfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.approvals.backend.serializers import ApprovalPolicySerializer-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.api.feature_flag import (+ FeatureFlagSerializer,+ _get_flag_rollout_info,+ flag_version_conflict_message,+)from products.feature_flags.backend.api.test.test_feature_flag_config_v2_updates import (AdmittedV2TestCase,JsonValue,@@ -51,15 +58,116 @@ class TestV2SafetyWritesNeedNoAdmission(V2UpdateTestCase):assert entry.activity == "updated"assert self.changed_fields(entry) == {"active", "version"}- def test_an_echoed_deleted_false_does_not_undo_a_concurrent_bulk_delete(self) -> None:+ def test_an_echoed_deleted_false_does_not_undo_a_soft_delete_that_kept_the_version(self) -> None:flag = self.flag(active=True)stale = FeatureFlag.objects.get(pk=flag.pk)- FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True) # a bulk delete does not bump version+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True) # as the file-system trash doesupdated = flag_facade.update_flag(stale, {"version": 3, "deleted": False, "active": False}, team=self.team, user=self.user)assert (updated.deleted, updated.active, updated.version) == (True, False, 4)+ def test_bulk_delete_disables_and_bumps_the_version_like_a_single_delete(self) -> None:+ flag = self.flag(active=True)+ v1_flag = FeatureFlag.objects.create(+ team=self.team,+ key="v1-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ version=5,+ )+ self._activity_qs(v1_flag).delete()+ stale = FeatureFlag.objects.get(pk=flag.pk)++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/", {"ids": [flag.id, v1_flag.id]}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert {item["id"] for item in response.json()["deleted"]} == {flag.id, v1_flag.id}+ flag.refresh_from_db()+ assert (flag.deleted, flag.active, flag.version) == (True, False, 4)+ (entry,) = self.activity(flag)+ assert entry.activity == "deleted"+ assert {c["field"]: (c["before"], c["after"]) for c in (entry.detail or {})["changes"]} == {+ "deleted": (False, True),+ "active": (True, False),+ "version": (3, 4),+ }+ v1_flag.refresh_from_db()+ assert (v1_flag.deleted, v1_flag.active, v1_flag.version) == (True, True, 5)+ (v1_entry,) = self.activity(v1_flag)+ assert (v1_entry.activity, (v1_entry.detail or {})["changes"]) == ("deleted", [])+ with self.assertRaises(Conflict):+ flag_facade.update_flag(stale, {"version": 3, "active": False}, team=self.team, user=self.user)++ def test_bulk_delete_reports_a_row_the_single_delete_refuses(self) -> None:+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.disable",+ approver_config={},+ enabled=True,+ )+ flag = self.flag(active=True)++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/", {"ids": [flag.id]}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["deleted"] == []+ assert response.json()["errors"] == [+ {+ "id": flag.id,+ "key": flag.key,+ "reason": "This flag cannot be written while an approval policy is enabled.",+ }+ ]+ flag.refresh_from_db()+ assert (flag.deleted, flag.active, flag.version) == (False, True, 3)+ assert self.activity(flag) == []+ assert not ChangeRequest.objects.filter(organization=self.organization).exists()++ def test_bulk_delete_reports_a_row_that_changed_after_the_read_and_deletes_the_rest(self) -> None:+ moved = self.flag(active=True, key="moved")+ other = self.flag(active=True, key="other")++ def read_then_move(flag, checker):+ if flag.pk == moved.pk:+ FeatureFlag.objects.filter(pk=moved.pk).update(version=4)+ return _get_flag_rollout_info(flag, checker)++ with patch(+ "products.feature_flags.backend.api.feature_flag._get_flag_rollout_info", side_effect=read_then_move+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",+ {"ids": [moved.id, other.id]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["errors"] == [+ {"id": moved.id, "key": moved.key, "reason": flag_version_conflict_message(3, 4)}+ ]+ assert [item["id"] for item in response.json()["deleted"]] == [other.id]+ moved.refresh_from_db()+ assert (moved.deleted, moved.active, moved.version) == (False, True, 4)+ other.refresh_from_db()+ assert (other.deleted, other.active, other.version) == (True, False, 4)++ def test_bulk_delete_still_soft_deletes_a_row_in_an_unsupported_format(self) -> None:+ flag = self.flag({"version": 99}, active=True)++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/", {"ids": [flag.id]}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [item["id"] for item in response.json()["deleted"]] == [flag.id]+ flag.refresh_from_db()+ assert (flag.deleted, flag.active, flag.version) == (True, True, 3)+def test_soft_deleting_disables_an_enabled_row_in_the_same_write(self) -> None:flag = self.flag(active=True)response = self.patch_flag(flag, {"version": 3, "deleted": True})diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex 3991e41a058d..866cf668ded6 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -6,7 +6,7 @@ call these functions instead of driving the serializer and its DRF context by ha``deactivate_trashed_flag`` and ``reactivate_restored_flag`` bypass the serializer, becausefile-system trash and restore flip ``active`` without the gate or validation.``clear_feature_enrollment`` falls back to a raw model write when the serializer rejects-a flag's stored filters, because enrollment cleanup must never fail.+a flag's stored config version 1 filters, because enrollment cleanup must never fail.The read helpers (``user_can_edit_flag``, ``user_can_create_flags``, ``flag_disable_requires_approval``,``serialize_flags``, ``get_feature_flag_request_usage``) expose the flag API'saccess-control, approval-policy, representation, and request-usage logic behind@@ -260,6 +260,9 @@ def clear_feature_enrollment(flag_id: int, *, team: Team) -> None:model write when it raises. This is a system write (user=None): an enabled approvalpolicy must never block cleanup with a 409, and activity is logged as system.+ Another config format raises ``ConfigFormatError`` from ``set_feature_enrollment`` before+ either write. No caller reaches it: an early access feature only links config version 1 flags.+The early return covers a hard-deleted id or another team's flag, so nothing is left toclear. A soft-deleted flag still gets cleared, through ``objects_including_soft_deleted``:the default manager hides it, and skipping it would leave the marker to come back with thediff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 3e3ff6949a94..b0157670373d 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -20,6 +20,7 @@ from products.feature_flags.backend.facade.api import (_redact_unchanged_encrypted_payloads,_roll_out_variant,archive_flag,+ clear_feature_enrollment,create_flag,flag_disable_requires_approval,set_flag_active,@@ -1158,3 +1159,13 @@ class TestFilterTransformsRequireV1:with pytest.raises(ConfigFormatError):transform(filters)assert filters == pristine+++class TestClearFeatureEnrollmentRequiresV1(APIBaseTest):+ @parameterized.expand(UNSUPPORTED_DOCUMENTS)+ def test_refuses_before_either_write(self, _name, filters):+ flag = FeatureFlag.objects.create(team=self.team, key="other-format", filters=filters, version=2)+ with pytest.raises(ConfigFormatError):+ clear_feature_enrollment(flag.id, team=self.team)+ flag.refresh_from_db()+ assert (flag.filters, flag.version) == (filters, 2)diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex 33715c64febd..24088a5e9cc4 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -1090,8 +1090,9 @@ export const getFeatureFlagsBulkDeleteCreateUrl = (projectId: string) => {** Returns same format as bulk_delete for UI compatibility.*- * Uses bulk operations for efficiency: database updates are batched and cache- * invalidation happens once at the end rather than per-flag.+ * Config version 1 flags are deleted with batched updates, and cache invalidation+ * runs once at the end. Config version 2 flags are deleted one at a time through+ * ``update_flag``. Each one bumps its ``version`` and commits on its own.*/export const featureFlagsBulkDeleteCreate = async (projectId: string,diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 627a5c35e551..bee3f415311b 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -1212,8 +1212,9 @@ export const FeatureFlagsTestEvaluationCreateBody = /* @__PURE__ */ zod.object({** Returns same format as bulk_delete for UI compatibility.*- * Uses bulk operations for efficiency: database updates are batched and cache- * invalidation happens once at the end rather than per-flag.+ * Config version 1 flags are deleted with batched updates, and cache invalidation+ * runs once at the end. Config version 2 flags are deleted one at a time through+ * ``update_flag``. Each one bumps its ``version`` and commits on its own.*/export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex 14543617152a..9bcb98a83d79 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -1159,8 +1159,9 @@ export const FeatureFlagsUnarchiveCreateParams = () => zod.object({** Returns same format as bulk_delete for UI compatibility.*- * Uses bulk operations for efficiency: database updates are batched and cache- * invalidation happens once at the end rather than per-flag.+ * Config version 1 flags are deleted with batched updates, and cache invalidation+ * runs once at the end. Config version 2 flags are deleted one at a time through+ * ``update_flag``. Each one bumps its ``version`` and commits on its own.*/export const FeatureFlagsBulkDeleteCreateParams = () => zod.object({project_id: zod