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.

fix(flags): skip non-v1 configs in cross-team flag jobs (#105871)

Anders42fcec00d4a9
diff --git a/posthog/management/commands/fix_invalid_flag_property_types.py b/posthog/management/commands/fix_invalid_flag_property_types.py
deleted file mode 100644
index 7df0ce243a4d..000000000000
--- a/posthog/management/commands/fix_invalid_flag_property_types.py
+++ /dev/null
@@ -1,87 +0,0 @@
-from django.core.management.base import BaseCommand
-
-from products.feature_flags.backend.models.feature_flag import FeatureFlag
-
-# Valid property types for feature flags (from validate_filters in api/feature_flag.py)
-VALID_PROPERTY_TYPES = {"person", "cohort", "group", "flag"}
-
-# Map of invalid types to their correct replacement
-TYPE_FIXES = {
- "event": "person", # Django treats "event" the same as "person" for backwards compatibility
-}
-
-# Raw SQL to find flags with invalid property types (used as a subquery filter)
-INVALID_FLAGS_SQL = """
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters::jsonb->'groups') as grp,
- jsonb_array_elements(grp->'properties') as prop
- WHERE prop->>'type' NOT IN ('person', 'cohort', 'group', 'flag')
- AND prop->>'type' IS NOT NULL
-"""
-
-
-class Command(BaseCommand):
- help = "Fix feature flags with invalid property types (e.g., 'event' -> 'person')"
-
- def add_arguments(self, parser):
- parser.add_argument("--team-id", default=None, type=int, help="Limit to a specific team ID")
- parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
-
- def handle(self, *args, **options):
- live_run = options.get("live_run", False)
- team_id = options.get("team_id")
-
- mode = "LIVE RUN" if live_run else "DRY RUN"
- self.stdout.write(f"Starting fix_invalid_flag_property_types ({mode})")
-
- # Only fetch flags that have invalid property types (efficient DB-level filter)
- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (INVALID_FLAGS_SQL is a static constant, admin-only command)
- flags = FeatureFlag.objects.filter(active=True).extra(where=[f"EXISTS ({INVALID_FLAGS_SQL})"])
- if team_id:
- flags = flags.filter(team_id=team_id)
- self.stdout.write(f"Filtering to team_id={team_id}")
-
- fixed_count = 0
- unfixable_count = 0
- flags_to_update = []
-
- for flag in flags.iterator():
- filters = flag.filters or {}
- groups = filters.get("groups", [])
- modified = False
-
- for group_idx, group in enumerate(groups):
- properties = group.get("properties", [])
- for prop_idx, prop in enumerate(properties):
- prop_type = prop.get("type")
-
- if prop_type and prop_type not in VALID_PROPERTY_TYPES:
- if prop_type in TYPE_FIXES:
- new_type = TYPE_FIXES[prop_type]
- self.stdout.write(
- f" Flag id={flag.id} team_id={flag.team_id} key='{flag.key}': "
- f"group[{group_idx}].properties[{prop_idx}].type '{prop_type}' -> '{new_type}'"
- )
- prop["type"] = new_type
- modified = True
- fixed_count += 1
- else:
- self.stdout.write(
- self.style.WARNING(
- f" Flag id={flag.id} team_id={flag.team_id} key='{flag.key}': "
- f"group[{group_idx}].properties[{prop_idx}].type '{prop_type}' has no known fix"
- )
- )
- unfixable_count += 1
-
- if modified:
- flag.filters = filters # nosemgrep: feature-flags-no-raw-filters-access -- data-repair command that fixes the filters JSON itself
- flags_to_update.append(flag)
-
- if live_run and flags_to_update:
- FeatureFlag.objects.bulk_update(flags_to_update, ["filters"])
- self.stdout.write(self.style.SUCCESS(f" Saved {len(flags_to_update)} flags"))
-
- self.stdout.write(f"Completed ({mode}): {fixed_count} properties fixed, {unfixable_count} unfixable")
-
- if not live_run and fixed_count > 0:
- self.stdout.write(self.style.NOTICE("Run with --live-run to apply changes"))
diff --git a/posthog/management/commands/reencrypt_flag_payloads.py b/posthog/management/commands/reencrypt_flag_payloads.py
index 7447de37e7ee..45542ef56521 100644
--- a/posthog/management/commands/reencrypt_flag_payloads.py
+++ b/posthog/management/commands/reencrypt_flag_payloads.py
@@ -6,6 +6,7 @@ import structlog
from cryptography.fernet import InvalidToken
from 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.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -40,6 +41,9 @@ class Command(BaseCommand):
scanned = updated = skipped = 0
for flag in self._get_flags(team_id, limit).iterator(chunk_size=batch_size):
scanned += 1
+ if self._skip_unsupported(flag):
+ skipped += 1
+ continue
try:
changed = self._reencrypt(flag.pk, codec) if live_run else self._needs_reencrypt(flag, codec)
except InvalidToken as e:
@@ -53,26 +57,38 @@ class Command(BaseCommand):
)
self.stderr.write(f" ! skipped flag {flag.id} (team {flag.team_id}): {e}")
continue
- if changed:
+ if changed is None:
+ skipped += 1
+ elif changed:
updated += 1
verb = "re-encrypted" if live_run else "would re-encrypt"
self.stdout.write(f"Done. scanned={scanned} {verb}={updated} skipped={skipped}")
+ 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"):
+ return False
+ logger.warning("reencrypt_flag_payloads.skip_unsupported_config", flag_id=flag.id, team_id=flag.team_id)
+ return True
+
def _needs_reencrypt(self, flag: FeatureFlag, codec: FlagPayloadCodec) -> bool:
"""Dry-run check on the streamed snapshot: would this flag's payloads be rotated?"""
payloads = (flag.filters or {}).get("payloads") or {}
return self._rotate_payloads(payloads, codec) is not None
- def _reencrypt(self, flag_pk: int, codec: FlagPayloadCodec) -> bool:
- """Rotate one flag's payloads under a row lock, returning True if anything changed.
+ def _reencrypt(self, flag_pk: int, codec: FlagPayloadCodec) -> bool | None:
+ """Rotate one flag's payloads under a row lock: True if anything changed, None if skipped.
Re-read ``filters`` inside the lock so we merge the rotation into the current
value rather than a stale streamed snapshot — otherwise a concurrent edit to
other filter fields between the scan and the write would be silently lost.
"""
with transaction.atomic():
- flag = FeatureFlag.objects.select_for_update().only("id", "filters").get(pk=flag_pk)
+ flag = FeatureFlag.objects.select_for_update().only("id", "team_id", "filters").get(pk=flag_pk)
+ if self._skip_unsupported(flag):
+ return None
filters = flag.filters or {}
rotated = self._rotate_payloads(filters.get("payloads") or {}, codec)
if rotated is None:
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
index db5791b8a020..e8f1bbe3370d 100644
--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
@@ -1,8 +1,6 @@
# Generated by write_baseline() in test_feature_flag_gated_writes.py. Shrink it, never grow it.
posthog/api/file_system/registrations.py::_feature_flag_pre_delete::feature_flag.active =
posthog/api/file_system/registrations.py::_feature_flag_pre_restore::feature_flag.active =
-posthog/management/commands/fix_invalid_flag_property_types.py::Command.handle::FeatureFlag.objects.bulk_update()
-posthog/management/commands/fix_invalid_flag_property_types.py::Command.handle::flag.filters =
posthog/management/commands/generate_random_product_tours.py::Command.create_internal_targeting_flag::FeatureFlag.objects.create()
posthog/management/commands/reencrypt_flag_payloads.py::Command._reencrypt::FeatureFlag.objects.filter(pk=flag_pk).update()
posthog/management/commands/sync_feature_flags.py::Command.create_feature_flag::FeatureFlag.objects.create()
diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
index bd13aaf37cd6..383a5fdcbabd 100644
--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
@@ -27,7 +27,6 @@ ALLOWED_REASONS: dict[str, str] = {
"products/surveys/backend/api/survey.py": "targeting flag writes and the start/stop mirror of active",
"posthog/api/file_system/registrations.py": "file-system trash and restore flip active",
"products/early_access_features/backend/api.py": "never-fail cleanup when stored filters fail validation",
- "posthog/management/commands/fix_invalid_flag_property_types.py": "data repair command",
"posthog/management/commands/generate_random_product_tours.py": "local data generator",
"posthog/management/commands/reencrypt_flag_payloads.py": "payload re-encryption command",
"posthog/management/commands/sync_feature_flags.py": "local dev flag sync",
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index b9999f9e1921..0faae66fc716 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -74,14 +74,12 @@ def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) ->
# test runs before the array function; the planner is free to reorder the arms of `AND` and `OR`.
# Both predicates below interpolate these, so they are f-strings and every literal `{}` in their
# SQL is written `{{}}`.
-_GROUPS_ARRAY = (
- "CASE WHEN jsonb_typeof(posthog_featureflag.filters->'groups') = 'array' "
- "THEN posthog_featureflag.filters->'groups' ELSE '[]'::jsonb END"
-)
-_VARIANTS_ARRAY = (
- "CASE WHEN jsonb_typeof(posthog_featureflag.filters->'multivariate'->'variants') = 'array' "
- "THEN posthog_featureflag.filters->'multivariate'->'variants' ELSE '[]'::jsonb END"
-)
+def jsonb_array_or_empty(expr: str) -> str:
+ return f"CASE WHEN jsonb_typeof({expr}) = 'array' THEN {expr} ELSE '[]'::jsonb END"
+
+
+_GROUPS_ARRAY = jsonb_array_or_empty("posthog_featureflag.filters->'groups'")
+_VARIANTS_ARRAY = jsonb_array_or_empty("posthog_featureflag.filters->'multivariate'->'variants'")
# A release condition carries no targeting when `properties` is `[]`, absent, or JSON null, which
# is how `is_group_fully_rolled_out` and `is_boolean_flag_fully_rolled_out` read it. Postgres `->`
# returns SQL NULL for the absent key and the jsonb scalar `null` for the stored null, so each
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 ca385084eb90..34010218caa7 100644
--- a/products/feature_flags/backend/management/commands/audit_flag_filters.py
+++ b/products/feature_flags/backend/management/commands/audit_flag_filters.py
@@ -33,6 +33,7 @@ from products.feature_flags.backend.api.filters_schema import (
UNKNOWN_KEYS_SINK_CONTEXT_KEY,
is_legacy_unknown_key,
)
+from products.feature_flags.backend.facade.config import detect_config_format
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
@@ -333,6 +334,7 @@ class Command(BaseCommand):
divergences = RoundTripDivergenceAggregator(max_samples=samples)
rule_reports: dict[str, RuleReport] = {}
scanned = 0
+ skipped_unsupported = 0
flags_with_violations = 0
# objects_including_soft_deleted: the default manager excludes soft-deleted flags, and
@@ -348,6 +350,9 @@ class Command(BaseCommand):
# stored flags with empty groups are valid state and must never show up in this report.
for flag in _iter_flag_rows(queryset, limit=limit):
scanned += 1
+ if isinstance(flag.filters, dict) and detect_config_format(flag.filters).kind != "v1":
+ skipped_unsupported += 1
+ continue
try:
violations = collect_filters_violations(
flag.filters, context={UNKNOWN_KEYS_SINK_CONTEXT_KEY: sink, FLAG_ID_CONTEXT_KEY: flag.id}
@@ -389,13 +394,14 @@ class Command(BaseCommand):
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, divergences)
+ self._emit_json(scanned, skipped_unsupported, flags_with_violations, reports, sink, divergences)
else:
- self._emit_console(scanned, flags_with_violations, reports, sink, divergences)
+ self._emit_console(scanned, skipped_unsupported, flags_with_violations, reports, sink, divergences)
def _emit_json(
self,
scanned: int,
+ skipped_unsupported: int,
flags_with_violations: int,
reports: list[RuleReport],
sink: UnknownKeyAggregator,
@@ -403,6 +409,7 @@ class Command(BaseCommand):
) -> None:
payload = {
"scanned": scanned,
+ "skipped_unsupported_config_format": skipped_unsupported,
"flags_with_violations": flags_with_violations,
"clean": flags_with_violations == 0,
# Enumerate fields explicitly: report.__dict__ would leak any future internal
@@ -447,14 +454,16 @@ class Command(BaseCommand):
def _emit_console(
self,
scanned: int,
+ skipped_unsupported: int,
flags_with_violations: int,
reports: list[RuleReport],
sink: UnknownKeyAggregator,
divergences: RoundTripDivergenceAggregator,
) -> None:
- clean = scanned - flags_with_violations
+ clean = scanned - skipped_unsupported - flags_with_violations
self.stdout.write(
- f"Scanned {scanned} flags (soft-deleted included); {clean} clean, {flags_with_violations} with violations."
+ f"Scanned {scanned} flags (soft-deleted included); {clean} clean, {flags_with_violations} with violations, "
+ f"{skipped_unsupported} skipped (config format not 1)."
)
if reports:
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 ef55de97a43d..31b2fe32171b 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
@@ -200,12 +200,13 @@ class TestAuditFlagFilters(BaseTest):
def test_console_output_summarizes(self) -> None:
self._create_flag("cross-field", INVALID_MULTIVARIATE_FILTERS)
+ self._create_flag("v2", {"version": 2, "rules": []})
out = StringIO()
call_command("audit_flag_filters", "--team-id", str(self.team.id), stdout=out)
output = out.getvalue()
- assert "1 with violations" in output
+ assert "0 clean, 1 with violations, 1 skipped (config format not 1)." in output
assert "cross_field.variant_rollout_sum_not_100" in output
def test_console_output_reports_clean_scan(self) -> None:
@@ -516,3 +517,14 @@ class TestAuditFlagFilters(BaseTest):
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
+
+ def test_other_config_formats_are_skipped_not_validated(self) -> None:
+ self._create_flag("v2", {"version": 2, "rules": []})
+ self._create_flag("structural", {"groups": [{"properties": [{"type": "person"}]}]})
+
+ report = self._run()
+
+ assert report["scanned"] == 2
+ assert report["skipped_unsupported_config_format"] == 1
+ assert report["flags_with_violations"] == 1
+ assert report["unknown_keys"] == []
diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
index 4759c09288a8..92470cedffcd 100644
--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
@@ -1,4 +1,4 @@
-from collections.abc import Collection
+from collections.abc import Collection, Iterable
from datetime import datetime
from django.db.models import Q
@@ -16,6 +16,7 @@ from posthog.temporal.health_checks.models import HealthCheckResult
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.config import detect_config_format
from products.feature_flags.backend.flag_status import (
ROLLOUT_FULLY_ROLLED_OUT,
ROLLOUT_NOT_ROLLED_OUT,
@@ -143,15 +144,18 @@ class StaleFeatureFlagsCheck(HealthCheck):
# boundary be selected by one of them and then classified against the other.
stale_threshold = stale_flag_threshold()
- stale_candidates = list(filter_stale_flags(reportable_flags, stale_threshold=stale_threshold))
+ stale_rows = list(filter_stale_flags(reportable_flags, stale_threshold=stale_threshold))
+ stale_candidates = _v1_flags(stale_rows)
# Only a never-called stale flag can come back from the rollout query too: a usage-stale
# flag's last call predates the cutoff, which fails the call-recency filter below. Excluding
# those ids beats fetching the rows again and dropping them in Python, and
- # `hash_keys=["flag_id"]` would otherwise give both rows the same issue identity.
+ # `hash_keys=["flag_id"]` would otherwise give both rows the same issue identity. It reads
+ # `stale_rows`, not `stale_candidates`, so a never-called non-v1 row also stays out of the
+ # rollout query instead of being fetched and logged a second time.
# The ids go in as a bound list. A subquery looks tidier and is wrong here: the inner
# `.extra(where=...)` hard-codes `posthog_featureflag`, the subquery aliases that table,
# and the raw text then tests the outer row instead of the inner one.
- overlap_ids = {flag.id for flag in stale_candidates if flag.last_called_at is None}
+ overlap_ids = {flag.id for flag in stale_rows if flag.last_called_at is None}
# The prefilter reads configuration only and returns a superset, so the policy that makes
# one of those flags a cleanup candidate is applied here, and the checker settles each
# remaining row. A flag created after the cutoff is too new for a constant configuration to
@@ -169,7 +173,7 @@ class StaleFeatureFlagsCheck(HealthCheck):
)
full_rollout_candidates = [
flag
- for flag in full_rollout_query
+ for flag in _v1_flags(full_rollout_query)
if not _serves_more_than_one_result(flag)
and FeatureFlagStatusChecker(feature_flag=flag).is_flag_fully_rolled_out(flag)[0]
]
@@ -205,6 +209,21 @@ class StaleFeatureFlagsCheck(HealthCheck):
return issues
+def _v1_flags(flags: Iterable[FeatureFlag]) -> list[FeatureFlag]:
+ """Keep the rows whose `filters` is None or a config format 1 object.
+
+ Drop and log the rest, so `detect` never reports a flag it can't read.
+ """
+ kept = []
+ for flag in flags:
+ filters = flag.filters
+ if filters is None or (isinstance(filters, dict) and detect_config_format(filters).kind == "v1"):
+ kept.append(flag)
+ else:
+ logger.info("stale_feature_flags_skipped_unsupported_config", flag_id=flag.id, team_id=flag.team_id)
+ return kept
+
+
def _serves_more_than_one_result(flag: FeatureFlag) -> bool:
"""Whether the matcher can return more than the one result the checker named.
diff --git a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
index 9a1966004174..ccccc364fef1 100644
--- a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
@@ -10,6 +10,7 @@ from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from parameterized import parameterized
+from structlog.testing import capture_logs
from posthog.clickhouse.query_tagging import Product
from posthog.job_owners import JobOwners
@@ -652,6 +653,42 @@ class TestStaleFlagsDetect(BaseTest):
assert len(results[team_two.id]) == 1
assert results[team_two.id][0].payload["flag_id"] != blocked.id
+ def test_other_config_formats_are_skipped_without_failing_the_batch(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ unsupported = FeatureFlag.objects.create(
+ team=other_team,
+ key="v2-flag",
+ created_by=self.user,
+ active=True,
+ created_at=timezone.now() - timedelta(days=60),
+ filters={"version": 2, **FULL_ROLLOUT_FILTERS},
+ )
+ not_an_object = FeatureFlag.objects.create(
+ team=other_team,
+ key="list-filters",
+ created_by=self.user,
+ active=True,
+ **{**stale_by_usage(), "filters": ["version"]},
+ )
+ called = FeatureFlag.objects.create(
+ team=other_team,
+ key="v2-called",
+ created_by=self.user,
+ active=True,
+ **{**constant_and_called(), "filters": {"version": 2, **FULL_ROLLOUT_FILTERS}},
+ )
+ self._create_flag("v1-stale", **stale_by_usage())
+
+ with capture_logs() as logs:
+ results = self._detect([self.team.id, other_team.id])
+
+ assert set(results) == {self.team.id}
+ assert [result.payload["flag_key"] for result in results[self.team.id]] == ["v1-stale"]
+ skips = [log for log in logs if log["event"] == "stale_feature_flags_skipped_unsupported_config"]
+ assert sorted((log["flag_id"], log["team_id"]) for log in skips) == sorted(
+ [(unsupported.id, other_team.id), (not_an_object.id, other_team.id), (called.id, other_team.id)]
+ )
+
def test_query_count_does_not_grow_with_candidates_or_teams(self) -> None:
self._create_flag("baseline", **stale_by_usage())
check = StaleFeatureFlagsCheck()
diff --git a/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py b/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py
index 4f0c12683016..fa05ee771e7f 100644
--- a/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py
+++ b/products/feature_flags/backend/test/test_reencrypt_flag_payloads.py
@@ -1,11 +1,16 @@
+from io import StringIO
+
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.core.management import call_command
from django.test import override_settings
from cryptography.fernet import InvalidToken
+from structlog.testing import capture_logs
from posthog.management.commands.reencrypt_flag_payloads import Command
+from posthog.models import Team
from products.feature_flags.backend.encrypted_flag_payloads import (
FlagPayloadCodec,
@@ -113,3 +118,54 @@ class TestReencryptFlagPayloads(BaseTest):
assert flag.filters["groups"] == [{"properties": [{"key": "x", "value": "y"}]}]
new_token = flag.filters["payloads"]["true"].encode("utf-8")
assert _codec(NEW_KEY).decrypt(new_token).decode("utf-8") == PAYLOAD
+
+ def test_skips_other_config_formats_and_still_rotates_v1_rows(self):
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ token = _codec(OLD_KEY).encrypt(PAYLOAD.encode("utf-8")).decode("utf-8")
+ unsupported = FeatureFlag.objects.create(
+ team=other_team,
+ key="v2-flag",
+ created_by=self.user,
+ is_remote_configuration=True,
+ has_encrypted_payloads=True,
+ filters={"version": 2, "rules": [], "payloads": {"true": token}},
+ )
+ not_an_object = FeatureFlag.objects.create(
+ team=other_team,
+ key="list-filters",
+ created_by=self.user,
+ is_remote_configuration=True,
+ has_encrypted_payloads=True,
+ filters=["version"],
+ )
+ v1_flag = self._make_flag("rc-flag", encrypt_with=OLD_KEY)
+
+ with override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]):
+ with capture_logs() as logs:
+ call_command("reencrypt_flag_payloads", "--live-run")
+
+ unsupported.refresh_from_db()
+ assert unsupported.filters == {"version": 2, "rules": [], "payloads": {"true": token}}
+ v1_flag.refresh_from_db()
+ assert _codec(NEW_KEY).decrypt(v1_flag.filters["payloads"]["true"].encode("utf-8")).decode("utf-8") == PAYLOAD
+ skips = [log for log in logs if log["event"] == "reencrypt_flag_payloads.skip_unsupported_config"]
+ assert sorted((log["flag_id"], log["team_id"]) for log in skips) == sorted(
+ [(unsupported.id, other_team.id), (not_an_object.id, other_team.id)]
+ )
+
+ def test_format_change_under_lock_is_counted_as_skipped(self):
+ self._make_flag("rc-flag", encrypt_with=OLD_KEY)
+ real = Command._reencrypt
+
+ def switch_format_under_lock(command, pk, codec):
+ FeatureFlag.objects.filter(pk=pk).update(filters={"version": 2, "rules": []})
+ return real(command, pk, codec)
+
+ out = StringIO()
+ with (
+ override_settings(FLAGS_SECRET_KEYS=[NEW_KEY, OLD_KEY]),
+ patch.object(Command, "_reencrypt", switch_format_under_lock),
+ ):
+ call_command("reencrypt_flag_payloads", "--team-id", str(self.team.id), "--live-run", stdout=out)
+
+ assert "re-encrypted=0 skipped=1" in out.getvalue()