Skip to content

: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.

chore(flags): count the filters round-trip divergences in the audit (#98614)

James Gille97b6cb3bc38
diff --git a/products/feature_flags/backend/management/commands/audit_flag_filters.py b/products/feature_flags/backend/management/commands/audit_flag_filters.py
index 8a9ab70299c5..ca385084eb90 100644
--- a/products/feature_flags/backend/management/commands/audit_flag_filters.py
+++ b/products/feature_flags/backend/management/commands/audit_flag_filters.py
@@ -8,24 +8,33 @@ time in FeatureFlagSerializer and are not audited.
Each flag costs a DRF serializer instantiation, so a full prod scan takes minutes, not
seconds — it's an offline command.
+
+A third section counts the `filters` round-trip divergences between the two flags-cache
+builders: shapes the Rust builder writes back narrower than the stored JSONB holds. They are
+never violations, because a clean violations run gates flipping enforcement on. Each count is
+reported over all stored flags and over the flags the verifier actually compares.
+DIVERGENCE_NOTE carries the operator-facing explanation.
"""
import re
import json
-from collections.abc import Iterator, Sequence
+from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
+from posthog.dataclasses import frozen
from posthog.models import Team
from products.feature_flags.backend.api.filters_schema import (
+ FEATURE_FLAG_OPERATOR_ALIASES,
FLAG_ID_CONTEXT_KEY,
UNKNOWN_KEYS_SINK_CONTEXT_KEY,
is_legacy_unknown_key,
)
from products.feature_flags.backend.filters_validation import Violation, collect_filters_violations
+from products.feature_flags.backend.flags_cache import _is_unevaluable
from products.feature_flags.backend.models.feature_flag import FeatureFlag
# Unknown keys come from user-controlled JSON, so the distinct-key space is unbounded; cap it
@@ -42,12 +51,30 @@ def _sanitize_for_console(text: str) -> str:
return _CONTROL_CHARS_RE.sub("�", text)
-def _iter_flag_rows(queryset: Any, *, limit: int, chunk_size: int = 500) -> Iterator[tuple[int, int, Any]]:
+@frozen
+class ScannedFlag:
+ id: int
+ team_id: int
+ filters: Any
+ active: bool
+ deleted: bool
+ has_encrypted_payloads: bool | None
+
+
+@frozen
+class Divergence:
+ shape_id: str
+ detail: str
+
+
+def _iter_flag_rows(queryset: Any, *, limit: int, chunk_size: int = 500) -> Iterator[ScannedFlag]:
# Keyset pagination instead of .iterator(): prod runs behind PgBouncer with server-side
# cursors disabled, so .iterator() buffers the entire result set client-side on execute
# and a full scan would hold every flag's filters JSON in memory at once. Repeated
# id-bounded LIMIT queries keep memory bounded on any connection.
- base = queryset.order_by("id").values_list("id", "team_id", "filters")
+ base = queryset.order_by("id").values_list(
+ "id", "team_id", "filters", "active", "deleted", "has_encrypted_payloads"
+ )
last_id, yielded = 0, 0
while True:
page = chunk_size if not limit else min(chunk_size, limit - yielded)
@@ -56,7 +83,15 @@ def _iter_flag_rows(queryset: Any, *, limit: int, chunk_size: int = 500) -> Iter
chunk = list(base.filter(id__gt=last_id)[:page])
if not chunk:
return
- yield from chunk
+ for row in chunk:
+ yield ScannedFlag(
+ id=row[0],
+ team_id=row[1],
+ filters=row[2],
+ active=row[3],
+ deleted=row[4],
+ has_encrypted_payloads=row[5],
+ )
yielded += len(chunk)
last_id = chunk[-1][0]
@@ -101,17 +136,181 @@ class UnknownKeyAggregator:
samples.append(flag_id)
+# MultivariateFlagOptions, MultivariateFlagVariant and Holdout
+# (rust/feature-flags/src/flags/flag_models.rs) are the only three Rust structs without
+# `#[serde(flatten)] extra`, so Rust drops every other key at these levels on cache write. Every
+# other level has `extra` and round-trips unknown keys unchanged. `description` on a variant is
+# dropped even though filters_schema.py declares and keeps it. A field added to one of these three
+# structs belongs here too, or this audit counts a divergence that no longer happens.
+RUST_MULTIVARIATE_FIELDS = frozenset({"variants"})
+RUST_VARIANT_FIELDS = frozenset({"key", "name", "rollout_percentage"})
+RUST_HOLDOUT_FIELDS = frozenset({"id", "exclusion_percentage"})
+
+DIVERGENCE_NUMERIC_PROPERTY_KEY = "roundtrip.numeric_property_key"
+DIVERGENCE_DROPPED_KEY = "roundtrip.dropped_key"
+DIVERGENCE_OPERATOR_ALIAS = "roundtrip.operator_alias"
+DIVERGENCE_ABSENT_GROUPS = "roundtrip.absent_groups"
+
+# Fixed set, so a shape that matches nothing still reports its zero.
+DIVERGENCE_SHAPES: tuple[str, ...] = (
+ DIVERGENCE_NUMERIC_PROPERTY_KEY,
+ DIVERGENCE_DROPPED_KEY,
+ DIVERGENCE_OPERATOR_ALIAS,
+ DIVERGENCE_ABSENT_GROUPS,
+)
+
+DIVERGENCE_NOTE = """\
+These are cache-write divergences, not enforcement violations, so they do not affect the
+clean-run gate above. The two builders differ in the bytes they write, not in what the flag
+resolves to for a user. The Python cache verifier reports the difference as a filters mismatch
+and repairs it on every pass.
+The second number counts only the flags whose stored filters the verifier compares. It leaves
+out a flag that is inactive or deleted, a flag with encrypted payloads, and a flag with a
+structural violation, because no cache entry holds the stored filters of any of those. Each
+sampled detail says which one applies.
+Size a verifier fix from the second number, and a stored-data rewrite from the first.\
+"""
+
+
+def _iter_divergences(filters: Any) -> Iterator[Divergence]:
+ """Yield one Divergence per round-trip divergence in one stored filters blob."""
+ # Every level is type-guarded because a blob Rust cannot deserialize at all is reported by
+ # collect_filters_violations, not counted here.
+ if not isinstance(filters, dict):
+ return
+ if "groups" not in filters:
+ yield Divergence(shape_id=DIVERGENCE_ABSENT_GROUPS, detail='no groups key, and Rust writes "groups": []')
+ # Only `groups` is typed on the Rust side. super_groups and holdout_groups reach the `extra`
+ # map as raw JSON, so their contents come back byte-identical.
+ groups = filters.get("groups")
+ if isinstance(groups, list):
+ for group_index, group in enumerate(groups):
+ if not isinstance(group, dict):
+ continue
+ properties = group.get("properties")
+ if not isinstance(properties, list):
+ continue
+ for property_index, property_filter in enumerate(properties):
+ if not isinstance(property_filter, dict):
+ continue
+ yield from _iter_property_divergences(
+ property_filter, f"groups[{group_index}].properties[{property_index}]"
+ )
+ multivariate = filters.get("multivariate")
+ if isinstance(multivariate, dict):
+ yield from _iter_dropped_keys(multivariate, RUST_MULTIVARIATE_FIELDS, "multivariate")
+ variants = multivariate.get("variants")
+ if isinstance(variants, list):
+ for variant_index, variant in enumerate(variants):
+ if isinstance(variant, dict):
+ yield from _iter_dropped_keys(
+ variant, RUST_VARIANT_FIELDS, f"multivariate.variants[{variant_index}]"
+ )
+ holdout = filters.get("holdout")
+ if isinstance(holdout, dict):
+ yield from _iter_dropped_keys(holdout, RUST_HOLDOUT_FIELDS, "holdout")
+
+
+def _iter_property_divergences(property_filter: dict[str, Any], path: str) -> Iterator[Divergence]:
+ key = property_filter.get("key")
+ # isinstance(True, int) is True in Python, and Rust's `deserialize_key` takes a string or a
+ # JSON number only, so a bool key fails deserialization instead of round-tripping narrowed.
+ if not isinstance(key, bool) and isinstance(key, int | float):
+ yield Divergence(
+ shape_id=DIVERGENCE_NUMERIC_PROPERTY_KEY, detail=f"{path}.key: the number {key} becomes a string"
+ )
+ operator = property_filter.get("operator")
+ if isinstance(operator, str) and operator in FEATURE_FLAG_OPERATOR_ALIASES:
+ canonical = FEATURE_FLAG_OPERATOR_ALIASES[operator]
+ yield Divergence(shape_id=DIVERGENCE_OPERATOR_ALIAS, detail=f"{path}.operator: {operator} becomes {canonical}")
+
+
+def _iter_dropped_keys(level: dict[str, Any], kept_by_rust: frozenset[str], path: str) -> Iterator[Divergence]:
+ # The verifier's _strip_null_values drops a null-valued key from the stored side too, so both
+ # sides come out equal even though Rust never wrote the key.
+ for key, value in level.items():
+ if key not in kept_by_rust and value is not None:
+ yield Divergence(shape_id=DIVERGENCE_DROPPED_KEY, detail=f"{path}.{key} is dropped")
+
+
+@frozen(frozen=False)
+class DivergenceReport:
+ shape_id: str
+ flags_affected: int = 0
+ # Only these can make the verifier report a mismatch. See _not_compared_reason.
+ compared_flags_affected: int = 0
+ sample_flag_ids: list[int] = field(default_factory=list)
+ sample_details: list[str] = field(default_factory=list)
+
+
+def _not_compared_reason(flag: ScannedFlag, *, structurally_valid: bool) -> str | None:
+ """Why the verifier never compares this flag's stored filters, or None when it does."""
+ # _is_unevaluable is the cache builders' own gate, so a change to what they blank cannot
+ # leave this count quietly wrong.
+ if _is_unevaluable({"active": flag.active, "deleted": flag.deleted}):
+ return "inactive or deleted"
+ # An encrypted-payload flag is served from /remote_config, and _get_feature_flags_for_teams_batch
+ # excludes it from the payload the verifier compares.
+ if flag.has_encrypted_payloads:
+ return "encrypted payloads"
+ # filters_schema.py mirrors the Rust field shapes, so a blob it rejects structurally is one
+ # Rust may fail to deserialize. Rust then writes no narrowed form to diverge from.
+ if not structurally_valid:
+ return "structural violation"
+ return None
+
+
+class RoundTripDivergenceAggregator:
+ """Counts flags per divergence shape, once per shape however often it recurs."""
+
+ def __init__(self, max_samples: int) -> None:
+ self.max_samples = max_samples
+ self.reports: dict[str, DivergenceReport] = {
+ shape_id: DivergenceReport(shape_id=shape_id) for shape_id in DIVERGENCE_SHAPES
+ }
+ self.flags_with_any_divergence = 0
+ self.compared_flags_with_any_divergence = 0
+
+ def record(self, *, flag: ScannedFlag, not_compared: str | None, found: Iterable[Divergence]) -> None:
+ counted: set[str] = set()
+ for divergence in found:
+ if divergence.shape_id in counted:
+ continue
+ counted.add(divergence.shape_id)
+ report = self.reports[divergence.shape_id]
+ report.flags_affected += 1
+ if not_compared is None:
+ report.compared_flags_affected += 1
+ if len(report.sample_flag_ids) < self.max_samples:
+ report.sample_flag_ids.append(flag.id)
+ # Naming the reason saves tracing a sample id back to find out why the verifier
+ # never reports it.
+ marker = "" if not_compared is None else f" [not compared: {not_compared}]"
+ report.sample_details.append(f"flag={flag.id} team={flag.team_id} {divergence.detail}{marker}")
+ if counted:
+ self.flags_with_any_divergence += 1
+ if not_compared is None:
+ self.compared_flags_with_any_divergence += 1
+
+
class Command(BaseCommand):
help = (
"Read-only audit of FeatureFlag.filters (all flags, soft-deleted included) against the "
"#50084 structural + cross-field rules. Reports violations grouped by rule; a clean run "
- "gates flipping enforcement on."
+ "gates flipping enforcement on. Also counts the filters round-trip divergences between "
+ "the Python and Rust cache builders, which are cache-write divergences rather than "
+ "enforcement violations and do not affect that gate. The report explains both counts."
)
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--json", action="store_true", help="Emit a machine-readable JSON report instead")
parser.add_argument("--limit", type=int, default=0, help="Max flags to scan (0 = all)")
- parser.add_argument("--samples", type=int, default=5, help="Sample flag ids to record per rule / unknown key")
+ parser.add_argument(
+ "--samples",
+ type=int,
+ default=5,
+ help="Sample flag ids to record per rule / unknown key / divergence shape",
+ )
parser.add_argument("--team-id", type=int, default=None, help="Restrict the scan to one team (debugging)")
def handle(self, *args: Any, **options: Any) -> None:
@@ -131,6 +330,7 @@ class Command(BaseCommand):
raise CommandError(f"Team {team_id} does not exist")
sink = UnknownKeyAggregator(max_samples=samples)
+ divergences = RoundTripDivergenceAggregator(max_samples=samples)
rule_reports: dict[str, RuleReport] = {}
scanned = 0
flags_with_violations = 0
@@ -146,11 +346,11 @@ class Command(BaseCommand):
# collect_filters_violations runs CROSS_FIELD_CHECKS, which deliberately excludes
# check_groups_non_empty_for_create: non-empty groups is a POST-only rule (#50084) —
# stored flags with empty groups are valid state and must never show up in this report.
- for flag_id, flag_team_id, filters in _iter_flag_rows(queryset, limit=limit):
+ for flag in _iter_flag_rows(queryset, limit=limit):
scanned += 1
try:
violations = collect_filters_violations(
- filters, context={UNKNOWN_KEYS_SINK_CONTEXT_KEY: sink, FLAG_ID_CONTEXT_KEY: flag_id}
+ flag.filters, context={UNKNOWN_KEYS_SINK_CONTEXT_KEY: sink, FLAG_ID_CONTEXT_KEY: flag.id}
)
except Exception as exc:
# The whole point of this command is surviving wild-west data: one flag whose
@@ -162,6 +362,14 @@ class Command(BaseCommand):
message=f"{type(exc).__name__}: {exc}",
)
]
+ divergences.record(
+ flag=flag,
+ not_compared=_not_compared_reason(
+ flag,
+ structurally_valid=not any(v.rule_id.startswith("structural.") for v in violations),
+ ),
+ found=_iter_divergences(flag.filters),
+ )
if not violations:
continue
flags_with_violations += 1
@@ -174,19 +382,24 @@ class Command(BaseCommand):
counted_rules.add(violation.rule_id)
report.flags_affected += 1
if len(report.sample_flag_ids) < samples:
- report.sample_flag_ids.append(flag_id)
+ report.sample_flag_ids.append(flag.id)
report.sample_details.append(
- f"flag={flag_id} team={flag_team_id} {violation.path}: {violation.message}"
+ f"flag={flag.id} team={flag.team_id} {violation.path}: {violation.message}"
)
reports = sorted(rule_reports.values(), key=lambda r: (-r.flags_affected, r.rule_id))
if options["json"]:
- self._emit_json(scanned, flags_with_violations, reports, sink)
+ self._emit_json(scanned, flags_with_violations, reports, sink, divergences)
else:
- self._emit_console(scanned, flags_with_violations, reports, sink)
+ self._emit_console(scanned, flags_with_violations, reports, sink, divergences)
def _emit_json(
- self, scanned: int, flags_with_violations: int, reports: list[RuleReport], sink: UnknownKeyAggregator
+ self,
+ scanned: int,
+ flags_with_violations: int,
+ reports: list[RuleReport],
+ sink: UnknownKeyAggregator,
+ divergences: RoundTripDivergenceAggregator,
) -> None:
payload = {
"scanned": scanned,
@@ -215,11 +428,29 @@ class Command(BaseCommand):
for (level, key), count in sorted(sink.flag_counts.items())
],
"untracked_unknown_keys": sink.untracked_keys,
+ "flags_with_roundtrip_divergences": divergences.flags_with_any_divergence,
+ "compared_flags_with_roundtrip_divergences": divergences.compared_flags_with_any_divergence,
+ "roundtrip_divergences": [
+ {
+ "shape_id": report.shape_id,
+ "flags_affected": report.flags_affected,
+ "compared_flags_affected": report.compared_flags_affected,
+ "sample_flag_ids": report.sample_flag_ids,
+ "sample_details": report.sample_details,
+ }
+ for report in divergences.reports.values()
+ ],
+ "roundtrip_divergences_note": DIVERGENCE_NOTE,
}
self.stdout.write(json.dumps(payload, indent=2))
def _emit_console(
- self, scanned: int, flags_with_violations: int, reports: list[RuleReport], sink: UnknownKeyAggregator
+ self,
+ scanned: int,
+ flags_with_violations: int,
+ reports: list[RuleReport],
+ sink: UnknownKeyAggregator,
+ divergences: RoundTripDivergenceAggregator,
) -> None:
clean = scanned - flags_with_violations
self.stdout.write(
@@ -258,3 +489,23 @@ class Command(BaseCommand):
f"{MAX_TRACKED_UNKNOWN_KEYS} distinct-key tracking cap"
)
)
+
+ self._emit_divergences_console(divergences)
+
+ def _emit_divergences_console(self, divergences: RoundTripDivergenceAggregator) -> None:
+ self.stdout.write("")
+ self.stdout.write(
+ f"Cache-write round-trip divergences ({divergences.flags_with_any_divergence} flags, "
+ f"{divergences.compared_flags_with_any_divergence} compared by the verifier):"
+ )
+ for report in sorted(divergences.reports.values(), key=lambda r: (-r.flags_affected, r.shape_id)):
+ ids = ", ".join(str(flag_id) for flag_id in report.sample_flag_ids)
+ self.stdout.write(
+ f" {report.shape_id:<30} {report.flags_affected} flags, "
+ f"{report.compared_flags_affected} compared sample ids: {ids}"
+ )
+ for detail in report.sample_details:
+ self.stdout.write(f" {_sanitize_for_console(detail)}")
+ if divergences.flags_with_any_divergence:
+ for line in DIVERGENCE_NOTE.splitlines():
+ self.stdout.write(f" {line}")
diff --git a/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py b/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py
index 5f3387e56c0b..ef55de97a43d 100644
--- a/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py
+++ b/products/feature_flags/backend/management/commands/test/test_audit_flag_filters.py
@@ -1,3 +1,4 @@
+import re
import json
from io import StringIO
from typing import Any
@@ -13,6 +14,13 @@ from parameterized import parameterized
from posthog.models import Team
from products.feature_flags.backend.filters_validation import collect_filters_violations
+from products.feature_flags.backend.management.commands.audit_flag_filters import (
+ DIVERGENCE_ABSENT_GROUPS,
+ DIVERGENCE_DROPPED_KEY,
+ DIVERGENCE_NUMERIC_PROPERTY_KEY,
+ DIVERGENCE_OPERATOR_ALIAS,
+ DIVERGENCE_SHAPES,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
INVALID_MULTIVARIATE_FILTERS: dict[str, Any] = {
@@ -37,6 +45,12 @@ class TestAuditFlagFilters(BaseTest):
def _rule(self, report: dict[str, Any], rule_id: str) -> dict[str, Any] | None:
return next((rule for rule in report["rules"] if rule["rule_id"] == rule_id), None)
+ def _divergence_counts(self, report: dict[str, Any]) -> dict[str, int]:
+ return {entry["shape_id"]: entry["flags_affected"] for entry in report["roundtrip_divergences"]}
+
+ def _divergence(self, report: dict[str, Any], shape_id: str) -> dict[str, Any]:
+ return next(entry for entry in report["roundtrip_divergences"] if entry["shape_id"] == shape_id)
+
def test_clean_flags_report_no_violations(self) -> None:
self._create_flag("clean", {"groups": [{"properties": [], "rollout_percentage": 50}]})
self._create_flag("empty_filters", {})
@@ -124,12 +138,19 @@ class TestAuditFlagFilters(BaseTest):
limited = self._run("--limit", "1")
assert limited["scanned"] == 1
+ self._create_flag("diverging-first", {"payloads": {}})
+ self._create_flag("diverging-second", {"payloads": {}})
sampled = self._run("--samples", "1")
rule = self._rule(sampled, "cross_field.variant_rollout_sum_not_100")
assert rule is not None
assert rule["flags_affected"] == 2
assert len(rule["sample_flag_ids"]) == 1
+ divergence = self._divergence(sampled, DIVERGENCE_ABSENT_GROUPS)
+ assert divergence["flags_affected"] == 2
+ assert len(divergence["sample_flag_ids"]) == 1
+ assert len(divergence["sample_details"]) == 1
+
def test_team_id_restricts_scan(self) -> None:
other_team = Team.objects.create(organization=self.organization, name="other")
self._create_flag("other-team", INVALID_MULTIVARIATE_FILTERS, team=other_team)
@@ -242,7 +263,12 @@ class TestAuditFlagFilters(BaseTest):
def test_console_output_escapes_control_sequences(self) -> None:
self._create_flag(
"escape-junk",
- {"groups": [], "payloads": {"\x1b]0;evil\x07": "1"}, "junk\x1b[31mkey": 1},
+ {
+ "groups": [],
+ "holdout": {"id": 1, "exclusion_percentage": 0, "junk\x1b[31mkey": 1},
+ "payloads": {"\x1b]0;evil\x07": "1"},
+ "junk\x1b[31mkey": 1,
+ },
)
out = StringIO()
@@ -261,3 +287,232 @@ class TestAuditFlagFilters(BaseTest):
assert len(report["unknown_keys"]) == 1
assert report["untracked_unknown_keys"] == 1
+
+ @parameterized.expand(
+ [
+ (
+ "numeric_property_key",
+ {
+ "groups": [
+ {
+ "properties": [
+ {"key": 987654, "type": "flag", "operator": "flag_evaluates_to", "value": True}
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ [DIVERGENCE_NUMERIC_PROPERTY_KEY],
+ ),
+ (
+ "variant_description_dropped",
+ {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50, "description": "baseline"},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ [DIVERGENCE_DROPPED_KEY],
+ ),
+ (
+ "multivariate_key_dropped",
+ {
+ "groups": [],
+ "multivariate": {
+ "variants": [{"key": "control", "rollout_percentage": 100}],
+ "description": "two-arm split",
+ },
+ },
+ [DIVERGENCE_DROPPED_KEY],
+ ),
+ (
+ "holdout_key_dropped",
+ {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "holdout": {"id": 42, "exclusion_percentage": 10, "name": "Q3 holdout"},
+ },
+ [DIVERGENCE_DROPPED_KEY],
+ ),
+ (
+ "operator_alias_min",
+ {
+ "groups": [
+ {
+ "properties": [{"key": "age", "type": "person", "operator": "min", "value": 18}],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ [DIVERGENCE_OPERATOR_ALIAS],
+ ),
+ (
+ "operator_alias_max",
+ {
+ "groups": [
+ {
+ "properties": [{"key": "age", "type": "person", "operator": "max", "value": 65}],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ [DIVERGENCE_OPERATOR_ALIAS],
+ ),
+ ("absent_groups", {"payloads": {"true": '"x"'}}, [DIVERGENCE_ABSENT_GROUPS]),
+ (
+ "null_valued_dropped_key",
+ {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100, "description": None}]},
+ },
+ [],
+ ),
+ (
+ "blank_valued_dropped_key",
+ {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100, "description": ""}]},
+ },
+ [DIVERGENCE_DROPPED_KEY],
+ ),
+ ("malformed_levels_are_skipped", {"groups": "all", "multivariate": [], "holdout": 3}, []),
+ (
+ "unknown_keys_at_round_tripped_levels",
+ {
+ "junk_f": 1,
+ "groups": [
+ {
+ "properties": [{"key": "k", "type": "person", "value": "x", "junk_p": 1}],
+ "rollout_percentage": 100,
+ "junk_g": 1,
+ }
+ ],
+ },
+ [],
+ ),
+ (
+ "integer_rollout_and_absent_variant_name",
+ {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ },
+ [],
+ ),
+ (
+ "boolean_property_key",
+ {"groups": [{"properties": [{"key": True, "type": "person"}], "rollout_percentage": 100}]},
+ [],
+ ),
+ ]
+ )
+ def test_roundtrip_divergence_shapes(self, name: str, filters: dict[str, Any], expected: list[str]) -> None:
+ flag = self._create_flag(name, filters)
+
+ report = self._run()
+
+ counts = self._divergence_counts(report)
+ assert counts == {shape_id: 1 if shape_id in expected else 0 for shape_id in DIVERGENCE_SHAPES}
+ for shape_id in expected:
+ assert self._divergence(report, shape_id)["sample_flag_ids"] == [flag.id]
+
+ def test_json_report_carries_the_divergence_note(self) -> None:
+ self._create_flag("absent-groups", {"payloads": {"true": '"x"'}})
+
+ report = self._run()
+
+ assert "Size a verifier fix from the second number" in report["roundtrip_divergences_note"]
+
+ def test_roundtrip_divergence_counts_flag_once_per_shape(self) -> None:
+ self._create_flag(
+ "two-numeric-keys",
+ {
+ "groups": [
+ {"properties": [{"key": 1, "type": "flag", "operator": "flag_evaluates_to", "value": True}]},
+ {"properties": [{"key": 2, "type": "flag", "operator": "flag_evaluates_to", "value": True}]},
+ ]
+ },
+ )
+
+ report = self._run()
+
+ assert self._divergence_counts(report)[DIVERGENCE_NUMERIC_PROPERTY_KEY] == 1
+ assert report["flags_with_roundtrip_divergences"] == 1
+
+ def test_divergence_only_flag_reports_no_violations(self) -> None:
+ # A clean violations run gates flipping #50084 enforcement on.
+ flag = self._create_flag(
+ "divergence-only",
+ {
+ "groups": [
+ {
+ "properties": [{"key": 7, "type": "person", "operator": "min", "value": "18"}],
+ "rollout_percentage": 100,
+ }
+ ]
+ },
+ )
+
+ report = self._run()
+
+ assert report["clean"] is True
+ assert report["flags_with_violations"] == 0
+ counts = self._divergence_counts(report)
+ assert counts[DIVERGENCE_NUMERIC_PROPERTY_KEY] == 1
+ assert counts[DIVERGENCE_OPERATOR_ALIAS] == 1
+ assert report["flags_with_roundtrip_divergences"] == 1
+ assert report["compared_flags_with_roundtrip_divergences"] == 1
+ detail = self._divergence(report, DIVERGENCE_NUMERIC_PROPERTY_KEY)["sample_details"][0]
+ assert f"flag={flag.id} team={self.team.id}" in detail
+ assert "groups[0].properties[0].key" in detail
+
+ @parameterized.expand(
+ [
+ ("inactive", {"payloads": {}}, {"active": False}, "inactive or deleted"),
+ ("soft_deleted", {"payloads": {}}, {"deleted": True}, "inactive or deleted"),
+ ("encrypted", {"payloads": {}}, {"has_encrypted_payloads": True}, "encrypted payloads"),
+ (
+ "structural_violation",
+ {"groups": [{"properties": [{"key": 1}]}]},
+ {},
+ "structural violation",
+ ),
+ ]
+ )
+ def test_flag_the_verifier_skips_counts_only_in_the_total(
+ self, name: str, filters: dict[str, Any], flag_kwargs: dict[str, Any], reason: str
+ ) -> None:
+ flag = self._create_flag(name, filters, **flag_kwargs)
+
+ report = self._run()
+
+ shape_id = DIVERGENCE_NUMERIC_PROPERTY_KEY if name == "structural_violation" else DIVERGENCE_ABSENT_GROUPS
+ entry = self._divergence(report, shape_id)
+ assert entry["flags_affected"] == 1
+ assert entry["compared_flags_affected"] == 0
+ assert report["flags_with_roundtrip_divergences"] == 1
+ assert report["compared_flags_with_roundtrip_divergences"] == 0
+ assert f"flag={flag.id} team={self.team.id}" in entry["sample_details"][0]
+ assert f"[not compared: {reason}]" in entry["sample_details"][0]
+
+ def test_console_output_reports_divergences_and_their_meaning(self) -> None:
+ self._create_flag("absent-groups", {"payloads": {"true": '"x"'}})
+ out = StringIO()
+
+ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)
+
+ output = out.getvalue()
+ assert "Cache-write round-trip divergences (1 flags, 1 compared by the verifier):" in output
+ assert re.search(rf"{re.escape(DIVERGENCE_ABSENT_GROUPS)}\s+1 flags, 1 compared", output)
+ assert "not enforcement violations" in output
+
+ def test_console_output_omits_the_divergence_note_on_a_clean_scan(self) -> None:
+ self._create_flag("clean", {"groups": []})
+ out = StringIO()
+
+ call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)
+
+ output = out.getvalue()
+ assert "Cache-write round-trip divergences (0 flags, 0 compared by the verifier):" in output
+ assert "not enforcement violations" not in output