: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 recoverable filter violations found by audit (#73349)
Patricio8b939070f200
diff --git a/products/feature_flags/backend/migrations/0011_clean_flag_filters_recoverable_violations.py b/products/feature_flags/backend/migrations/0011_clean_flag_filters_recoverable_violations.pynew file mode 100644index 000000000000..65b6e885db85--- /dev/null+++ b/products/feature_flags/backend/migrations/0011_clean_flag_filters_recoverable_violations.py@@ -0,0 +1,193 @@+import json+import math++from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++BATCH_SIZE = 500++# Operators written by external tools that have an unambiguous canonical equivalent.+# Unknown operator strings are left untouched: the audit keeps reporting them until+# they are mapped here or fixed by hand.+OPERATOR_TYPO_MAP = {+ "contains": "icontains",+ "matches regex": "regex",+ "does not equal": "is_not",+ "is_in": "exact",+}++# Operators whose value must be a string; plain numbers are stringified (the+# evaluators compare stringified values anyway).+# Deliberately frozen copy of filters_validation.STRING_VALUE_OPERATORS (as is the+# in/not_in-on-non-cohort rule below): migrations must stay self-contained while app+# code evolves. If the canonical definitions change, reconcile by hand.+STRING_VALUE_OPERATORS = frozenset({"regex", "not_regex", "icontains", "not_icontains", "gt", "gte", "lt", "lte"})+++def _reject_json_constant(value: str) -> None:+ # json.loads accepts NaN/Infinity/-Infinity by default; raising here makes them+ # count as non-strict JSON so those payloads get re-encoded as JSON strings.+ raise ValueError(f"Non-strict JSON constant: {value}")+++def _is_strict_json(value: str) -> bool:+ try:+ json.loads(value, parse_constant=_reject_json_constant)+ return True+ except ValueError:+ return False+++def _clean_filters(filters: dict) -> tuple[dict, set[str]]:+ """Idempotent transform fixing the recoverable-violation shapes from the #50084 audit.+ Returns (new_filters, rules_applied); empty set means the flag is untouched."""+ rules: set[str] = set()+ new_filters = dict(filters)++ # Payload values that are strings but not strict JSON become JSON-encoded strings.+ # SDKs that parse-with-fallback return the same value either way; strict parsers stop failing.+ payloads = new_filters.get("payloads")+ if isinstance(payloads, dict):+ new_payloads = {}+ for key, value in payloads.items():+ if isinstance(value, str) and not _is_strict_json(value):+ new_payloads[key] = json.dumps(value)+ rules.add("payload_not_json")+ else:+ new_payloads[key] = value+ if "payload_not_json" in rules:+ new_filters["payloads"] = new_payloads++ # Re-apply the 0007 cleanup: malformed multivariate means the flag is boolean.+ # The API still accepts this shape until enforcement ships, so drift reappears.+ multivariate = new_filters.get("multivariate")+ if multivariate is not None:+ variants = multivariate.get("variants") if isinstance(multivariate, dict) else None+ if not isinstance(variants, list) or len(variants) == 0:+ new_filters["multivariate"] = None+ rules.add("multivariate_empty")+ payloads = new_filters.get("payloads")+ if isinstance(payloads, dict) and any(key != "true" for key in payloads):+ new_filters["payloads"] = {key: value for key, value in payloads.items() if key == "true"}++ groups = new_filters.get("groups")+ if isinstance(groups, list):+ variant_keys = {+ variant.get("key")+ for variant in (new_filters.get("multivariate") or {}).get("variants", [])+ if isinstance(variant, dict)+ }+ new_groups = []+ for group in groups:+ if not isinstance(group, dict):+ new_groups.append(group)+ continue+ new_group = dict(group)++ # Numeric-string rollout percentages become floats.+ rollout = new_group.get("rollout_percentage")+ if isinstance(rollout, str):+ try:+ parsed = float(rollout)+ except ValueError:+ parsed = None+ if parsed is not None and math.isfinite(parsed) and 0 <= parsed <= 100:+ new_group["rollout_percentage"] = parsed+ rules.add("rollout_percentage_string")++ # Variant overrides that reference no existing variant fall back to the+ # computed variant, same as 0007.+ if new_group.get("variant") and new_group["variant"] not in variant_keys:+ new_group["variant"] = None+ rules.add("dangling_variant_override")++ properties = new_group.get("properties")+ if isinstance(properties, list):+ new_properties = []+ for prop in properties:+ if not isinstance(prop, dict):+ new_properties.append(prop)+ continue+ new_prop = dict(prop)+ operator = new_prop.get("operator")++ # in/not_in outside cohorts hard-errors in the Rust matcher;+ # exact/is_not with the same value is the intended semantics.+ if operator in ("in", "not_in") and new_prop.get("type") != "cohort":+ new_prop["operator"] = "exact" if operator == "in" else "is_not"+ rules.add("in_not_in_non_cohort")+ elif isinstance(operator, str) and operator in OPERATOR_TYPO_MAP:+ new_prop["operator"] = OPERATOR_TYPO_MAP[operator]+ rules.add("operator_typo")++ if new_prop.get("operator") in STRING_VALUE_OPERATORS:+ value = new_prop.get("value")+ if isinstance(value, int | float) and not isinstance(value, bool):+ new_prop["value"] = str(value)+ rules.add("non_string_value")++ new_properties.append(new_prop)+ new_group["properties"] = new_properties+ new_groups.append(new_group)+ new_filters["groups"] = new_groups++ return new_filters, rules+++def clean_flag_filters_recoverable_violations(apps, schema_editor):+ """One-time cleanup of the recoverable violations found by audit_flag_filters (#50084).+ Violations live in nested arrays that jsonb prefilters can't select cheaply, so this+ scans all flags read-only and writes only the ~0.2% that change. Soft-deleted flags+ included, so a restore can't resurrect a violation."""+ FeatureFlag = apps.get_model("feature_flags", "FeatureFlag")++ total = 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+ # regardless of how the connection is pooled.+ last_id = 0+ while True:+ # _base_manager: the default manager excludes soft-deleted flags, also inside bulk_update.+ rows = list(+ FeatureFlag._base_manager.filter(id__gt=last_id)+ .exclude(filters=None)+ .order_by("id")+ .only("id", "filters")[:BATCH_SIZE]+ )+ if not rows:+ break+ last_id = rows[-1].id++ to_update = []+ for flag in rows:+ if not isinstance(flag.filters, dict):+ continue+ new_filters, rules = _clean_filters(flag.filters)+ if not rules:+ continue+ for rule in rules:+ rule_counts[rule] = rule_counts.get(rule, 0) + 1+ flag.filters = new_filters+ to_update.append(flag)++ if to_update:+ FeatureFlag._base_manager.bulk_update(to_update, ["filters"])+ total += len(to_update)++ logger.info("cleaned_flag_filters_recoverable_violations", updated_rows=total, **rule_counts)+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0010_remove_featureflag_performed_rollback_and_more"),+ ]++ operations = [+ migrations.RunPython(clean_flag_filters_recoverable_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 b89a9015f206..6af005e44eac 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0010_remove_featureflag_performed_rollback_and_more+0011_clean_flag_filters_recoverable_violationsdiff --git a/products/feature_flags/backend/test/test_migration_0011_clean_filters.py b/products/feature_flags/backend/test/test_migration_0011_clean_filters.pynew file mode 100644index 000000000000..15e85ae243ca--- /dev/null+++ b/products/feature_flags/backend/test/test_migration_0011_clean_filters.py@@ -0,0 +1,203 @@+from importlib import import_module+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized++from products.feature_flags.backend.filters_validation import collect_filters_violations++_migration = import_module("products.feature_flags.backend.migrations.0011_clean_flag_filters_recoverable_violations")+_clean_filters = _migration._clean_filters++# (name, dirty, expected, expected_rules, audit_clean_after)+# audit_clean_after is False for cases that deliberately leave unrecoverable+# violations in place (unknown operators, junk rollout strings, bool values).+CASES: list[tuple[str, dict[str, Any], dict[str, Any] | None, set[str], bool]] = [+ (+ "payload_raw_string_reencoded_valid_json_untouched",+ {+ "groups": [],+ "multivariate": {+ "variants": [{"key": "v1", "rollout_percentage": 50.0}, {"key": "v2", "rollout_percentage": 50.0}]+ },+ "payloads": {"v1": "hello world", "v2": '{"a": 1}'},+ },+ {+ "groups": [],+ "multivariate": {+ "variants": [{"key": "v1", "rollout_percentage": 50.0}, {"key": "v2", "rollout_percentage": 50.0}]+ },+ "payloads": {"v1": '"hello world"', "v2": '{"a": 1}'},+ },+ {"payload_not_json"},+ True,+ ),+ (+ "payload_nan_token_reencoded_as_string",+ {"groups": [], "payloads": {"true": "NaN"}},+ {"groups": [], "payloads": {"true": '"NaN"'}},+ {"payload_not_json"},+ True,+ ),+ (+ "in_not_in_remapped_on_person",+ {+ "groups": [+ {+ "properties": [+ {"key": "email", "type": "person", "operator": "in", "value": ["a", "b"]},+ {"key": "plan", "type": "person", "operator": "not_in", "value": ["x"]},+ ]+ }+ ]+ },+ {+ "groups": [+ {+ "properties": [+ {"key": "email", "type": "person", "operator": "exact", "value": ["a", "b"]},+ {"key": "plan", "type": "person", "operator": "is_not", "value": ["x"]},+ ]+ }+ ]+ },+ {"in_not_in_non_cohort"},+ True,+ ),+ (+ "cohort_in_operator_left_untouched",+ {"groups": [{"properties": [{"key": "id", "type": "cohort", "operator": "in", "value": 42}]}]},+ None,+ set(),+ True,+ ),+ (+ "operator_typos_mapped_unknown_left",+ {+ "groups": [+ {+ "properties": [+ {"key": "k", "type": "person", "operator": "contains", "value": "x"},+ {"key": "k2", "type": "person", "operator": "matches regex", "value": "^a"},+ {"key": "k3", "type": "person", "operator": "is_contained_within", "value": "y"},+ ]+ }+ ]+ },+ {+ "groups": [+ {+ "properties": [+ {"key": "k", "type": "person", "operator": "icontains", "value": "x"},+ {"key": "k2", "type": "person", "operator": "regex", "value": "^a"},+ {"key": "k3", "type": "person", "operator": "is_contained_within", "value": "y"},+ ]+ }+ ]+ },+ {"operator_typo"},+ False,+ ),+ (+ "numeric_string_rollout_coerced_junk_and_out_of_range_left",+ {"groups": [{"rollout_percentage": "50"}, {"rollout_percentage": "abc"}, {"rollout_percentage": "150"}]},+ {"groups": [{"rollout_percentage": 50.0}, {"rollout_percentage": "abc"}, {"rollout_percentage": "150"}]},+ {"rollout_percentage_string"},+ False,+ ),+ (+ "dangling_variant_override_nulled_valid_kept",+ {+ "groups": [{"variant": "ghost"}, {"variant": "real"}],+ "multivariate": {"variants": [{"key": "real", "rollout_percentage": 100}]},+ },+ {+ "groups": [{"variant": None}, {"variant": "real"}],+ "multivariate": {"variants": [{"key": "real", "rollout_percentage": 100}]},+ },+ {"dangling_variant_override"},+ True,+ ),+ (+ "numeric_value_stringified_bool_left",+ {+ "groups": [+ {+ "properties": [+ {"key": "v", "type": "person", "operator": "gt", "value": 5},+ {"key": "b", "type": "person", "operator": "gt", "value": True},+ ]+ }+ ]+ },+ {+ "groups": [+ {+ "properties": [+ {"key": "v", "type": "person", "operator": "gt", "value": "5"},+ {"key": "b", "type": "person", "operator": "gt", "value": True},+ ]+ }+ ]+ },+ {"non_string_value"},+ False,+ ),+ (+ "empty_multivariate_nulled_with_override_and_payload_keys",+ {+ "groups": [{"variant": "control"}],+ "multivariate": {"variants": []},+ "payloads": {"true": "1", "control": "2"},+ },+ {"groups": [{"variant": None}], "multivariate": None, "payloads": {"true": "1"}},+ {"multivariate_empty", "dangling_variant_override"},+ True,+ ),+ (+ "typo_remap_chains_into_stringification",+ {"groups": [{"properties": [{"key": "n", "type": "person", "operator": "contains", "value": 7}]}]},+ {"groups": [{"properties": [{"key": "n", "type": "person", "operator": "icontains", "value": "7"}]}]},+ {"operator_typo", "non_string_value"},+ True,+ ),+ (+ "fully_valid_flag_untouched",+ {+ "groups": [+ {+ "properties": [{"key": "email", "type": "person", "operator": "icontains", "value": "@x.com"}],+ "rollout_percentage": 50,+ "variant": "a",+ }+ ],+ "multivariate": {"variants": [{"key": "a", "rollout_percentage": 100.0}]},+ "payloads": {"a": '"payload"'},+ "aggregation_group_type_index": None,+ },+ None,+ set(),+ True,+ ),+]+++class TestCleanFiltersTransform(SimpleTestCase):+ @parameterized.expand([(name, dirty, expected, rules) for name, dirty, expected, rules, _ in CASES])+ def test_transform(self, _name: str, dirty: dict, expected: dict | None, expected_rules: set[str]) -> None:+ cleaned, rules = _clean_filters(dirty)+ assert rules == expected_rules+ assert cleaned == (dirty if expected is None else expected)++ @parameterized.expand([(name, dirty) for name, dirty, *_ in CASES])+ def test_transform_is_idempotent(self, _name: str, dirty: dict) -> None:+ cleaned, _ = _clean_filters(dirty)+ second, second_rules = _clean_filters(cleaned)+ assert second == cleaned+ assert second_rules == set()++ @parameterized.expand([(name, dirty) for name, dirty, _, _, audit_clean in CASES if audit_clean])+ def test_recoverable_output_passes_the_audit_rule_set(self, _name: str, dirty: dict) -> None:+ cleaned, _ = _clean_filters(dirty)+ assert collect_filters_violations(cleaned) == []