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(file-system): stop flipping active when a flag is trashed (#108143)

Yasen6bffeb965aa8
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index 736d59d7ef85..57216ac080b2 100644
--- a/posthog/api/file_system/registrations.py
+++ b/posthog/api/file_system/registrations.py
@@ -320,27 +320,9 @@ def _feature_flag_post_restore(context: RestoreContext, feature_flag: Any) -> No
name=_first_non_blank(getattr(feature_flag, "name", None), getattr(feature_flag, "key", None))
or "Untitled feature flag",
object_type="feature flag",
- extra_changes=[Change(type="FeatureFlag", action="changed", field="active", before=False, after=True)],
)
-def _feature_flag_pre_delete(context: DeletionContext, feature_flag: Any) -> None:
- # Deferred: the flag facade pulls FeatureFlagSerializer, which drags posthog.schema and the
- # LLM SDKs in. This module is imported from AppConfig.ready(), so a module-level import would
- # put all of that on every process's startup path.
- from products.feature_flags.backend.facade.api import deactivate_trashed_flag # noqa: PLC0415
-
- deactivate_trashed_flag(feature_flag.id, team_id=feature_flag.team_id)
- feature_flag.refresh_from_db(fields=["active"])
-
-
-def _feature_flag_pre_restore(context: RestoreContext, feature_flag: Any) -> None:
- from products.feature_flags.backend.facade.api import reactivate_restored_flag # noqa: PLC0415
-
- reactivate_restored_flag(feature_flag.id, team_id=feature_flag.team_id)
- feature_flag.refresh_from_db(fields=["active"])
-
-
def register_core_file_system_types() -> None:
register_file_system_type(
"action",
@@ -366,8 +348,6 @@ def register_core_file_system_types() -> None:
"FeatureFlag",
undo_message="Send PATCH /api/projects/@current/feature_flags/{id} with deleted=false.",
)
- register_pre_delete_hook("feature_flag", _feature_flag_pre_delete)
- register_pre_restore_hook("feature_flag", _feature_flag_pre_restore)
register_post_delete_hook("feature_flag", _feature_flag_post_delete)
register_post_restore_hook("feature_flag", _feature_flag_post_restore)
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index 32c095fd7b29..8564d4715224 100644
--- a/posthog/api/test/test_file_system.py
+++ b/posthog/api/test/test_file_system.py
@@ -24,7 +24,7 @@ from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.actions.backend.models.action import Action
-from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
+from products.approvals.backend.models import ChangeRequest
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
@@ -704,9 +704,7 @@ class TestFileSystemDeletion(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert FileSystem.objects.filter(team=self.team, path="Unfiled/Unknown/Item").exists()
- @parameterized.expand(
- [("plain",), ("active_dependent_flag",), ("depends_on_inactive_flag",), ("disable_and_enable_policies",)]
- )
+ @parameterized.expand([("plain",), ("active_dependent_flag",), ("depends_on_inactive_flag",)])
@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
def test_undo_delete_restores_feature_flag(self, setup: str, _mock_approvals_enabled) -> None:
flag = FeatureFlag.objects.create(team=self.team, key="undo-flag", created_by=self.user)
@@ -748,16 +746,6 @@ class TestFileSystemDeletion(APIBaseTest):
]
}
flag.save()
- elif setup == "disable_and_enable_policies":
- for action_key in ("feature_flag.disable", "feature_flag.enable"):
- ApprovalPolicy.objects.create(
- organization=self.organization,
- team=self.team,
- action_key=action_key,
- conditions={},
- approver_config={"quorum": 1, "users": [self.user.id]},
- created_by=self.user,
- )
file_entry = FileSystem.objects.get(team=self.team, type="feature_flag", ref=str(flag.id))
delete_response = self.client.delete(
@@ -767,7 +755,8 @@ class TestFileSystemDeletion(APIBaseTest):
assert delete_response.status_code == status.HTTP_200_OK
flag.refresh_from_db()
assert flag.deleted is True
- assert flag.active is False
+ # Trash leaves active alone: deleted already stops the flag serving.
+ assert flag.active is True
undo_response = self.client.post(
f"/api/environments/{self.team.id}/file_system/undo_delete/",
@@ -775,10 +764,12 @@ class TestFileSystemDeletion(APIBaseTest):
)
assert undo_response.status_code == status.HTTP_200_OK
- flag.refresh_from_db()
assert FileSystem.objects.filter(team=self.team, type="feature_flag", ref=str(flag.id)).exists()
- assert flag.active is True
- assert flag.deleted is False # type: ignore
+ # Re-fetch instead of refresh_from_db: mypy narrows the earlier truthy assert on deleted,
+ # which makes asserting False on the same instance unreachable.
+ restored = FeatureFlag.objects.get(pk=flag.pk)
+ assert restored.active is True
+ assert restored.deleted is False
assert not ChangeRequest.objects.filter(team=self.team).exists()
def test_undo_delete_restores_original_path(self) -> None:
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
index c79438c27306..ef29f896ed27 100644
--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
@@ -1,6 +1,4 @@
# Generated by write_baseline() in test_feature_flag_gated_writes.py. Shrink it, never grow it.
-posthog/api/file_system/registrations.py::_feature_flag_pre_delete::deactivate_trashed_flag()
-posthog/api/file_system/registrations.py::_feature_flag_pre_restore::reactivate_restored_flag()
posthog/management/commands/generate_random_product_tours.py::Command.create_internal_targeting_flag::FeatureFlag.objects.create()
posthog/management/commands/reencrypt_flag_payloads.py::Command._reencrypt::FeatureFlag.objects.filter(pk=flag_pk).update()
posthog/management/commands/sync_feature_flags.py::Command.create_feature_flag::FeatureFlag.objects.create()
@@ -11,7 +9,6 @@ posthog/management/commands/sync_feature_flags_from_api.py::sync_feature_flags_f
products/demo/backend/logic/matrix/matrix.py::Matrix.set_project_up::FeatureFlag.objects.create()
products/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up.create_experiment_flag::FeatureFlag.objects.create()
products/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up::FeatureFlag.objects.create()
-products/feature_flags/backend/facade/api.py::_set_trashed_flag_active::FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team_id=team_id).update()
products/feature_flags/backend/facade/api.py::clear_feature_enrollment::flag.filters =
products/feature_flags/evals/seeders.py::_create_flag::FeatureFlag.objects.create()
products/feature_flags/evals/seeders.py::seed_stale_full_rollout_flag::FeatureFlag.objects.create()
diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
index 7cb5cc41294f..99c8a3edf001 100644
--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
@@ -24,8 +24,7 @@ GATED_PATH = {
# Shrink-only. Move a write to the facade, then regenerate the baseline and drop its entry here.
ALLOWED_REASONS: dict[str, str] = {
"products/surveys/backend/api/survey.py": "start/stop mirror of active, which the serializer would gate and guard",
- "products/feature_flags/backend/facade/api.py": "file-system trash and restore flip active, and never-fail early access enrollment cleanup",
- "posthog/api/file_system/registrations.py": "calls the ungated trash and restore helpers",
+ "products/feature_flags/backend/facade/api.py": "never-fail early access enrollment cleanup",
"posthog/management/commands/generate_random_product_tours.py": "local data generator",
"posthog/management/commands/reencrypt_flag_payloads.py": "payload re-encryption command",
"posthog/management/commands/sync_feature_flags.py": "local dev flag sync",
@@ -151,9 +150,6 @@ def _names_gated_field(values: list[ast.expr]) -> bool:
return any(not isinstance(v, ast.Constant) or v.value in GATED_FIELDS for v in values)
-UNGATED_FACADE_WRITES = {"deactivate_trashed_flag", "reactivate_restored_flag"}
-
-
def _write_target(
node: ast.AST, flag_names: set[str], models: set[str], serializers: set[str], *, serializer_exempt: bool
) -> str | None:
@@ -167,12 +163,6 @@ def _write_target(
if not isinstance(node, ast.Call):
return None
- # These facade helpers write `active` without the gate, so a call to one is itself an
- # ungated write. Without this the write would be recorded only where it is defined, and a
- # new caller anywhere in the tree would add no baseline entry.
- if _terminal_name(node.func) in UNGATED_FACADE_WRITES:
- return f"{_terminal_name(node.func)}()"
-
if _terminal_name(node.func) in serializers:
# Positional data or **kwargs cannot be resolved, so they count as a write.
is_write = len(node.args) > 1 or any(kw.arg in (None, "data") for kw in node.keywords)
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
index 866cf668ded6..fd990a7cd8ec 100644
--- a/products/feature_flags/backend/facade/api.py
+++ b/products/feature_flags/backend/facade/api.py
@@ -3,8 +3,6 @@
Every write routes through ``FeatureFlagSerializer`` — the only path that honors
``@approval_gate``, validation, and activity logging. Consumers (currently experiments)
call these functions instead of driving the serializer and its DRF context by hand.
-``deactivate_trashed_flag`` and ``reactivate_restored_flag`` bypass the serializer, because
-file-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 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``,
@@ -186,38 +184,6 @@ def set_flag_active(
return update_flag(flag, {"active": active}, team=team, user=user, request=request)
-def _set_trashed_flag_active(flag_id: int, *, team_id: int, active: bool) -> None:
- """Flip ``active`` on a flag the file system trashes or restores. UNGATED on purpose.
-
- A queryset update fires no signals. The file system then saves the flag inside
- ``mute_selected_signals()``. That silences only the activity-log receiver, because the file
- system writes its own trash and restore entries. The post_save receivers, such as flags cache
- invalidation, still fire on that save. A serializer write here would log a second activity
- entry and add the dependents check, filter validation and the approval gate. Trash never had
- any of those.
-
- The caller reads the row back, because the file system saves the whole instance after
- this and would otherwise write the stale value over it.
-
- Restore runs while the row still carries ``deleted``, which the default manager excludes,
- so this reaches the row through ``objects_including_soft_deleted``.
- """
- FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team_id=team_id).update(active=active)
-
-
-def deactivate_trashed_flag(flag_id: int, *, team_id: int) -> None:
- """Disable a flag that the file system moves to trash. See ``_set_trashed_flag_active``."""
- # TODO: trash disables a flag without passing a feature_flag.disable policy.
- _set_trashed_flag_active(flag_id, team_id=team_id, active=False)
-
-
-def reactivate_restored_flag(flag_id: int, *, team_id: int) -> None:
- """Enable a flag that the file system restores from trash. See ``_set_trashed_flag_active``."""
- # TODO: restore enables a flag without passing a feature_flag.enable policy. It does so even
- # when the flag was off before trash, because trash does not record the prior state.
- _set_trashed_flag_active(flag_id, team_id=team_id, active=True)
-
-
def archive_flag(
flag: FeatureFlag,
*,