: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
chore(file-system): flip trashed flags through the flag facade (#107819)
Yasenbf9b9f260e9a
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex d43e17c29056..7352cdd1fe4d 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -336,11 +336,20 @@ def _feature_flag_post_restore(context: RestoreContext, feature_flag: Any) -> Nodef _feature_flag_pre_delete(context: DeletionContext, feature_flag: Any) -> None:- feature_flag.active = False+ # 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:- feature_flag.active = True+ 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:diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.pyindex 13b797c46741..4f203dcd777f 100644--- a/posthog/api/test/test_file_system.py+++ b/posthog/api/test/test_file_system.py@@ -24,6 +24,7 @@ from posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom products.actions.backend.models.action import Action+from products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboard@@ -722,8 +723,60 @@ class TestFileSystemDeletion(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert FileSystem.objects.filter(team=self.team, path="Unfiled/Unknown/Item").exists()- def test_undo_delete_restores_feature_flag(self) -> None:+ @parameterized.expand(+ [("plain",), ("active_dependent_flag",), ("depends_on_inactive_flag",), ("disable_and_enable_policies",)]+ )+ @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)+ if setup == "active_dependent_flag":+ FeatureFlag.objects.create(+ team=self.team,+ key="dependent-flag",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(flag.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ elif setup == "depends_on_inactive_flag":+ # Restore skips the serializer's enable-side check, which refuses to turn on a flag+ # whose conditions depend on a disabled flag.+ dependency = FeatureFlag.objects.create(+ team=self.team, key="dependency-flag", created_by=self.user, active=False+ )+ flag.filters = {+ "groups": [+ {+ "properties": [+ {+ "key": str(dependency.id),+ "type": "flag",+ "value": True,+ "operator": "flag_evaluates_to",+ }+ ],+ "rollout_percentage": 100,+ }+ ]+ }+ 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(@@ -745,6 +798,7 @@ class TestFileSystemDeletion(APIBaseTest):assert FileSystem.objects.filter(team=self.team, type="feature_flag", ref=str(flag.id)).exists()assert flag.active is Trueassert flag.deleted is False # type: ignore+ assert not ChangeRequest.objects.filter(team=self.team).exists()def test_undo_delete_restores_original_path(self) -> None:flag = FeatureFlag(team=self.team, key="undo-path-flag", created_by=self.user)diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txtindex 2e58121e2b0b..635537b2e145 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,6 @@# 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::feature_flag.active =-posthog/api/file_system/registrations.py::_feature_flag_pre_restore::feature_flag.active =+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()@@ -12,6 +12,7 @@ products/demo/backend/logic/matrix/matrix.py::Matrix.set_project_up::FeatureFlagproducts/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/early_access_features/backend/api.py::clear_feature_enrollment::feature_flag.filters =+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/evals/seeders.py::_create_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_full_rollout_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_partial_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.pyindex 4bfde85c454d..4d7d8d9edcad 100644--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py@@ -24,7 +24,8 @@ 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": "targeting flag writes and the start/stop mirror of active",- "posthog/api/file_system/registrations.py": "file-system trash and restore flip active",+ "products/feature_flags/backend/facade/api.py": "file-system trash and restore flip active",+ "posthog/api/file_system/registrations.py": "calls the ungated trash and restore helpers","products/early_access_features/backend/api.py": "never-fail cleanup when stored filters fail validation","posthog/management/commands/generate_random_product_tours.py": "local data generator","posthog/management/commands/reencrypt_flag_payloads.py": "payload re-encryption command",@@ -151,6 +152,9 @@ 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:@@ -164,6 +168,12 @@ 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.pyindex 0c1f67b2b746..c387d518ec67 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -3,6 +3,8 @@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.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@@ -178,6 +180,38 @@ 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,*,