: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): clean the flag filter violations no evaluator can see (#90272)
Patricio9e2c00c5268d
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex 70eb2c7d47d8..e26f971a6adf 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -24,3 +24,8 @@ tasks.0110_backfill_taskrun_origin_product# (the partition list is only known at runtime), which the type-based check can't see.warehouse_sources_queue.0008_sourcebatch_supersededwarehouse_sources_queue.0009_sourcebatch_job_id_idx+# Scans every flag row but writes only the few hundred that need cleaning, each as its own+# compare-and-swap. Atomic would hold one transaction open across the whole scan, pinning xmin+# on the table the flags API writes to. Re-running is a no-op: the transform is idempotent and+# each swap only matches rows still holding the pre-clean value.+feature_flags.0014_clean_flag_filters_inert_violationsdiff --git a/products/feature_flags/backend/migrations/0014_clean_flag_filters_inert_violations.py b/products/feature_flags/backend/migrations/0014_clean_flag_filters_inert_violations.pynew file mode 100644index 000000000000..541d64705f72--- /dev/null+++ b/products/feature_flags/backend/migrations/0014_clean_flag_filters_inert_violations.py@@ -0,0 +1,160 @@+from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++BATCH_SIZE = 500+++def _variant_keys(filters: dict) -> set[str]:+ """Variant keys a stored payload or override could legitimately point at.++ Non-string keys are skipped: a payload key always arrives as a JSON string, so it could+ never resolve to one anyway."""+ multivariate = filters.get("multivariate")+ variants = multivariate.get("variants") if isinstance(multivariate, dict) else None+ if not isinstance(variants, list):+ return set()+ keys = set()+ for variant in variants:+ if not isinstance(variant, dict):+ continue+ key = variant.get("key")+ if isinstance(key, str):+ keys.add(key)+ return keys+++# Payload keys the evaluator resolves beyond the variant keys themselves: a boolean result+# looks up "true"/"false", and a user in a holdout gets the synthesised `holdout-{id}` variant.+BOOLEAN_PAYLOAD_KEYS = frozenset({"true", "false"})+HOLDOUT_PAYLOAD_KEY_PREFIX = "holdout-"+++def _payload_key_is_resolvable(key: str, variant_keys: set[str]) -> bool:+ # Pinned by test_migration_0014_clean_inert_violations; the holdout and boolean keys are the+ # ones a variant-key-only check silently deletes.+ return key in variant_keys or key in BOOLEAN_PAYLOAD_KEYS or key.startswith(HOLDOUT_PAYLOAD_KEY_PREFIX)+++def _clean_filters(filters: dict) -> tuple[dict, set[str]]:+ """Idempotent transform for the #50084 violations that no evaluator can observe.++ Every rule here is a no-op at runtime, so the stored value changes and flag behaviour does+ not. Violations that change what a flag does are deliberately absent: rollout sums, property+ types that don't suit the condition set's aggregation, and flag dependencies carrying the+ wrong operator, which the evaluator treats as an unmatchable condition rather than ignoring.+ Returns (new_filters, rules_applied); an empty set means the flag is untouched."""+ rules: set[str] = set()+ new_filters = dict(filters)+ variant_keys = _variant_keys(new_filters)++ # A variant override the evaluator can't resolve is already ignored: it falls back to the+ # computed variant (get_matching_variant in rust/feature-flags/src/flags/flag_matching.rs).+ groups = new_filters.get("groups")+ if isinstance(groups, list):+ new_groups = []+ for group in groups:+ if not isinstance(group, dict):+ new_groups.append(group)+ continue+ new_group = dict(group)++ variant = new_group.get("variant")+ if variant and variant not in variant_keys:+ new_group["variant"] = None+ rules.add("group_variant_not_a_variant")++ new_groups.append(new_group)+ new_filters["groups"] = new_groups++ # A payload under a key no evaluation can resolve is unreachable, so dropping it is invisible.+ payloads = new_filters.get("payloads")+ if isinstance(payloads, dict):+ if not new_filters.get("multivariate"):+ rule = "payload_key_not_true"+ kept = {k: v for k, v in payloads.items() if _payload_key_is_resolvable(k, set())}+ elif variant_keys:+ rule = "payload_key_not_a_variant"+ kept = {k: v for k, v in payloads.items() if _payload_key_is_resolvable(k, variant_keys)}+ else:+ # No variant list we could read, so every payload would look orphaned. A flag whose+ # variants are missing or malformed belongs to the multivariate_empty rule in 0011.+ rule, kept = "", payloads+ if rule and len(kept) != len(payloads):+ new_filters["payloads"] = kept+ rules.add(rule)++ return new_filters, rules+++def clean_flag_filters_inert_violations(apps, schema_editor):+ """One-time cleanup of the #50084 violations that can be repaired without a customer (see+ the per-rule rollout in the issue). Violations live in nested arrays that jsonb prefilters+ can't select cheaply, so this scans all flags read-only and writes only the ones that change.+ Soft-deleted and inactive flags included: their filters are blanked in the cached payload,+ but restoring or re-enabling a flag would put the stored value straight back in play."""+ FeatureFlag = apps.get_model("feature_flags", "FeatureFlag")++ updated_rows = 0+ skipped_concurrent = 0+ rule_counts: dict[str, int] = {}++ # Keyset pagination instead of .iterator(): server-side cursors are disabled when migrations+ # run through pgbouncer (DISABLE_SERVER_SIDE_CURSORS), which would make .iterator() buffer the+ # whole table client-side. id-range batches are memory-bounded however the connection is pooled.+ last_id = 0+ while True:+ # _base_manager documents that soft-deleted rows are in scope (a historical model's+ # manager is plain anyway). Encrypted flags are skipped entirely: every payload key is+ # ciphertext, so dropping one destroys a secret; exclude keeps legacy NULL rows in scope.+ rows = list(+ FeatureFlag._base_manager.filter(id__gt=last_id)+ .exclude(has_encrypted_payloads=True)+ .order_by("id")+ .only("id", "filters")[:BATCH_SIZE]+ )+ if not rows:+ break+ last_id = rows[-1].id++ for flag in rows:+ if not isinstance(flag.filters, dict):+ continue+ new_filters, rules = _clean_filters(flag.filters)+ if not rules:+ continue+ # Compare-and-swap on the value we read: a flag edited between the batch select and+ # this write keeps the newer filters instead of being reverted to our snapshot. Only+ # a few hundred rows change fleet-wide, so per-row writes cost little.+ written = FeatureFlag._base_manager.filter(id=flag.id, filters=flag.filters).update(filters=new_filters)+ if not written:+ skipped_concurrent += 1+ continue+ for rule in rules:+ rule_counts[rule] = rule_counts.get(rule, 0) + 1+ updated_rows += 1++ logger.info(+ "cleaned_flag_filters_inert_violations",+ updated_rows=updated_rows,+ skipped_concurrent=skipped_concurrent,+ **rule_counts,+ )+++class Migration(migrations.Migration):+ # Non-atomic so each row's UPDATE commits as it goes. The default wrapping transaction would+ # stay open across the whole scan, holding an xmin autovacuum cannot advance past on the table+ # the flags API writes to. Safe to resume: every compare-and-swap is independently correct and+ # the transform is idempotent, so a partial run leaves a consistent table.+ atomic = False++ dependencies = [+ ("feature_flags", "0013_narrow_whole_rollout_percentages"),+ ]++ operations = [+ migrations.RunPython(clean_flag_filters_inert_violations, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txtindex 795c798f667c..44b69ed1f3ac 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0013_narrow_whole_rollout_percentages+0014_clean_flag_filters_inert_violationsdiff --git a/products/feature_flags/backend/test/test_migration_0014_clean_inert_violations.py b/products/feature_flags/backend/test/test_migration_0014_clean_inert_violations.pynew file mode 100644index 000000000000..9a1d7e9b079f--- /dev/null+++ b/products/feature_flags/backend/test/test_migration_0014_clean_inert_violations.py@@ -0,0 +1,172 @@+from typing import Any++from posthog.test.base import TestMigrations++MULTIVARIATE = {+ "variants": [+ {"key": "control", "name": "", "rollout_percentage": 50},+ {"key": "test", "name": "", "rollout_percentage": 50},+ ]+}+++def group(**overrides: Any) -> dict:+ return {"properties": [], "rollout_percentage": 100, "variant": None, **overrides}+++class CleanInertFilterViolationsMigrationTest(TestMigrations):+ migrate_from = "0013_narrow_whole_rollout_percentages"+ migrate_to = "0014_clean_flag_filters_inert_violations"++ CLASS_DATA_LEVEL_SETUP = False++ @property+ def app(self) -> str:+ return "feature_flags"++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")+ FeatureFlag = apps.get_model("feature_flags", "FeatureFlag")++ org = Organization.objects.create(name="Test Organization")+ project = Project.objects.create(id=999995, organization=org, name="Test Project")+ team = Team.objects.create(organization=org, project=project, name="Test Team")++ def make_flag(key: str, filters: dict, **kwargs: Any) -> Any:+ return FeatureFlag.objects.create(team=team, created_by=None, key=key, filters=filters, **kwargs)++ self.orphan_payload_id = make_flag(+ "orphan-payload",+ {"groups": [group()], "multivariate": MULTIVARIATE, "payloads": {"control": "1", "ghost": "2"}},+ ).id+ self.resolvable_payloads_id = make_flag(+ "resolvable-payloads",+ {+ "groups": [group()],+ "multivariate": MULTIVARIATE,+ "payloads": {"control": "1", "false": "2", "holdout-7": "3", "ghost": "4"},+ },+ ).id+ self.boolean_payloads_id = make_flag(+ "boolean-payloads",+ {"groups": [group()], "payloads": {"true": "1", "false": "2", "holdout-9": "3", "control": "4"}},+ ).id+ self.dangling_variant_id = make_flag(+ "dangling-variant",+ {"groups": [group(variant="ghost"), group(variant="control")], "multivariate": MULTIVARIATE},+ ).id+ self.already_clean_id = make_flag(+ "already-clean",+ {"groups": [group(variant="control")], "multivariate": MULTIVARIATE, "payloads": {"control": "1"}},+ ).id+ self.soft_deleted_id = make_flag(+ "soft-deleted",+ {"groups": [group(variant="ghost")], "multivariate": MULTIVARIATE},+ deleted=True,+ ).id+ self.inactive_id = make_flag(+ "inactive",+ {"groups": [group(variant="ghost")], "multivariate": MULTIVARIATE},+ active=False,+ ).id+ # Rules this migration deliberately does not own.+ self.non_inert_id = make_flag(+ "non-inert",+ {+ "groups": [group(properties=[{"key": "1", "type": "flag", "value": True, "operator": "exact"}])],+ "multivariate": {+ "variants": [+ {"key": "a", "name": "", "rollout_percentage": 40},+ {"key": "b", "name": "", "rollout_percentage": 40},+ {"key": "c", "name": "", "rollout_percentage": 40},+ ]+ },+ },+ ).id+ # Every payload key on an encrypted flag is ciphertext, so pruning one destroys a secret.+ self.encrypted_id = make_flag(+ "encrypted",+ {"groups": [group()], "payloads": {"true": "cipher-1", "staging": "cipher-2"}},+ has_encrypted_payloads=True,+ ).id+ self.encrypted_legacy_null_id = make_flag(+ "encrypted-legacy-null",+ {+ "groups": [group(variant="ghost")],+ "multivariate": MULTIVARIATE,+ "payloads": {"control": "1", "ghost": "2"},+ },+ has_encrypted_payloads=None,+ ).id++ # Shapes the scan must skip rather than raise on, which would abort the whole migration.+ self.junk_ids = [+ make_flag("junk-groups", {"groups": {}}).id,+ make_flag("junk-group-entry", {"groups": ["nope"], "multivariate": MULTIVARIATE}).id,+ make_flag(+ "junk-multivariate-list", {"groups": [group()], "multivariate": ["nope"], "payloads": {"x": "1"}}+ ).id,+ make_flag(+ "junk-multivariate-str", {"groups": [group()], "multivariate": "nope", "payloads": {"x": "1"}}+ ).id,+ make_flag("junk-payloads", {"groups": [group()], "payloads": []}).id,+ ]++ def _filters(self, flag_id: int) -> dict:+ assert self.apps is not None+ FeatureFlag = self.apps.get_model("feature_flags", "FeatureFlag")+ return FeatureFlag.objects.get(id=flag_id).filters++ def test_drops_payload_keys_no_evaluation_can_resolve(self) -> None:+ assert self._filters(self.orphan_payload_id)["payloads"] == {"control": "1"}++ def test_keeps_payload_keys_the_evaluator_resolves(self) -> None:+ # "false" is reached by a boolean result and "holdout-N" by the synthesised holdout variant.+ assert self._filters(self.resolvable_payloads_id)["payloads"] == {+ "control": "1",+ "false": "2",+ "holdout-7": "3",+ }+ assert self._filters(self.boolean_payloads_id)["payloads"] == {+ "true": "1",+ "false": "2",+ "holdout-9": "3",+ }++ def test_clears_only_dangling_variant_overrides(self) -> None:+ groups = self._filters(self.dangling_variant_id)["groups"]+ assert groups[0]["variant"] is None+ assert groups[1]["variant"] == "control"++ def test_covers_soft_deleted_and_inactive_flags(self) -> None:+ assert self._filters(self.soft_deleted_id)["groups"][0]["variant"] is None+ assert self._filters(self.inactive_id)["groups"][0]["variant"] is None++ def test_leaves_an_already_clean_flag_untouched(self) -> None:+ assert self._filters(self.already_clean_id) == {+ "groups": [group(variant="control")],+ "multivariate": MULTIVARIATE,+ "payloads": {"control": "1"},+ }++ def test_leaves_violations_it_does_not_own(self) -> None:+ filters = self._filters(self.non_inert_id)+ assert filters["groups"][0]["properties"][0]["operator"] == "exact"+ assert [variant["rollout_percentage"] for variant in filters["multivariate"]["variants"]] == [40, 40, 40]++ def test_leaves_encrypted_flags_alone(self) -> None:+ assert self._filters(self.encrypted_id)["payloads"] == {"true": "cipher-1", "staging": "cipher-2"}++ def test_still_cleans_flags_with_a_null_encrypted_marker(self) -> None:+ filters = self._filters(self.encrypted_legacy_null_id)+ assert filters["payloads"] == {"control": "1"}+ assert filters["groups"][0]["variant"] is None++ def test_skips_malformed_filters_without_raising(self) -> None:+ # Reaching any assertion here means the scan completed; these rows stay as they were.+ assert self._filters(self.junk_ids[0]) == {"groups": {}}+ assert self._filters(self.junk_ids[2])["payloads"] == {"x": "1"}+ assert self._filters(self.junk_ids[3])["payloads"] == {"x": "1"}+ assert self._filters(self.junk_ids[4])["payloads"] == []