: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): remap flag dependencies when copying across projects (#64472)
Ben Leacca066a3f9ab
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9981506de036..0a241562e8e0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2609,7 +2609,10 @@ const api = {async copy(orgId: OrganizationType['id'] = ApiConfig.getCurrentOrganizationId(),data: OrganizationFeatureFlagsCopyBody- ): Promise<{ success: FeatureFlagType[]; failed: any }> {+ ): Promise<{+ success: (FeatureFlagType & { flag_dependency_warnings?: string[]; schedule_copy_warning?: string })[]+ failed: any+ }> {return await new ApiRequest().copyOrganizationFeatureFlags(orgId).create({ data })},async keys(diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 37585da30344..b0b9d58f68ae 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -2081,6 +2081,14 @@ export const featureFlagLogic = kea<featureFlagLogicType>([: 'copied'lemonToast.success(`Feature flag ${operation} successfully!`)eventUsageLogic.actions.reportFeatureFlagCopySuccess()++ // Surface any warnings the copy returned (e.g. a flag dependency dropped because it+ // doesn't exist in the target, or scheduled changes that failed to copy).+ const warnings = featureFlagCopy.success.flatMap((flag) => [+ ...(flag.flag_dependency_warnings ?? []),+ ...(flag.schedule_copy_warning ? [flag.schedule_copy_warning] : []),+ ])+ warnings.forEach((warning) => lemonToast.warning(warning))} else {const errorMessage = JSON.stringify(featureFlagCopy?.failed) || featureFlagCopylemonToast.error(`Error while saving feature flag: ${errorMessage}`)diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 548e84bbaa74..ff527e2c5528 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -19,6 +19,7 @@ from posthog.models import Team, Userfrom posthog.models.filters.filter import Filterfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.user_permissions import UserPermissions+from posthog.utils import safe_intfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer@@ -63,6 +64,15 @@ class CopyFlagsSuccessItemSerializer(serializers.Serializer):name = serializers.CharField(help_text="Name of the feature flag")active = serializers.BooleanField(help_text="Whether the flag is active")team_id = serializers.IntegerField(help_text="Team ID the flag was copied to")+ flag_dependency_warnings = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Warnings for flag dependencies that were dropped because no matching active flag exists in the target project",+ )+ schedule_copy_warning = serializers.CharField(+ required=False,+ help_text="Warning emitted when the flag was copied but its scheduled changes failed to copy",+ )class CopyFlagsResponseSerializer(serializers.Serializer):@@ -288,6 +298,22 @@ class OrganizationFeatureFlagView(successful_projects = []failed_projects = []+ # Flag dependencies reference other flags by ID, which differs across projects. Like cohorts,+ # we remap them by the dependency flag's key, so resolve each source dependency ID to its key once.+ source_dependency_keys: dict[int, str] = {}+ for group in flag_to_copy.get_filters().get("groups", []) or []:+ for prop in group.get("properties", []) or []:+ if isinstance(prop, dict) and prop.get("type") == "flag":+ dependency_id = safe_int(prop.get("key"))+ if dependency_id is not None and dependency_id not in source_dependency_keys:+ dependency_flag = (+ FeatureFlag.objects.filter(id=dependency_id, team__project_id=from_project, deleted=False)+ .only("key")+ .first()+ )+ if dependency_flag:+ source_dependency_keys[dependency_id] = dependency_flag.key+# Get accessible teams for the useruser_permissions = UserPermissions(user=request.user)accessible_team_ids = set(user_permissions.team_ids_visible_for_user)@@ -385,8 +411,13 @@ class OrganizationFeatureFlagView(if destination_cohort is not None and original_cohort.name is not None:name_to_dest_cohort_id[original_cohort.name] = destination_cohort.id+ # Deep-copy the filters per iteration before remapping the cohort and flag-dependency+ # references, whose target IDs are project-specific. Both remaps mutate this dict, so+ # working on a per-target copy keeps one target's IDs from leaking into the next.+ filters = copy.deepcopy(flag_to_copy.get_filters())+# reference correct destination cohort ids in the flag- for group in flag_to_copy.conditions:+ for group in filters.get("groups", []) or []:props = group.get("properties", [])for prop in props:if isinstance(prop, dict) and prop.get("type") == "cohort":@@ -400,8 +431,7 @@ class OrganizationFeatureFlagView(except (ValueError, TypeError):continue- # Retrieve filters per iteration since cohort replacement logic mutates the dict- filters = flag_to_copy.get_filters()+ flag_dependency_warnings = self._remap_flag_dependencies(filters, source_dependency_keys, target_project_id)if flag_to_copy.has_encrypted_payloads:# Decrypt payloads before copying to ensure the new flag has unencrypted payloads# that will be re-encrypted by the serializer if needed@@ -412,7 +442,10 @@ class OrganizationFeatureFlagView("key": flag_to_copy.key,"name": flag_to_copy.name,"filters": filters,- "active": False if disable_copied_flag else flag_to_copy.active,+ # Dropping a flag dependency leaves its condition group ungated (an empty-property+ # group matches everyone), so a copy with dropped dependencies must never land+ # enabled — force it inactive for review.+ "active": False if (disable_copied_flag or flag_dependency_warnings) else flag_to_copy.active,"ensure_experience_continuity": flag_to_copy.ensure_experience_continuity,"deleted": False,"evaluation_runtime": flag_to_copy.evaluation_runtime,@@ -466,6 +499,8 @@ class OrganizationFeatureFlagView(result = feature_flag_serializer.dataif schedule_copy_error:result["schedule_copy_warning"] = f"Flag copied but schedules failed: {schedule_copy_error}"+ if flag_dependency_warnings:+ result["flag_dependency_warnings"] = flag_dependency_warningssuccessful_projects.append(result)except Exception as e:failed_projects.append(@@ -482,6 +517,75 @@ class OrganizationFeatureFlagView(status=status.HTTP_200_OK,)+ def _remap_flag_dependencies(+ self, filters: dict, source_dependency_keys: dict[int, str], target_project_id: int+ ) -> list[str]:+ """Remap flag-dependency references to the matching flag in the target project.++ Flag dependencies store the parent flag's ID, which differs across projects, so we match by+ key — the same approach used for cohorts. When no active flag with that key exists in the+ target project, the dependency is dropped and a warning is returned rather than failing the+ whole copy (the validator would otherwise reject a dangling or disabled dependency).+ """+ warnings: list[str] = []+ # Resolve every source dependency key to its target flag in one query per target, rather than+ # querying once per flag-type property (mirrors the batched source-dependency scan upstream).+ target_flags_by_key = {+ flag.key: flag+ for flag in FeatureFlag.objects.filter(+ key__in=source_dependency_keys.values(), team__project_id=target_project_id, deleted=False+ ).only("id", "key", "active")+ }+ for group in filters.get("groups", []) or []:+ # Leave groups without a properties key untouched so we don't change the filter shape+ # (an injected empty list would otherwise alter every copied flag's serialized filters).+ if not group.get("properties"):+ continue+ kept_properties = []+ dropped_dependency = False+ for prop in group.get("properties", []) or []:+ if not (isinstance(prop, dict) and prop.get("type") == "flag"):+ kept_properties.append(prop)+ continue++ source_dependency_id = safe_int(prop.get("key"))+ source_key = (+ source_dependency_keys.get(source_dependency_id) if source_dependency_id is not None else None+ )++ if source_key is None:+ # The source dependency itself couldn't be resolved (e.g. it was soft-deleted), so+ # there's no key to match in the target — drop it and name the unresolved source id.+ dropped_dependency = True+ warnings.append(+ f"Removed a flag dependency (source flag id {prop.get('key')}) because the dependency flag could not be resolved in the source project."+ )+ continue++ target_flag = target_flags_by_key.get(source_key)+ if target_flag and target_flag.active:+ # Preserve the original key type (dependencies are typically stored as strings)+ prop["key"] = str(target_flag.id) if isinstance(prop.get("key"), str) else target_flag.id+ kept_properties.append(prop)+ elif target_flag and not target_flag.active:+ dropped_dependency = True+ warnings.append(+ f"Removed dependency on flag '{source_key}' because that flag is disabled in the target project."+ )+ else:+ dropped_dependency = True+ warnings.append(+ f"Removed dependency on flag '{source_key}' because no flag with that key exists in the target project."+ )+ # Dropping a dependency that leaves a group with no other constraints turns it into a+ # 100%-rollout group that matches everyone, so flag it for review before re-enabling.+ if dropped_dependency and not kept_properties:+ warnings.append(+ "A condition group now has no remaining constraints and will match all users at its rollout percentage — review and re-gate it before re-enabling this flag."+ )+ group["properties"] = kept_properties+ return warnings+def _copy_feature_flag_schedules(self, source_schedules, target_flag, user, cohort_mapping, cohort_cache):"""Copy all scheduled changes from source flag to target flag.diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 0c7f49a16053..dd78fc29f02f 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -1102,6 +1102,222 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):if destination_cohort is not None:self.assertTrue(destination_cohort.groups[0]["properties"][0]["value"] == destination_cohort_prop_value)+ def _flag_dependency_property(self, dependency_flag, as_int=False):+ return {+ "key": dependency_flag.id if as_int else str(dependency_flag.id),+ "type": "flag",+ "value": "true",+ "operator": "flag_evaluates_to",+ }++ @parameterized.expand(+ [+ # name, target_parent_active (None = no same-key flag in target), include_sibling_prop,+ # expected_warning_substring (None = remapped, no warning), expected_active, expected_remaining_types+ ("present_and_active", True, False, None, True, ["flag"]),+ ("missing_with_sibling", None, True, "no flag with that key", False, ["person"]),+ ("missing_only_property", None, False, "no flag with that key", False, []),+ ("disabled_in_target", False, False, "disabled", False, []),+ ]+ )+ def test_copy_feature_flag_remaps_or_drops_dependency(+ self,+ _name,+ target_parent_active,+ include_sibling_prop,+ expected_warning_substring,+ expected_active,+ expected_remaining_types,+ ):+ target_project = self.team_2++ source_parent = FeatureFlag.objects.create(+ team=self.team_1, created_by=self.user, key="parent-flag", active=True+ )+ target_parent = None+ if target_parent_active is not None:+ # Same-key parent in the target project, created with a different ID than the source+ target_parent = FeatureFlag.objects.create(+ team=target_project, created_by=self.user, key="parent-flag", active=target_parent_active+ )++ properties = [self._flag_dependency_property(source_parent)]+ if include_sibling_prop:+ properties.append({"key": "$some_prop", "value": "x", "type": "person", "operator": "exact"})++ dependent_flag = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="dependent-flag",+ active=True,+ filters={"groups": [{"rollout_percentage": 100, "properties": properties}]},+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": dependent_flag.key,+ "from_project": dependent_flag.team_id,+ "target_project_ids": [target_project.id],+ }+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["failed"]), 0)+ success = response.json()["success"][0]++ copied_flag = FeatureFlag.objects.get(key="dependent-flag", team_id=target_project.id)+ remaining = copied_flag.filters["groups"][0].get("properties", [])+ self.assertEqual([prop["type"] for prop in remaining], expected_remaining_types)+ self.assertEqual(copied_flag.active, expected_active)++ if expected_warning_substring is None:+ # Dependency remapped to the target project's parent flag; nothing dropped, copy stays active+ assert target_parent is not None+ self.assertNotIn("flag_dependency_warnings", success)+ self.assertEqual(remaining[0]["key"], str(target_parent.id))+ else:+ # Dependency dropped: a warning is surfaced and the copy is forced inactive for review+ self.assertIn("flag_dependency_warnings", success)+ self.assertIn(expected_warning_substring, success["flag_dependency_warnings"][0])++ def test_copy_feature_flag_remaps_int_keyed_dependency(self):+ # Dependencies are usually stored as string keys, so the int-key branch of the remap is+ # otherwise untested — assert it remaps and preserves the int key type in the target.+ target_project = self.team_2+ source_parent = FeatureFlag.objects.create(+ team=self.team_1, created_by=self.user, key="parent-flag", active=True+ )+ target_parent = FeatureFlag.objects.create(+ team=target_project, created_by=self.user, key="parent-flag", active=True+ )+ dependent_flag = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="dependent-flag",+ active=True,+ filters={+ "groups": [+ {+ "rollout_percentage": 100,+ "properties": [self._flag_dependency_property(source_parent, as_int=True)],+ }+ ]+ },+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": dependent_flag.key,+ "from_project": dependent_flag.team_id,+ "target_project_ids": [target_project.id],+ }+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["failed"]), 0)+ copied_flag = FeatureFlag.objects.get(key="dependent-flag", team_id=target_project.id)+ remapped_key = copied_flag.filters["groups"][0]["properties"][0]["key"]+ self.assertEqual(remapped_key, target_parent.id)+ self.assertIsInstance(remapped_key, int)+ self.assertTrue(copied_flag.active)++ def test_copy_feature_flag_with_multiple_dependencies_in_one_group(self):+ # A group with two flag dependencies: one present-and-active in the target (remapped), one+ # missing (dropped). Exactly one warning should be surfaced and only the active one kept.+ target_project = self.team_2+ present_parent = FeatureFlag.objects.create(+ team=self.team_1, created_by=self.user, key="present-parent", active=True+ )+ target_present_parent = FeatureFlag.objects.create(+ team=target_project, created_by=self.user, key="present-parent", active=True+ )+ missing_parent = FeatureFlag.objects.create(+ team=self.team_1, created_by=self.user, key="missing-parent", active=True+ )++ dependent_flag = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="dependent-flag",+ active=True,+ filters={+ "groups": [+ {+ "rollout_percentage": 100,+ "properties": [+ self._flag_dependency_property(present_parent),+ self._flag_dependency_property(missing_parent),+ ],+ }+ ]+ },+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": dependent_flag.key,+ "from_project": dependent_flag.team_id,+ "target_project_ids": [target_project.id],+ }+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["failed"]), 0)+ success = response.json()["success"][0]++ copied_flag = FeatureFlag.objects.get(key="dependent-flag", team_id=target_project.id)+ remaining = copied_flag.filters["groups"][0]["properties"]+ # Only the present dependency survives, remapped to the target's parent ID+ self.assertEqual(len(remaining), 1)+ self.assertEqual(remaining[0]["key"], str(target_present_parent.id))+ # The dropped dependency yields exactly one warning (the group still has the kept dependency,+ # so no "group now matches everyone" warning is added)+ self.assertEqual(len(success["flag_dependency_warnings"]), 1)+ self.assertIn("missing-parent", success["flag_dependency_warnings"][0])+ # A dependency was dropped, so the copy is forced inactive for review even though the+ # remapped dependency still gates the group.+ self.assertFalse(copied_flag.active)++ def test_copy_feature_flag_remaps_dependency_per_target_without_leak(self):+ # Each target has its own same-key parent under a different ID. The remap runs on a per-target+ # deep copy of the filters, so each copy must point at its own target's parent and stay active.+ target_1 = self.team_2+ target_2 = Team.objects.create(organization=self.organization)+ source_parent = FeatureFlag.objects.create(+ team=self.team_1, created_by=self.user, key="parent-flag", active=True+ )+ parent_in_1 = FeatureFlag.objects.create(team=target_1, created_by=self.user, key="parent-flag", active=True)+ parent_in_2 = FeatureFlag.objects.create(team=target_2, created_by=self.user, key="parent-flag", active=True)+ dependent_flag = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="dependent-flag",+ active=True,+ filters={+ "groups": [{"rollout_percentage": 100, "properties": [self._flag_dependency_property(source_parent)]}]+ },+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": dependent_flag.key,+ "from_project": dependent_flag.team_id,+ "target_project_ids": [target_1.id, target_2.id],+ }+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["failed"]), 0)+ for success in response.json()["success"]:+ self.assertNotIn("flag_dependency_warnings", success)++ copied_1 = FeatureFlag.objects.get(key="dependent-flag", team_id=target_1.id)+ copied_2 = FeatureFlag.objects.get(key="dependent-flag", team_id=target_2.id)+ self.assertEqual(copied_1.filters["groups"][0]["properties"][0]["key"], str(parent_in_1.id))+ self.assertEqual(copied_2.filters["groups"][0]["properties"][0]["key"], str(parent_in_2.id))+ self.assertTrue(copied_1.active)+ self.assertTrue(copied_2.active)+def test_copy_remote_config_flag_preserves_type(self):"""Test that copying a remote config flag preserves the is_remote_configuration field."""url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 05b16970a063..0ad1fdaba0ea 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -34,6 +34,10 @@ export interface CopyFlagsSuccessItemApi {active: boolean/** Team ID the flag was copied to */team_id: number+ /** Warnings for flag dependencies that were dropped because no matching active flag exists in the target project */+ flag_dependency_warnings?: string[]+ /** Warning emitted when the flag was copied but its scheduled changes failed to copy */+ schedule_copy_warning?: string}export interface CopyFlagsResultApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 458f4ef75a85..405bc36c4df7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13808,6 +13808,10 @@ export namespace Schemas {active: boolean;/** Team ID the flag was copied to */team_id: number;+ /** Warnings for flag dependencies that were dropped because no matching active flag exists in the target project */+ flag_dependency_warnings?: string[];+ /** Warning emitted when the flag was copied but its scheduled changes failed to copy */+ schedule_copy_warning?: string;}export interface CopyFlagsResult {