: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): never read a non-v1 config document as v1 (#106609)
Andersd410c5888dac
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 530a1cef11e6..69d7f1d49bfe 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -3,7 +3,7 @@ import jsonimport timeimport uuidimport hashlib-from collections.abc import Iterator, Sequence+from collections.abc import Iterable, Iterator, Sequencefrom copy import deepcopyfrom typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast@@ -112,6 +112,7 @@ from products.cohorts.backend.realtime_state import (has_realtime_state,resolve_realtime_readiness,)+from products.feature_flags.backend.facade.config import ConfigFormatError, is_v1_configfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.team_feature_flags_config import (PropertyMatchingVersion,@@ -1405,7 +1406,9 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializcohort_id = instance.pkflags = FeatureFlag.objects.filter(team__project_id=self.context["project_id"], active=True)- cohort_used_in_flags = any(cohort_id in flag.get_cohort_ids(stop_traversal_at_static=True) for flag in flags)+ cohort_used_in_flags = any(+ cohort_id in flag.get_cohort_ids(stop_traversal_at_static=True) for flag in _v1_flags(flags)+ )if not cohort_used_in_flags:return@@ -1642,6 +1645,16 @@ def _flags_with_cohort_filters(cohort: Cohort) -> QuerySet[FeatureFlag]:)+def _v1_flags(flags: Iterable[FeatureFlag]) -> Iterator[FeatureFlag]:+ """Rows whose document carries the v1 release groups the cohort walks below read.++ A flag in another config format references cohorts in its own shape; until those reads+ exist it is skipped here rather than read as a flag with no conditions. Lazy, so a caller+ that short-circuits stops at the first match.+ """+ return (flag for flag in flags if is_v1_config(flag.filters))++def _directly_referenced_cohort_ids(flags: list[FeatureFlag]) -> set[int]:"""Cohort ids each flag references directly in its filter conditions.@@ -1668,7 +1681,7 @@ def _filter_flags_referencing_cohort(target still resolves: ``used_in`` reports flags referencing a deleted cohort, whichmatches the insights and cohorts blocks (neither checks the target's deleted state)."""- flag_list = list(flags)+ flag_list = list(_v1_flags(flags))seen_cohorts_cache: dict[int, CohortOrEmpty] = {cohort.id: cohort}direct_ids = _directly_referenced_cohort_ids(flag_list) - seen_cohorts_cache.keys()if direct_ids:@@ -2380,7 +2393,19 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)return- if not feature_flag.active or feature_flag.aggregation_group_type_index is not None:+ if not feature_flag.active:+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)+ return++ try:+ aggregates_by_group = feature_flag.aggregation_group_type_index is not None+ except ConfigFormatError:+ cohort._safe_save_cohort_state(+ team_id=team_id, processing_error="This flag uses a configuration format that cannot populate a cohort."+ )+ return++ if aggregates_by_group:cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)returndiff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex f7812c1359c5..a4aa97641b11 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -5324,6 +5324,66 @@ [email protected],}self.assertEqual(set(chain_cohort_ids), expected_cohort_ids)+ @patch("posthog.api.cohort.report_user_action")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_flags_in_another_config_format_are_skipped_by_the_flag_checks(self, patch_calculate_cohort, patch_capture):+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts",+ data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},+ )+ cohort_id = response.json()["id"]+ FeatureFlag.objects.create(+ team=self.team,+ filters={+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [+ {+ "id": "11111111-1111-4111-8111-111111111111",+ "rule_type": "targeted_release",+ "targeting": {"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]},+ "value": True,+ }+ ],+ },+ name="Other format flag",+ key="other-format",+ created_by=self.user,+ active=True,+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}",+ data={+ "filters": {+ "properties": {+ "type": "OR",+ "values": [{"key": "$some_prop", "value": "x", "type": "person", "operator": "exact"}],+ }+ }+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ FeatureFlag.objects.create(+ team=self.team,+ filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},+ name="Flag using cohort",+ key="cohort-flag",+ created_by=self.user,+ active=True,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}",+ data={"groups": [{"properties": {"team_id": 6}}]},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", data={"deleted": True})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("used in 1 active feature flag(s): Flag using cohort", response.json()["detail"])+@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_active_feature_flag(self, patch_calculate_cohort, patch_capture):diff --git a/posthog/management/commands/reencrypt_flag_payloads.py b/posthog/management/commands/reencrypt_flag_payloads.pyindex 45542ef56521..4b6d550e210f 100644--- a/posthog/management/commands/reencrypt_flag_payloads.py+++ b/posthog/management/commands/reencrypt_flag_payloads.py@@ -6,7 +6,7 @@ import structlogfrom cryptography.fernet import InvalidTokenfrom products.feature_flags.backend.encrypted_flag_payloads import FlagPayloadCodec, flag_payload_codec-from products.feature_flags.backend.facade.config import detect_config_format+from products.feature_flags.backend.facade.config import is_v1_configfrom products.feature_flags.backend.models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)@@ -67,8 +67,7 @@ class Command(BaseCommand):def _skip_unsupported(self, flag: FeatureFlag) -> bool:"""Only config format 1 stores ``payloads``; never touch a document in another format."""- filters = flag.filters- if filters is None or (isinstance(filters, dict) and detect_config_format(filters).kind == "v1"):+ if is_v1_config(flag.filters):return Falselogger.warning("reencrypt_flag_payloads.skip_unsupported_config", flag_id=flag.id, team_id=flag.team_id)return Truediff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex e1d2bf0cda35..7d186bac1fdd 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -834,6 +834,7 @@'_meta','_payloads','_tombstone_suffix',+ '_v1_filters','access','aggregation_group_type_index','analytics_dashboards',diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex d3220a12cb88..d3f9300e6180 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -214,6 +214,23 @@ class TestProductIntent(BaseTest):)self.assertTrue(self.product_intent.has_activated_feature_flags())+ def test_has_activated_feature_flags_ignores_flags_in_another_config_format(self):+ self.product_intent.product_type = "feature_flags"+ self.product_intent.save()+ FeatureFlag.objects.create(+ team=self.team,+ key="other-format",+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )+ for index in (1, 2):+ FeatureFlag.objects.create(+ team=self.team,+ key=f"flag-{index}",+ filters={"groups": [{"properties": [{"key": "email", "value": "[email protected]"}]}]},+ )++ self.assertTrue(self.product_intent.has_activated_feature_flags())+def test_has_activated_feature_flags_excludes_experiment_and_survey_flags(self):self.product_intent.product_type = "feature_flags"self.product_intent.save()diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.pyindex d8ad9e413803..402859084761 100644--- a/posthog/tasks/test/test_process_scheduled_changes.py+++ b/posthog/tasks/test/test_process_scheduled_changes.py@@ -138,6 +138,43 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):self.assertEqual(updated_flag.filters["groups"][0], new_release_condition)self.assertEqual(updated_flag.filters["multivariate"]["variants"], variants)+ def test_a_target_in_another_config_format_fails_without_blocking_the_batch(self) -> None:+ v2_document = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+ other_format = FeatureFlag.objects.create(+ name="other", key="other-format", active=True, filters=v2_document, team=self.team, created_by=self.user+ )+ v1_flag = FeatureFlag.objects.create(+ name="v1", key="v1-flag", active=False, filters={"groups": []}, team=self.team, created_by=self.user+ )+ failing = ScheduledChange.objects.create(+ team=self.team,+ record_id=other_format.id,+ model_name="FeatureFlag",+ payload={"operation": "add_release_condition", "value": {"groups": [{"properties": []}]}},+ scheduled_at=(datetime.now(UTC) - timedelta(seconds=60)),+ )+ applying = ScheduledChange.objects.create(+ team=self.team,+ record_id=v1_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": True},+ scheduled_at=(datetime.now(UTC) - timedelta(seconds=30)),+ )++ process_scheduled_changes()++ other_format.refresh_from_db()+ v1_flag.refresh_from_db()+ failing.refresh_from_db()+ applying.refresh_from_db()+ assert other_format.filters == v2_document+ assert v1_flag.active is True+ assert failing.failure_reason is not None+ assert json.loads(failing.failure_reason)["error_type"] == "ConfigFormatError"+ assert failing.executed_at is not None+ assert applying.failure_reason is None+ assert applying.executed_at is not None+def test_schedule_feature_flag_invalid_payload(self) -> None:feature_flag = FeatureFlag.objects.create(name="Flag 1",diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.pyindex 1c109ac24e2d..600b1e40c460 100644--- a/products/early_access_features/backend/test/test_early_access_feature.py+++ b/products/early_access_features/backend/test/test_early_access_feature.py@@ -675,6 +675,25 @@ class TestEarlyAccessFeature(APIBaseTest):"Group-based feature flags are not supported for Early Access Features.",)+ def test_cant_create_early_access_feature_with_flag_in_another_config_format(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ key="other-format",+ created_by=self.user,+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/early_access_feature/",+ data={"name": "Other format", "stage": "beta", "feature_flag_id": flag.id},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "configuration format that an early access feature cannot use yet" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.filters == {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+def test_cant_create_early_access_feature_with_multivariate_flag(self):flag = FeatureFlag.objects.create(team=self.team,diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex d2db9c35e22d..cd6213768f5b 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -3905,8 +3905,12 @@ class ExperimentService:should_check_existing = is_cross_project or feature_flag_key != source_experiment.feature_flag.keyif should_check_existing:existing_flag = FeatureFlag.objects.filter(key=feature_flag_key, team_id=target.id).first()- if existing_flag and existing_flag.variants:- clone_variants = deepcopy(existing_flag.variants)+ if existing_flag:+ # The same adoption check create_experiment applies, taken before the variants are+ # read so a flag this product cannot use surfaces as a validation error here too.+ assert_flag_available_for(existing_flag, product=FLAG_OWNER_EXPERIMENT)+ if existing_flag.variants:+ clone_variants = deepcopy(existing_flag.variants)clone_filters: dict[str, Any] = {}if clone_variants:diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 365cbfdfff99..4ce91cfb19c3 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -701,6 +701,20 @@ class TestExperimentService(APIBaseTest):assert "baseline variant cannot be excluded" in str(ctx.exception)+ def test_existing_flag_in_another_config_format_raises(self):+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="other-format",+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )++ with self.assertRaises(ValidationError) as ctx:+ self._service().create_experiment(name="Other format", feature_flag_key="other-format")++ assert "configuration format that an experiment cannot use yet" in str(ctx.exception)+ assert not Experiment.objects.filter(team=self.team, name="Other format").exists()+def test_existing_flag_with_one_variant_raises(self):self._create_flag(key="one-variant",@@ -2632,6 +2646,23 @@ class TestExperimentService(APIBaseTest):flag_variants = dup.feature_flag.filters["multivariate"]["variants"]assert len(flag_variants) == 3+ def test_duplicate_experiment_onto_a_flag_in_another_config_format_raises(self):+ self._create_flag(key="dup-source")+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="dup-other-format",+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )+ service = self._service()+ source = service.create_experiment(name="Source", feature_flag_key="dup-source")++ with self.assertRaises(ValidationError) as ctx:+ service.duplicate_experiment(source, feature_flag_key="dup-other-format")++ assert "configuration format that an experiment cannot use yet" in str(ctx.exception)+ assert Experiment.objects.filter(team=self.team).count() == 1+def test_duplicate_experiment_uses_flag_variants_over_stale_parameters(self):self._create_flag(key="dup-stale-source")service = self._service()diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex defbbada5c75..504a322e94aa 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -119,11 +119,7 @@ from products.feature_flags.backend.api.filters_schema import (FinitePercentageField,)from products.feature_flags.backend.api.remote_config_shadow import shadow_compare_remote_config-from products.feature_flags.backend.dependency_formats import (- DependencyConfigFormatError,- require_v1_config,- validate_dependency_formats,-)+from products.feature_flags.backend.dependency_formats import DependencyConfigFormatError, validate_dependency_formatsfrom products.feature_flags.backend.encrypted_flag_payloads import (REDACTED_PAYLOAD_VALUE,apply_approved_encrypted_payloads,@@ -135,7 +131,7 @@ from products.feature_flags.backend.facade import (config_writes,filters as flag_filters,)-from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format+from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format, require_v1_configfrom products.feature_flags.backend.facade.config_validation import ConfigValidationError, ValidationLimitsfrom products.feature_flags.backend.filters_validation import collect_cross_field_violations, flatten_structural_errorsfrom products.feature_flags.backend.flag_analytics import increment_request_count@@ -2746,7 +2742,8 @@ class FeatureFlagSerializer(if old_key != instance.key:_update_feature_flag_dashboard(instance, old_key)- if instance.has_feature_enrollment:+ # Enrollment lives in the v1 document; a v2 flag cannot back an early access feature.+ if detect_config_format(instance.filters).kind == "v1" and instance.has_feature_enrollment:from products.feature_flags.backend.tasks import migrate_feature_enrollment_on_key_changemigrate_feature_enrollment_on_key_change.delay(instance.team_id, old_key, instance.id)@@ -4581,6 +4578,12 @@ class FeatureFlagViewSet(rejection = self._deleted_flag_rejection(feature_flag, deleted_hint)if rejection is not None:return rejection+ # A format change bumps `version`, so the locked precondition refuses one landing after this.+ if detect_config_format(feature_flag.filters).kind != "v1":+ raise exceptions.ValidationError(+ "This flag uses a configuration format that rollout actions cannot modify yet.",+ code="unsupported_config_version",+ )# A flag written before versioning reads as null; the precondition normalises the stored# side the same way, so a caller can send back exactly what the read returned.diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 03fa6bfdfb76..b40a97c6ed8f 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -41,6 +41,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,)from products.feature_flags.backend.facade.api import create_flag, serialize_flags, update_flag+from products.feature_flags.backend.facade.config import ConfigFormatErrorfrom products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -496,14 +497,18 @@ class OrganizationFeatureFlagView(return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST)copy_source_flags = [*dependency_graph.dependency_flags, flag_to_copy]- copy_source_contexts = {- source_flag.id: self._get_feature_flag_copy_source_context(- source_flag,- copy_schedule,- user,- )- for source_flag in copy_source_flags- }+ copy_source_contexts: dict[int, FeatureFlagCopySourceContext] = {}+ for source_flag in copy_source_flags:+ try:+ copy_source_contexts[source_flag.id] = self._get_feature_flag_copy_source_context(+ source_flag, copy_schedule, user+ )+ except ConfigFormatError:+ subject = "This flag" if source_flag.id == flag_to_copy.id else f"Dependency flag '{source_flag.key}'"+ return Response(+ {"error": f"{subject} uses a configuration format that cannot be copied yet."},+ status=status.HTTP_400_BAD_REQUEST,+ )successful_projects = []failed_projects = []diff --git a/products/feature_flags/backend/api/scheduled_change.py b/products/feature_flags/backend/api/scheduled_change.pyindex 46349a9ba389..bcc6f232c0bc 100644--- a/products/feature_flags/backend/api/scheduled_change.py+++ b/products/feature_flags/backend/api/scheduled_change.py@@ -16,6 +16,7 @@ from products.approvals.backend.models import ChangeRequest, ChangeRequestStatefrom products.approvals.backend.scheduled_changes import gate_scheduled_changefrom products.approvals.backend.serializers import ChangeRequestSummarySerializerfrom products.feature_flags.backend.api.feature_flag import CanEditFeatureFlag+from products.feature_flags.backend.facade.config import detect_config_formatfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -129,6 +130,20 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):return Nonereturn obj.formatted_failure_reason+ @staticmethod+ def _reject_unsupported_target(feature_flag: FeatureFlag, payload: object) -> None:+ # A status change never reads the document; every other operation merges into it as v1+ # (build_scheduled_change_serializer_data), so a target in another config format fails+ # closed when scheduled rather than when fired. Payload shape stays the applier's business.+ operation = payload.get("operation") if isinstance(payload, dict) else None+ if operation == ScheduledChange.OperationType.UPDATE_STATUS:+ return+ if detect_config_format(feature_flag.filters).kind != "v1":+ raise serializers.ValidationError(+ {"payload": "This flag uses a configuration format that scheduled changes cannot modify."},+ code="unsupported_config_version",+ )+def validate(self, data: dict) -> dict:instance = getattr(self, "instance", None)@@ -285,6 +300,7 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):# same flag here but would dodge the str-equality access filter in the viewset if persisted verbatim.if feature_flag is not None:validated_data["record_id"] = str(feature_flag.id)+ self._reject_unsupported_target(feature_flag, validated_data.get("payload", {}))# Capture the project's timezone at creation time so cron recurrence resolves# wall-clock fields in that timezone, independent of later team.timezone changes.@@ -317,6 +333,7 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):# Canonicalize any legacy non-canonical record_id so the access filter keeps matching it.if feature_flag is not None:instance.record_id = str(feature_flag.id)+ self._reject_unsupported_target(feature_flag, validated_data.get("payload", instance.payload))# Re-gate whenever the payload changes: create() only gates the payload the row is born with,# so without this an editor could create an ungated schedule and then PATCH its payload to adiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 1c6bf7fb6b1f..71847f821a6b 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -9362,6 +9362,30 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):cohort.refresh_from_db()self.assertEqual(cohort.count, None)+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_flag_in_another_config_format_records_an_error_without_calling_service(self, mock_batch_evaluate):+ self._create_flag(filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []})+ cohort = self._create_static_cohort()++ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ mock_batch_evaluate.assert_not_called()+ cohort.refresh_from_db()+ self.assertEqual((cohort.count, cohort.is_calculating, cohort.errors_calculating), (None, False, 1))++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_inactive_flag_in_another_config_format_is_a_clean_no_op(self, mock_batch_evaluate):+ self._create_flag(+ active=False, filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+ )+ cohort = self._create_static_cohort()++ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ mock_batch_evaluate.assert_not_called()+ cohort.refresh_from_db()+ self.assertEqual((cohort.count, cohort.is_calculating, cohort.errors_calculating), (None, False, 0))+@patch("posthog.api.cohort.batch_evaluate_flag_for_team")def test_group_flag_returns_empty_without_calling_service(self, mock_batch_evaluate):self._create_flag(diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.pyindex 455b6eda7508..7bfe7083dc81 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py@@ -596,6 +596,13 @@ class TestV2AdmissionBoundary(AdmittedV2TestCase):flag.refresh_from_db()assert (flag.name, flag.key, flag.version) == ("Renamed", "v2-renamed", 4)+ def test_a_key_change_never_reads_v1_enrollment(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "key": "v2-renamed"})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.key, flag.filters) == ("v2-renamed", config(targeted(), rollout()))+@parameterized.expand(["has_encrypted_payloads", "is_remote_configuration"])def test_unsupported_flag_families_are_not_admitted(self, field: str) -> None:# Not in the admitted family, so the write falls back to the closed path ratherdiff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py b/products/feature_flags/backend/api/test/test_feature_flag_config_version.pyindex f3a4871665b1..faf67818453f 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py@@ -156,3 +156,42 @@ class TestFeatureFlagConfigVersionWrites(APIBaseTest):assert flag.filters == filterselse:assert not FeatureFlag.objects.filter(team=self.team, key="reserved-version").exists()+++V2_DOCUMENT = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+++class TestV2RowReads(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.v2_flag = FeatureFlag.objects.create(+ team=self.team, key="v2-flag", created_by=self.user, filters=V2_DOCUMENT+ )+ self.v1_flag = FeatureFlag.objects.create(+ team=self.team,+ key="v1-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ def test_get_serializes_the_stored_document(self) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{self.v2_flag.id}/")+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["filters"] == V2_DOCUMENT+ assert response.json()["is_eligible_for_experiment"] is False++ def test_list_serves_v1_and_v2_rows_together(self) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/")+ assert response.status_code == status.HTTP_200_OK, response.json()+ filters_by_key = {flag["key"]: flag["filters"] for flag in response.json()["results"]}+ assert filters_by_key["v2-flag"] == V2_DOCUMENT+ assert filters_by_key["v1-flag"]["groups"] == [{"properties": [], "rollout_percentage": 100}]++ def test_activity_and_version_history_read_the_v2_row(self) -> None:+ activity = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{self.v2_flag.id}/activity/")+ assert activity.status_code == status.HTTP_200_OK, activity.json()+ history = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/{self.v2_flag.id}/versions/{self.v2_flag.version}/"+ )+ assert history.status_code == status.HTTP_200_OK, history.json()+ assert history.json()["filters"] == V2_DOCUMENTdiff --git a/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.py b/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.pyindex 14dee9023593..dcfb9711fd7e 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.py@@ -334,6 +334,18 @@ class TestFeatureFlagRolloutActions(APIBaseTest):assert "has been deleted" in response.json()["error"]assert set(response.json()) == set(FlagDeletedRejectionSerializer().fields)+ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_refuses_a_flag_in_another_config_format(self, action, body):+ v2_filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+ flag = self._flag(filters=v2_filters)++ response = self._act(flag, action, {**body, "version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["code"] == "unsupported_config_version"+ flag.refresh_from_db()+ assert flag.filters == v2_filters+@parameterized.expand(ROLLOUT_ACTIONS)def test_rollout_action_requires_the_feature_flag_write_scope(self, action, body):flag = self._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 780f331f7c81..679895d1d9aa 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@@ -450,6 +450,46 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):]self.organization.save()+ def test_copy_rejects_a_source_in_another_config_format(self):+ self.feature_flag_to_copy.filters = {+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [],+ }+ self.feature_flag_to_copy.save()++ response = self.client.post(+ f"/api/organizations/{self.organization.id}/feature_flags/copy_flags",+ {+ "feature_flag_key": self.feature_flag_to_copy.key,+ "from_project": self.feature_flag_to_copy.team_id,+ "target_project_ids": [self.team_2.id],+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "configuration format" in response.json()["error"]+ assert not FeatureFlag.objects.filter(team=self.team_2, key=self.feature_flag_to_copy.key).exists()++ def test_copy_names_a_dependency_in_another_config_format(self):+ dependency = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="other-format-dependency",+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )+ self.feature_flag_to_copy.filters = {+ "groups": [{"rollout_percentage": 100, "properties": [self._flag_dependency_property(dependency)]}]+ }+ self.feature_flag_to_copy.save()++ response = self._post_copy_flag(self.feature_flag_to_copy, copy_dependencies=True)++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["error"].startswith("Dependency flag 'other-format-dependency' uses")+ assert not FeatureFlag.objects.filter(team=self.team_2, key=self.feature_flag_to_copy.key).exists()+@parameterized.expand(["evaluation_contexts", "tags"])def test_copy_succeeds_when_target_requires_flag_metadata(self, requirement):from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigdiff --git a/products/feature_flags/backend/api/test/test_scheduled_change.py b/products/feature_flags/backend/api/test/test_scheduled_change.pyindex cd750adfb052..f4f60382e687 100644--- a/products/feature_flags/backend/api/test/test_scheduled_change.py+++ b/products/feature_flags/backend/api/test/test_scheduled_change.py@@ -55,6 +55,69 @@ class TestScheduledChange(APIBaseTest):assert response_data["created_by"]["id"] == self.user.idassert response_data["change_request"] is None+ def test_v1_merge_operations_are_rejected_for_a_target_in_another_config_format(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="other-format",+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )+ base = {"record_id": str(flag.id), "model_name": "FeatureFlag", "scheduled_at": "2030-01-01T00:00:00Z"}++ merges: list[tuple[str, dict]] = [+ ("add_release_condition", {"groups": []}),+ ("update_variants", {"variants": []}),+ ]+ for operation, value in merges:+ response = self.client.post(+ f"/api/projects/{self.team.id}/scheduled_changes/",+ data={**base, "payload": {"operation": operation, "value": value}},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert (response.json()["code"], response.json()["attr"]) == ("unsupported_config_version", "payload")+ assert not ScheduledChange.objects.filter(record_id=str(flag.id)).exists()++ response = self.client.post(+ f"/api/projects/{self.team.id}/scheduled_changes/",+ data={**base, "payload": {"operation": "update_status", "value": True}},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ schedule_url = f"/api/projects/{self.team.id}/scheduled_changes/{response.json()['id']}/"++ response = self.client.patch(schedule_url, data={"scheduled_at": "2030-02-01T00:00:00Z"}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()++ response = self.client.patch(+ schedule_url,+ data={"payload": {"operation": "add_release_condition", "value": {"groups": []}}},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["code"] == "unsupported_config_version"++ @parameterized.expand(+ [("null_groups", {"operation": "add_release_condition", "value": {"groups": None}}), ("list", [])]+ )+ def test_a_v1_target_leaves_payload_shape_errors_to_the_applier(self, _name, payload):+ flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="v1", filters={"groups": [{"properties": []}]}+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/scheduled_changes/",+ data={+ "record_id": str(flag.id),+ "model_name": "FeatureFlag",+ "scheduled_at": "2030-01-01T00:00:00Z",+ "payload": payload,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+def test_cannot_create_scheduled_change_without_feature_flag_edit_permission(self):"""Test that users without edit permissions cannot create scheduled changes for feature flags"""# Create a feature flagdiff --git a/products/feature_flags/backend/dependency_formats.py b/products/feature_flags/backend/dependency_formats.pyindex 012ed366fde9..6cbb7fcb1f10 100644--- a/products/feature_flags/backend/dependency_formats.py+++ b/products/feature_flags/backend/dependency_formats.py@@ -5,7 +5,7 @@ from pydantic import JsonValuefrom posthog.utils import safe_int-from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format+from products.feature_flags.backend.facade.config import ConfigFormatError, require_v1_configfrom products.feature_flags.backend.models.feature_flag import FeatureFlagDEPENDENCY_BATCH_SIZE = 100@@ -17,12 +17,6 @@ class DependencyConfigFormatError(ConfigFormatError):self.flag_id = flag_id-def require_v1_config(filters: Mapping[str, JsonValue] | None) -> None:- config_format = detect_config_format(filters)- if config_format.kind != "v1":- raise ConfigFormatError(config_format)--def _dependency_ids(filters: Mapping[str, JsonValue]) -> Iterator[int]:# Unlike facade.references.flag_dependency_properties, this walk skips malformed# stored groups and properties so format checks do not change their validation policy.diff --git a/products/feature_flags/backend/facade/config.py b/products/feature_flags/backend/facade/config.pyindex cdf3f42ad1dc..9207637cb6d1 100644--- a/products/feature_flags/backend/facade/config.py+++ b/products/feature_flags/backend/facade/config.py@@ -8,8 +8,9 @@ unrelated to ``filters.version``.Detection follows the Feature Flag Rules v2 contract: an absent ``version`` or a number thatequals 1 selects v1, a number that equals 2 selects v2, and everything else is unsupported.-A JSON string or boolean never selects a version. An unsupported document is never read as-v1, so a reader with only a v1 branch checks the format before it touches any v1 key.+A JSON string or boolean never selects a version, and a stored value that is not an object+(a list, say) is unsupported outright. An unsupported document is never read as v1, so a+reader with only a v1 branch checks the format before it touches any v1 key.The v2 DTOs are structural reads of a stored document. They carry the fields later consumersroute on (return type, ordered rule identities, experiment identity) and nothing else. The@@ -45,8 +46,13 @@ class ConfigFormatError(ValueError):self.config_format = config_format-def detect_config_format(filters: Mapping[str, Any] | None) -> ConfigFormat:- if not filters or "version" not in filters:+def detect_config_format(filters: object) -> ConfigFormat:+ if filters is None:+ return ConfigFormat(kind="v1", raw_version=None)+ if not isinstance(filters, Mapping):+ # A list, string or number is no config document at all, so it is never read as v1.+ return ConfigFormat(kind="unsupported", raw_version=None)+ if "version" not in filters:return ConfigFormat(kind="v1", raw_version=None)version = filters["version"]# bool is an int subclass, so ``True == 1`` would read as v1 without this guard.@@ -59,6 +65,18 @@ def detect_config_format(filters: Mapping[str, Any] | None) -> ConfigFormat:return ConfigFormat(kind="unsupported", raw_version=version)+def require_v1_config(filters: Mapping[str, Any] | None) -> None:+ """Raise ``ConfigFormatError`` unless ``filters`` is a config version 1 document."""+ config_format = detect_config_format(filters)+ if config_format.kind != "v1":+ raise ConfigFormatError(config_format)+++def is_v1_config(filters: object) -> bool:+ """Whether a stored ``filters`` value is a config version 1 document (or null)."""+ return detect_config_format(filters).kind == "v1"++@frozenclass RuleV2:id: strdiff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.pyindex 150b7390baa6..858d616c1807 100644--- a/products/feature_flags/backend/facade/filters.py+++ b/products/feature_flags/backend/facade/filters.py@@ -6,6 +6,10 @@ conditions) so consumers don't have to. The marker keys and notes are opaque valpassed in by the caller — e.g. experiments' enrollment freeze — so the flag productlearns no consumer concepts.+Every transform and predicate reads config version 1 keys, so each one raises+``ConfigFormatError`` for a document in any other format before it reads or copies+anything: a v2 document must never silently gain v1 keys here.+Deliberately free of Django/DRF imports: consumer model modules import these predicatesat module level, and routing them through ``facade.api`` (which imports the flagserializer, whose module imports back into consumers) would create an import cycle.@@ -14,6 +18,8 @@ serializer, whose module imports back into consumers) would create an import cycfrom copy import deepcopyfrom typing import Literal+from products.feature_flags.backend.facade.config import require_v1_config+CohortRestrictionBlocker = Literal["group_aggregation", "holdout", "super_groups", "no_groups"]# Flag-level settings the flags service evaluates before, or instead of, the release conditions.@@ -42,6 +48,7 @@ def restrict_groups_to_cohort(to the (preserved) ``description`` as a human-readable note. Everything else(``multivariate``, ``payloads``, aggregation index) is left byte-for-byte."""+ require_v1_config(current_filters)cohort_condition = {"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}new_groups = []@@ -74,6 +81,7 @@ def strip_group_cohort_restriction(then: deleting earlier would yank the cohort from under a still-restricted flag if thesave fails."""+ require_v1_config(current_filters)new_groups = []cohort_ids: list[int] = []for group in current_filters.get("groups", []):@@ -116,6 +124,7 @@ def groups_carry_restriction_marker(current_filters: dict, *, marker_key: str) -restriction being lifted; an empty ``groups`` list is not restricted (there is nothingholding anyone back)."""+ require_v1_config(current_filters)groups = current_filters.get("groups", [])return bool(groups) and all(group.get(marker_key) is True for group in groups)@@ -129,6 +138,7 @@ def replace_variant_distribution(current_filters: dict, variants: list[dict]) ->configuration it doesn't know about. ``variants`` are deepcopied so the returnedfilters never alias the caller's dicts."""+ require_v1_config(current_filters)return {**current_filters, "multivariate": {"variants": deepcopy(variants)}}@@ -138,6 +148,7 @@ def replace_release_conditions(current_filters: dict, groups: list[dict]) -> dicEvery other key (``multivariate``, ``payloads``, aggregation, holdout/super groups)is preserved — only who the flag releases to changes, not what it serves."""+ require_v1_config(current_filters)return {**current_filters, "groups": deepcopy(groups)}@@ -149,6 +160,7 @@ def set_holdout(current_filters: dict, *, holdout_id: int | None, exclusion_perc``holdout`` key is written as None (not removed), so a previously attached holdoutis detached by the same write."""+ require_v1_config(current_filters)if not holdout_id or exclusion_percentage is None:return {**current_filters, "holdout": None}return {**current_filters, "holdout": {"id": holdout_id, "exclusion_percentage": exclusion_percentage}}@@ -164,6 +176,7 @@ def set_feature_enrollment(current_filters: dict, enrolled: bool | None, *, grouearly access uses it to roll a generally-available feature out to everyone.Everything else is spread through untouched."""+ require_v1_config(current_filters)new_filters = {**current_filters, "feature_enrollment": enrolled}new_filters.pop("super_groups", None)if groups is not None:@@ -187,6 +200,7 @@ def group_cohort_restriction_blocker(current_filters: dict) -> CohortRestrictionChecked in that order; the first blocker wins."""+ require_v1_config(current_filters)if current_filters.get("aggregation_group_type_index") is not None:return "group_aggregation"if current_filters.get("holdout") or current_filters.get("holdout_groups"):@@ -206,6 +220,7 @@ def set_release_condition_rollout(current_filters: dict, condition_index: int, ris only meaningful for the definition the caller read, so resolving it to some othercondition would change a rule the caller never saw."""+ require_v1_config(current_filters)groups = current_filters.get("groups") or []if not 0 <= condition_index < len(groups):raise IndexError(f"No release condition at index {condition_index}; the flag has {len(groups)}.")@@ -232,6 +247,7 @@ def _leads_with_unconditional_rollout(current_filters: dict) -> bool:matcher resolves aggregation per condition and skips one whose group type the evaluationdoes not supply, so such a condition does not serve everyone the flag otherwise would."""+ require_v1_config(current_filters)groups = current_filters.get("groups") or []if not groups:return False@@ -259,6 +275,7 @@ def roll_out_to_everyone(current_filters: dict, *, variant_key: str | None = NonA flag that already leads with a property-free 100% condition gains no second one, so acaller that repeats the call writes nothing."""+ require_v1_config(current_filters)new_filters = deepcopy(current_filters)if variant_key is not None:diff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.pyindex dec479f46bbd..f4f13b757030 100644--- a/products/feature_flags/backend/flag_version_sync.py+++ b/products/feature_flags/backend/flag_version_sync.py@@ -44,6 +44,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, LogActifrom posthog.models.activity_logging.utils import activity_storagefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.feature_flags.backend.facade.config import ConfigFormatErrorfrom products.feature_flags.backend.field_snapshots import capture_fields_before_save, snapshot_if_changedfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -263,6 +264,9 @@ def direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:dependency_ids: set[int] = set()try:conditions = flag.conditions+ except ConfigFormatError:+ # Only a v1 document carries release groups, so a row in another format has no v1 edges.+ return dependency_idsexcept Exception:# A sibling flag with malformed filters must neither break the save nor suppress# the bump for healthy flags.@@ -381,6 +385,8 @@ def _flags_referencing_cohort(cohort: Cohort) -> list[FeatureFlag]:try:if cohort.pk in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache, stop_traversal_at_static=True):flags.append(flag)+ except ConfigFormatError:+ continueexcept Exception:# A sibling flag with malformed filters (e.g. a non-numeric cohort value,# which get_cohort_ids doesn't tolerate) must neither break the cohort savediff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex c3799294c550..f78488851478 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -22,6 +22,7 @@ from posthog.models.utils import RootTeamManager, RootTeamMixin, RootTeamQuerySefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.experiments.backend.models.experiment import live_experiment_exists+from products.feature_flags.backend.facade.config import ConfigFormatError, require_v1_configfrom products.feature_flags.backend.variant_rollout import format_variant_rollout_sum, variant_rollout_sum_is_100if TYPE_CHECKING:@@ -51,6 +52,10 @@ def build_scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[stCallers decide what ``None`` means: the gate declines to gate an uninterpretable change; thedispatcher raises. Apply-time-only validation (variant rollout sums, payload-key matching)stays in the dispatcher.++ Raises ``ConfigFormatError`` when any operation other than ``update_status`` targets a flag+ whose ``filters`` is not config version 1. ``update_status`` never reads ``filters``, so it+ never raises."""operation = payload.get("operation")if operation is None or "value" not in payload:@@ -61,6 +66,8 @@ def build_scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[streturn {"active": value}current_filters = flag.get_filters()+ # The merges below are v1 merges; a target in another format fails closed here.+ require_v1_config(current_filters)if operation == "add_release_condition":new_groups = value.get("groups", []) if isinstance(value, dict) else []@@ -303,6 +310,10 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMix)def get_analytics_metadata(self) -> dict:+ try:+ self._v1_filters()+ except ConfigFormatError as exc:+ return {"created_at": self.created_at, "config_format": exc.config_format.kind}filter_count = sum(len(condition.get("properties", [])) for condition in self.conditions)variants_count = len(self.variants)payload_count = len(self._payloads)@@ -319,22 +330,34 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMix"payload_count": payload_count,}+ def _v1_filters(self) -> dict:+ """The stored document when it is config version 1; any other format raises ``ConfigFormatError``.++ The accessors below read v1 keys. A document in another format must never reach+ them and be read as a flag with no conditions and no variants; callers that can+ meet such a row catch the error. ``get_filters()`` stays raw for readers that+ classify the document themselves.+ """+ filters = self.get_filters()+ require_v1_config(filters)+ return filters+@propertydef conditions(self):"Each feature flag can have multiple conditions to match, they are OR-ed together."- return self.get_filters().get("groups", []) or []+ return self._v1_filters().get("groups", []) or []@propertydef has_feature_enrollment(self) -> bool:- return bool(self.get_filters().get("feature_enrollment", False))+ return bool(self._v1_filters().get("feature_enrollment", False))@propertydef holdout(self):- return self.get_filters().get("holdout", None)+ return self._v1_filters().get("holdout", None)@propertydef _payloads(self):- return self.get_filters().get("payloads", {}) or {}+ return self._v1_filters().get("payloads", {}) or {}def get_payload(self, match_val: str) -> Optional[object]:return self._payloads.get(match_val, None)@@ -342,12 +365,12 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMix@propertydef aggregation_group_type_index(self) -> Optional[GroupTypeIndex]:"If None, aggregating this feature flag by persons, otherwise by groups of given group_type_index"- return self.get_filters().get("aggregation_group_type_index", None)+ return self._v1_filters().get("aggregation_group_type_index", None)@propertydef variants(self):# :TRICKY: .get("multivariate", {}) returns "None" if the key is explicitly set to "null" inside json filters- multivariate = self.get_filters().get("multivariate", None)+ multivariate = self._v1_filters().get("multivariate", None)if isinstance(multivariate, dict):variants = multivariate.get("variants", None)if isinstance(variants, list):@@ -356,7 +379,12 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMix@propertydef is_eligible_for_experiment(self) -> bool:- return experiment_eligibility_error(self.variants) is None+ try:+ variants = self.variants+ except ConfigFormatError:+ # Only a v1 document carries the variants an experiment reads.+ return False+ return experiment_eligibility_error(variants) is None@propertydef usage_dashboard_has_enriched_insights(self) -> bool:diff --git a/products/feature_flags/backend/ownership.py b/products/feature_flags/backend/ownership.pyindex 0eafc2de8951..1cde62fd7305 100644--- a/products/feature_flags/backend/ownership.py+++ b/products/feature_flags/backend/ownership.py@@ -2,6 +2,8 @@ from typing import TYPE_CHECKINGfrom rest_framework import serializers+from products.feature_flags.backend.facade.config import detect_config_format+if TYPE_CHECKING:from products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -63,7 +65,15 @@ def assert_flag_available_for(flag: "FeatureFlag", *, product: str) -> None:This reads before the caller writes, so two products adopting the same free flag at the samemoment can both pass. No database constraint can span the four owning tables, so the remainingwindow is accepted rather than locked.++ A flag stored in another config format is not available either: every adopting product reads+ and writes its document as config version 1."""+ if detect_config_format(flag.filters).kind != "v1":+ raise serializers.ValidationError(+ f"The feature flag {flag.key} uses a configuration format that {_OWNER_LABELS[product]} "+ "cannot use yet. Pick a different flag."+ )owner = flag_owner_kind(flag)if owner is not None and owner != product:raise serializers.ValidationError(diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.pyindex e52f387b5ed8..60ac0be9c858 100644--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py@@ -16,7 +16,7 @@ from posthog.temporal.health_checks.models import HealthCheckResultfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment-from products.feature_flags.backend.facade.config import detect_config_format+from products.feature_flags.backend.facade.config import is_v1_configfrom products.feature_flags.backend.facade.filters import EVALUATED_BEFORE_RELEASE_CONDITIONSfrom products.feature_flags.backend.flag_status import (ROLLOUT_FULLY_ROLLED_OUT,@@ -217,8 +217,7 @@ def _v1_flags(flags: Iterable[FeatureFlag]) -> list[FeatureFlag]:"""kept = []for flag in flags:- filters = flag.filters- if filters is None or (isinstance(filters, dict) and detect_config_format(filters).kind == "v1"):+ if is_v1_config(flag.filters):kept.append(flag)else:logger.info("stale_feature_flags_skipped_unsupported_config", flag_id=flag.id, team_id=flag.team_id)diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex add3012c007b..3e3ff6949a94 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -28,6 +28,7 @@ from products.feature_flags.backend.facade.api import ()from products.feature_flags.backend.facade.config import ConfigFormatErrorfrom products.feature_flags.backend.facade.filters import (+ _leads_with_unconditional_rollout,group_cohort_restriction_blocker,groups_carry_restriction_marker,replace_release_conditions,@@ -40,7 +41,7 @@ from products.feature_flags.backend.facade.filters import (strip_group_cohort_restriction,)from products.feature_flags.backend.facade.rules import ExperimentRuleConfig, HoldoutRef, experiment_rule_from_filters-from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag, build_scheduled_change_serializer_dataclass TestFeatureFlagFacadeGatedWrites(APIBaseTest):@@ -1039,3 +1040,121 @@ class TestExperimentRuleFromFilters:with pytest.raises(ConfigFormatError) as exc_info:experiment_rule_from_filters(filters)assert exc_info.value.config_format.kind == expected_kind+++V1_GROUPS = [{"properties": [], "rollout_percentage": 40}]+UNSUPPORTED_DOCUMENTS = [+ ("v2_document", {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}),+ ("v2_discriminator_over_v1_keys", {"version": 2, "groups": V1_GROUPS}),+ ("string_discriminator", {"version": "1", "groups": V1_GROUPS}),+ ("boolean_discriminator", {"version": True, "groups": V1_GROUPS}),+ ("null_discriminator", {"version": None, "groups": V1_GROUPS}),+ ("unknown_future_version", {"version": 3, "groups": V1_GROUPS}),+]+ACCESSORS = (+ "conditions",+ "has_feature_enrollment",+ "holdout",+ "aggregation_group_type_index",+ "variants",+ "uses_cohorts",+)+++class TestModelAccessorsRequireV1:+ @parameterized.expand(UNSUPPORTED_DOCUMENTS)+ def test_accessors_raise_instead_of_reading_an_empty_v1_flag(self, _name, filters):+ flag = FeatureFlag(filters=filters)+ for accessor in ACCESSORS:+ with pytest.raises(ConfigFormatError):+ getattr(flag, accessor)+ with pytest.raises(ConfigFormatError):+ flag.get_payload("true")+ with pytest.raises(ConfigFormatError):+ flag.get_cohort_ids()+ assert flag.is_eligible_for_experiment is False+ assert flag.get_analytics_metadata() == {+ "created_at": flag.created_at,+ "config_format": "v2" if filters.get("version") == 2 else "unsupported",+ }++ @parameterized.expand(+ [+ ("empty", {}, [], [], None, None, False),+ ("explicit_version_1", {"version": 1, "groups": V1_GROUPS}, V1_GROUPS, [], None, None, False),+ ("null_groups", {"groups": None}, [], [], None, None, False),+ ("null_multivariate", {"multivariate": None}, [], [], None, None, False),+ ("null_variants", {"multivariate": {"variants": None}}, [], [], None, None, False),+ ("null_payloads_and_enrollment", {"payloads": None, "feature_enrollment": None}, [], [], None, None, False),+ (+ "full_shape",+ {+ "groups": V1_GROUPS,+ "multivariate": {"variants": [{"key": "a", "rollout_percentage": 100}]},+ "payloads": {"a": "1"},+ "holdout": {"id": 7},+ "aggregation_group_type_index": 2,+ "feature_enrollment": True,+ },+ V1_GROUPS,+ [{"key": "a", "rollout_percentage": 100}],+ {"id": 7},+ 2,+ True,+ ),+ ]+ )+ def test_v1_shapes_keep_their_values(self, _name, filters, conditions, variants, holdout, index, enrolled):+ flag = FeatureFlag(filters=filters)+ assert flag.conditions == conditions+ assert flag.variants == variants+ assert flag.holdout == holdout+ assert flag.aggregation_group_type_index == index+ assert flag.has_feature_enrollment is enrolled+ assert flag.get_payload("a") == (filters.get("payloads") or {}).get("a")+ assert flag.get_analytics_metadata()["groups_count"] == len(conditions)+++class TestScheduledChangeBuilderRequiresV1:+ @parameterized.expand(UNSUPPORTED_DOCUMENTS)+ def test_v1_merges_fail_closed_and_status_changes_do_not_read_the_document(self, _name, filters):+ flag = FeatureFlag(filters=filters)+ for payload in (+ {"operation": "add_release_condition", "value": {"groups": V1_GROUPS}},+ {"operation": "update_variants", "value": {"variants": []}},+ ):+ with pytest.raises(ConfigFormatError):+ build_scheduled_change_serializer_data(flag, payload)+ assert build_scheduled_change_serializer_data(flag, {"operation": "update_status", "value": True}) == {+ "active": True+ }+++TRANSFORMS = [+ ("restrict_groups_to_cohort", lambda filters: restrict_groups_to_cohort(filters, 42, **MARKER_KWARGS)),+ ("strip_group_cohort_restriction", lambda filters: strip_group_cohort_restriction(filters, **MARKER_KWARGS)),+ ("groups_carry_restriction_marker", lambda filters: groups_carry_restriction_marker(filters, marker_key="m")),+ ("replace_variant_distribution", lambda filters: replace_variant_distribution(filters, [])),+ ("replace_release_conditions", lambda filters: replace_release_conditions(filters, [])),+ ("set_holdout", lambda filters: set_holdout(filters, holdout_id=None, exclusion_percentage=None)),+ ("set_feature_enrollment", lambda filters: set_feature_enrollment(filters, True)),+ ("group_cohort_restriction_blocker", group_cohort_restriction_blocker),+ ("set_release_condition_rollout", lambda filters: set_release_condition_rollout(filters, 0, 10)),+ ("_leads_with_unconditional_rollout", _leads_with_unconditional_rollout),+ ("roll_out_to_everyone", roll_out_to_everyone),+]+++class TestFilterTransformsRequireV1:+ @parameterized.expand(+ [+ (f"{transform_name}_{document_name}", transform, filters)+ for transform_name, transform in TRANSFORMS+ for document_name, filters in UNSUPPORTED_DOCUMENTS+ ]+ )+ def test_transforms_raise_before_copying(self, _name, transform, filters):+ pristine = deepcopy(filters)+ with pytest.raises(ConfigFormatError):+ transform(filters)+ assert filters == pristinediff --git a/products/feature_flags/backend/test/test_facade_config.py b/products/feature_flags/backend/test/test_facade_config.pyindex ae76cba39ffb..79b4c4cddd24 100644--- a/products/feature_flags/backend/test/test_facade_config.py+++ b/products/feature_flags/backend/test/test_facade_config.py@@ -115,6 +115,8 @@ class TestDetectConfigFormat:("version_null", {"version": None}, ConfigFormat(kind="unsupported", raw_version=None)),("unknown_future_version", {"version": 3}, ConfigFormat(kind="unsupported", raw_version=3)),("fractional_version", {"version": 1.5}, ConfigFormat(kind="unsupported", raw_version=1.5)),+ ("list_document", [], ConfigFormat(kind="unsupported", raw_version=None)),+ ("string_document", "{}", ConfigFormat(kind="unsupported", raw_version=None)),])def test_detection(self, _name, filters, expected):diff --git a/products/feature_flags/backend/test/test_flag_version_sync.py b/products/feature_flags/backend/test/test_flag_version_sync.pyindex e86ba9d04150..254e96fbcfd0 100644--- a/products/feature_flags/backend/test/test_flag_version_sync.py+++ b/products/feature_flags/backend/test/test_flag_version_sync.py@@ -3,6 +3,7 @@ from posthog.test.base import BaseTestfrom django.utils import timezonefrom parameterized import parameterized+from structlog.testing import capture_logsfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.activity_logging.utils import activity_storage@@ -43,6 +44,23 @@ def _flag_dependency_filters(dependency_flag_id: int | str) -> dict:}+def _other_format_filters(referenced: dict) -> dict:+ # A v2 document whose predicate matches the receivers' jsonb prefilters, so it reaches the v1 reads.+ return {+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [+ {+ "id": "11111111-1111-4111-8111-111111111111",+ "rule_type": "targeted_release",+ "targeting": {"properties": [referenced]},+ "value": True,+ }+ ],+ }++def _cohort_filters(cohort_id: int) -> dict:return {"properties": {@@ -129,6 +147,27 @@ class TestFlagVersionSync(BaseTest):assert entry.user is Noneassert entry.is_system is True+ def test_a_flag_in_another_config_format_is_skipped_by_the_cohort_walk(self):+ edited = self._create_cohort("edited", _person_filters("[email protected]"))+ flag_direct = self._create_flag("direct", edited.pk)+ other_format = FeatureFlag.objects.create(+ team=self.team,+ key="other-format",+ created_by=self.user,+ filters=_other_format_filters({"key": "id", "type": "cohort", "value": edited.pk}),+ )++ with capture_logs() as logs:+ edited.filters = _person_filters("[email protected]")+ edited.save()++ flag_direct.refresh_from_db()+ other_format.refresh_from_db()+ assert flag_direct.version == 2+ assert other_format.version == 1+ assert _updated_entries(other_format) == []+ assert [log for log in logs if log["event"] == "flag_version_sync_cohort_expansion_failed"] == []+def test_flag_history_entry_attributes_the_cohort_editor(self):cohort = self._create_cohort("cohort", _person_filters("[email protected]"))flag = self._create_flag("flag", cohort.pk)@@ -277,6 +316,26 @@ class TestFlagDependencyVersionSync(BaseTest):transitive = self._create_flag("transitive", _flag_dependency_filters(dependent.pk))return base, dependent, transitive+ def test_a_flag_in_another_config_format_is_skipped_by_the_dependency_walk(self):+ base, dependent, _transitive = self._create_chain()+ other_format = self._create_flag(+ "other-format",+ _other_format_filters(+ {"key": str(base.pk), "type": "flag", "operator": "flag_evaluates_to", "value": True}+ ),+ )++ with capture_logs() as logs:+ base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}+ base.save()++ dependent.refresh_from_db()+ other_format.refresh_from_db()+ assert dependent.version == 2+ assert other_format.version == 1+ assert _updated_entries(other_format) == []+ assert [log for log in logs if log["event"] == "flag_version_sync_dependency_parse_failed"] == []+def test_flag_definition_change_bumps_versions_of_flags_depending_on_it(self):base, dependent, transitive = self._create_chain()# dependent also depends on transitive, so the walk revisits an already-bumpeddiff --git a/products/feature_flags/backend/test/test_ownership.py b/products/feature_flags/backend/test/test_ownership.pyindex c96e200d3c8f..38ad791ce358 100644--- a/products/feature_flags/backend/test/test_ownership.py+++ b/products/feature_flags/backend/test/test_ownership.py@@ -72,6 +72,16 @@ class TestFlagOwnership(APIBaseTest):assert "already belongs to an experiment" in str(cm.exception)+ def test_guard_rejects_a_flag_in_another_config_format(self) -> None:+ flag = self._flag("other-format")+ flag.filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+ flag.save()++ with self.assertRaises(serializers.ValidationError) as cm:+ assert_flag_available_for(flag, product=FLAG_OWNER_SURVEY)++ assert "configuration format that a survey cannot use yet" in str(cm.exception)+def test_guard_allows_a_free_flag(self) -> None:assert_flag_available_for(self._flag("free"), product=FLAG_OWNER_SURVEY)@@ -96,6 +106,23 @@ class TestSurveyFlagAdoptionGuard(APIBaseTest):assert response.status_code == 400, response.json()assert "already belongs to an experiment" in str(response.json())+ def test_survey_cannot_adopt_a_flag_in_another_config_format(self) -> None:+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="other-format",+ created_by=self.user,+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={"name": "poacher", "type": "popover", "targeting_flag_id": flag.id},+ format="json",+ )++ assert response.status_code == 400, response.json()+ assert "configuration format" in str(response.json())+def test_survey_cannot_be_repointed_at_a_flag_another_product_owns(self) -> None:created = self.client.post(f"/api/projects/{self.team.id}/surveys/",diff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex 5620a400b8b1..3f2a63b72875 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -43,6 +43,7 @@ from products.access_control.backend.presentation.access_control import AccessCofrom products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerfrom products.feature_flags.backend.facade.api import create_flag, set_flag_active, update_flag+from products.feature_flags.backend.facade.config import ConfigFormatErrorfrom products.product_tours.backend.constants import ProductTourEventName, ProductTourPersonPropertiesfrom products.product_tours.backend.generate_tour_content import ContentGenerationResult, generate_with_geminifrom products.product_tours.backend.models import ProductTour@@ -252,7 +253,12 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):conditions = content.get("conditions") or {}linked_flag_variant = conditions.get("linkedFlagVariant")if linked_flag_variant and linked_flag and linked_flag_variant != "any":- available_variants = [variant["key"] for variant in linked_flag.variants]+ try:+ available_variants = [variant["key"] for variant in linked_flag.variants]+ except ConfigFormatError:+ raise serializers.ValidationError(+ "linkedFlagVariant cannot be used with this feature flag's configuration format"+ )if linked_flag_variant not in available_variants:if available_variants:raise serializers.ValidationError(diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex e3f18bc19833..dba300eb6438 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -1062,6 +1062,27 @@ class TestProductTourLinkedFlagValidation(APIBaseTest):if error_substring:assert error_substring in str(response.json())+ def test_linked_flag_variant_rejects_a_flag_in_another_config_format(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="other-format",+ created_by=self.user,+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/product_tours/",+ data={+ "name": "Tour",+ "linked_flag_id": flag.id,+ "content": {"steps": [], "conditions": {"linkedFlagVariant": "control"}},+ },+ format="json",+ )++ assert response.status_code == 400, response.json()+ assert "configuration format" in str(response.json())+def test_linked_flag_variant_requires_linked_flag_id(self):response = self.client.post(f"/api/projects/{self.team.id}/product_tours/",diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 1014ed9bf896..8d535519ac21 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -74,6 +74,7 @@ from products.feature_flags.backend.api.feature_flag import (MinimalFeatureFlagSerializer,assert_feature_flag_write_scope,)+from products.feature_flags.backend.facade.config import ConfigFormatErrorfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.ownership import FLAG_OWNER_SURVEY, assert_flag_available_forfrom products.product_analytics.backend.facade.models import Insight@@ -1544,8 +1545,12 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):conditions = data.get("conditions") or {}linked_flag_variant = conditions.get("linkedFlagVariant")if linked_flag_variant and linked_flag and linked_flag_variant != "any":- # Get available variants from the linked feature flag- available_variants = [variant["key"] for variant in linked_flag.variants]+ try:+ available_variants = [variant["key"] for variant in linked_flag.variants]+ except ConfigFormatError:+ raise serializers.ValidationError(+ "linkedFlagVariant cannot be used with this feature flag's configuration format"+ )if linked_flag_variant not in available_variants:if available_variants:raise serializers.ValidationError(diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex ad62ce016920..f1c7aad282ac 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -6031,6 +6031,37 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):data = response.json()self.assertEqual(data["stats"]["survey sent"]["total_count"], 0)+ def test_linked_flag_in_another_config_format_links_but_cannot_pick_a_variant(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="other-format",+ created_by=self.user,+ filters={"version": 2, "return_type": "boolean", "default_value": False, "rules": []},+ )+ questions = [{"type": "open", "question": "How is it?"}]++ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Variant Survey",+ "type": "popover",+ "linked_flag_id": flag.id,+ "conditions": {"linkedFlagVariant": "control"},+ "questions": questions,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "configuration format" in response.json()["detail"]++ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={"name": "Linked Survey", "type": "popover", "linked_flag_id": flag.id, "questions": questions},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["linked_flag"]["id"] == flag.id+def test_create_survey_with_valid_linked_flag_variant(self):"""Test creating a survey with a valid linkedFlagVariant"""# Create a multivariate feature flag