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.

perf(flags): drop unreferenced inactive flags from cached payloads (#82117)

Phil Haack806bf3cb8a5c
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 1e593821e288..f2f8a21d5ed7 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -113,15 +113,15 @@ flags_hypercache = HyperCache(
)
```
-The `_get_feature_flags_for_service` function fetches all flags for a team (including inactive, but excluding deleted and encrypted remote config flags) and returns the cache payload. The Rust service filters out inactive flags at request time via `filtered_out_flag_ids`.
-
-Because that filtering happens before the matcher reads `filters`, an inactive flag's filters can never affect a response, so `_blank_inactive_filters` replaces them with an empty `{"groups": []}` before the payload is written.
-The flag entry itself stays, so a dependency condition on a disabled flag still resolves to false instead of raising `DependencyNotFound`.
-`build_flags_cache` in `rust/feature-flags/src/flags/cache_builder.rs` writes the same entry and applies the same blanking, so the two writers produce identical bytes and share one etag.
-While only one of the two carries the blanking, they disagree on inactive flags' `filters`, so the etag alternates and `FlagDefinitionsCache` reloads on each flip.
-This is scoped to teams whose invalidation routes to Kafka (`KAFKA_ROUTING_FLAG`), the only teams the Rust builder writes for.
-Every other team has Python as its sole writer and sees no disagreement.
-Deploy Django ahead of the Rust images: an older Python verifier lacks the `tolerate_blanked_filters` exemption, so it reports a blanked entry as `DATA_MISMATCH` and repairs it back to full filters, which the next Rust build undoes.
+The `_get_feature_flags_for_service` function fetches all flags for a team (including inactive, but excluding deleted and encrypted remote config flags), then returns a cache payload trimmed to the flags worth caching. The Rust service filters out inactive flags at request time via `filtered_out_flag_ids`.
+
+Because that filtering happens before the matcher reads `filters`, an inactive flag can never affect a response, so the payload keeps only evaluable flags plus the inactive flags that another flag's dependency conditions reference.
+A referenced entry is load-bearing: the matcher pre-seeds its id as false, so a dependent with `flag_evaluates_to: false` on a disabled flag still matches instead of missing a dependency.
+`_drop_unreferenced_unevaluable_flags` removes the rest, `evaluation_metadata` is computed on the surviving set, and `_blank_inactive_filters` replaces the kept unevaluable flags' `filters` with an empty `{"groups": []}` before the payload is written.
+`build_flags_cache` in `rust/feature-flags/src/flags/cache_builder.rs` writes the same entry and applies the same drop and blanking.
+Parity is per team, not per byte: each team has one primary writer (teams whose invalidation routes to Kafka via `KAFKA_ROUTING_FLAG` get the Rust builder, every other team Python), the Python verifier remains a repair writer for every team, and the two serializers order keys differently — so what must match is the flag set, fields, and metadata, not the bytes or etag.
+Old-shape entries that still carry unreferenced inactive rows stay valid: the matcher never reads those rows, and `verify_team_flags` suppresses them instead of reporting `STALE_IN_CACHE`, so they converge through flag edits and TTL rather than a fleet-wide repair.
+Deploy Django ahead of the Rust images: an older Python verifier reports a Rust-written entry's dropped rows as missing, repairs them back, and the next Rust build removes them again. The reverse skew is safe — the newer verifier tolerates the extra rows old writers leave.
### Cache payload structure
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index ee815d3ffc2d..75a97e8ba1db 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -343,6 +343,26 @@ def _compute_flag_dependencies(flags_data: list[dict[str, Any]]) -> dict[str, An
}
+def _drop_unreferenced_unevaluable_flags(flags_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Return the flags worth caching: evaluable ones, plus unevaluable ones that
+ another flag's dependency conditions reference.
+
+ An unreferenced inactive/deleted flag is dead weight — the matcher filters it
+ out before reading it and nothing resolves against it. A referenced one is
+ load-bearing: the matcher pre-seeds its id as false, so a dependent with
+ ``flag_evaluates_to: false`` on a disabled flag still matches; dropping it
+ would turn that dependent into a missing-dependency miss.
+
+ ``_extract_direct_dependency_ids`` returns nothing for unevaluable flags, so
+ only evaluable flags contribute references: a chain of inactive flags keeps
+ just the hop an evaluable flag points at.
+ """
+ referenced_ids: set[int] = set()
+ for flag in flags_data:
+ referenced_ids |= _extract_direct_dependency_ids(flag)
+ return [flag for flag in flags_data if not _is_unevaluable(flag) or flag["id"] in referenced_ids]
+
+
def _blank_inactive_filters(flags_data: list[dict[str, Any]]) -> None:
"""Empty the ``filters`` of flags that can never be evaluated, in place.
@@ -358,20 +378,24 @@ def _blank_inactive_filters(flags_data: list[dict[str, Any]]) -> None:
if _is_unevaluable(flag):
# Matches an empty Rust ``FlagFilters``, whose ``groups`` has no
# ``skip_serializing_if`` and so serializes as a key rather than ``{}``.
- # Both writers of this entry must emit the same bytes to share one etag.
+ # Both writers of this entry emit this same blank shape.
flag["filters"] = {"groups": []}
def _build_flags_payload(
flags_data: list[dict[str, Any]],
- evaluation_metadata: dict[str, Any],
cohorts: list[dict[str, Any]],
) -> dict[str, Any]:
- """Assemble the ``flags.json`` wrapper, blanking unevaluable flags' filters.
+ """Assemble the ``flags.json`` wrapper: drop unreferenced unevaluable flags,
+ compute dependency metadata on the survivors, and blank the kept unevaluable
+ flags' filters.
- Blanking lives here so no writer can assemble a payload without it. The Rust side
+ These steps live here so no writer can assemble a payload without them, and so
+ the metadata can never be computed on a pre-drop flag list. The Rust side
reaches the same point through a single ``build_flags_cache``.
"""
+ flags_data = _drop_unreferenced_unevaluable_flags(flags_data)
+ evaluation_metadata = _compute_flag_dependencies(flags_data)
_blank_inactive_filters(flags_data)
return {"flags": flags_data, "evaluation_metadata": evaluation_metadata, "cohorts": cohorts}
@@ -384,9 +408,10 @@ def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:
must match rust/feature-flags/src/flags/flag_models.rs::HypercacheFlagsWrapper.
Changes to this structure must follow the expand-and-contract pattern.
- Fetches all feature flags for the team (including inactive, excluding deleted)
- and returns them wrapped in a dict that HyperCache can serialize. The actual
- flag data is in the "flags" key as a list of flag dictionaries.
+ Fetches the team's evaluable feature flags (active, not deleted), plus the
+ inactive flags another flag's dependency conditions reference, wrapped in a
+ dict that HyperCache can serialize. The actual flag data is in the "flags"
+ key as a list of flag dictionaries.
Encrypted remote config flags are excluded since they can only be accessed via
the dedicated /remote_config endpoint which handles decryption. Including them
@@ -400,19 +425,18 @@ def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:
"""
flags = get_feature_flags(team=team, exclude_encrypted_payloads=True)
flags_data = serialize_feature_flags(flags)
- evaluation_metadata = _compute_flag_dependencies(flags_data)
-
cohorts = _get_referenced_cohorts(team.id, flags_data)
+ payload = _build_flags_payload(flags_data, cohorts)
logger.info(
"Loaded feature flags for service cache",
team_id=team.id,
project_id=team.project_id,
- flag_count=len(flags_data),
+ flag_count=len(payload["flags"]),
cohort_count=len(cohorts),
)
- return _build_flags_payload(flags_data, evaluation_metadata, cohorts)
+ return payload
def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str, Any]]:
@@ -436,8 +460,9 @@ def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str,
return {}
# Load all flags for all teams in one query with evaluation tags pre-loaded.
- # Include disabled flags (active=False) so flag dependencies can reference them
- # and evaluate them as false, rather than raising DependencyNotFound errors.
+ # Disabled flags (active=False) are loaded too: ones referenced by another
+ # flag's dependencies stay in the payload and evaluate as false, and
+ # _build_flags_payload drops the rest.
# Exclude encrypted payload flags - they can only be accessed via the
# dedicated /remote_config endpoint which handles decryption.
# Note: We intentionally don't select_related("team") here because we only need
@@ -487,19 +512,18 @@ def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str,
# Build result for each team
result: dict[int, dict[str, Any]] = {}
for team in teams:
- flags_data = flags_data_by_team[team.id]
- evaluation_metadata = _compute_flag_dependencies(flags_data)
-
team_cohorts = cohorts_by_team.get(team.id, [])
+ payload = _build_flags_payload(flags_data_by_team[team.id], team_cohorts)
+
logger.info(
"Loaded feature flags for service cache (batch)",
team_id=team.id,
project_id=team.project_id,
- flag_count=len(flags_data),
+ flag_count=len(payload["flags"]),
cohort_count=len(team_cohorts),
)
- result[team.id] = _build_flags_payload(flags_data, evaluation_metadata, team_cohorts)
+ result[team.id] = payload
return result
@@ -670,6 +694,12 @@ def verify_team_flags(
# Find stale flags (in cache but not in DB)
for flag_id in cached_flags_by_id:
if flag_id not in db_flags_by_id:
+ # An unevaluable cached row is invisible to the matcher, so its presence
+ # is not drift worth repairing, and reporting it would repair-rewrite
+ # every old-shape entry at once. A stale ACTIVE flag still reports: its
+ # cached copy has active=True.
+ if _is_unevaluable(cached_flags_by_id[flag_id]):
+ continue
diff = {
"type": "STALE_IN_CACHE",
"flag_id": flag_id,
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index fb6758e5db0b..266a62c7d456 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -37,6 +37,7 @@ from products.feature_flags.backend.flags_cache import (
_blank_inactive_filters,
_compare_flag_fields,
_compute_flag_dependencies,
+ _drop_unreferenced_unevaluable_flags,
_extract_cohort_ids_from_flag_filters,
_extract_direct_dependency_ids,
_get_feature_flags_for_service,
@@ -50,6 +51,7 @@ from products.feature_flags.backend.flags_cache import (
get_team_ids_with_recently_updated_flags,
get_teams_with_flags_queryset,
update_flags_cache,
+ verify_team_flags,
)
from products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidation
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
@@ -137,75 +139,49 @@ class TestServiceFlagsCache(BaseTest):
assert len(flags) == 1
assert flags[0]["key"] == "active-flag"
- def test_get_feature_flags_for_service_includes_inactive(self):
- """Test that inactive flags are included in cache.
-
- Inactive flags must be included so that flag dependencies can reference them
- and evaluate them as false, rather than raising DependencyNotFound errors.
- """
- # Create active flag
+ def _create_referenced_and_unreferenced_inactive_flags(self) -> None:
+ # An inactive flag with no referrer carries no evaluation weight and is dropped;
+ # one referenced by an active dependent stays so the dependency evaluates it as
+ # false rather than raising DependencyNotFound.
FeatureFlag.objects.create(
team=self.team,
- key="active-flag",
+ key="unreferenced-inactive-flag",
created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ active=False,
+ filters=_dependency_filters(),
)
-
- # Create inactive flag
- FeatureFlag.objects.create(
+ referenced_inactive = FeatureFlag.objects.create(
team=self.team,
- key="inactive-flag",
+ key="referenced-inactive-flag",
created_by=self.user,
active=False,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ filters=_dependency_filters(),
)
-
- result = _get_feature_flags_for_service(self.team)
- flags = result["flags"]
-
- # Both active and inactive flags should be included
- assert len(flags) == 2
- flag_keys = {f["key"] for f in flags}
- assert flag_keys == {"active-flag", "inactive-flag"}
-
- # Verify the inactive flag has active=False
- inactive_flag = next(f for f in flags if f["key"] == "inactive-flag")
- assert inactive_flag["active"] is False
-
- def test_get_feature_flags_for_teams_batch_includes_inactive(self):
- """Test that batch function includes inactive flags for dependency resolution.
-
- This tests the same behavior as test_get_feature_flags_for_service_includes_inactive
- but for the batch function used in management commands and cache warming.
- """
- # Create active flag
FeatureFlag.objects.create(
team=self.team,
- key="active-flag",
+ key="dependent-flag",
created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ filters=_dependency_filters(referenced_inactive.id),
)
- # Create inactive flag
- FeatureFlag.objects.create(
- team=self.team,
- key="inactive-flag",
- created_by=self.user,
- active=False,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
+ def _assert_keeps_referenced_inactive_drops_unreferenced(self, flags: list[dict]) -> None:
+ assert {f["key"] for f in flags} == {"referenced-inactive-flag", "dependent-flag"}
+ kept_inactive_flag = next(f for f in flags if f["key"] == "referenced-inactive-flag")
+ assert kept_inactive_flag["active"] is False
- result = _get_feature_flags_for_teams_batch([self.team])
- flags = result[self.team.id]["flags"]
+ def test_get_feature_flags_for_service_keeps_referenced_inactive_drops_unreferenced(self):
+ self._create_referenced_and_unreferenced_inactive_flags()
- # Both active and inactive flags should be included
- assert len(flags) == 2
- flag_keys = {f["key"] for f in flags}
- assert flag_keys == {"active-flag", "inactive-flag"}
+ result = _get_feature_flags_for_service(self.team)
+
+ self._assert_keeps_referenced_inactive_drops_unreferenced(result["flags"])
- # Verify the inactive flag has active=False
- inactive_flag = next(f for f in flags if f["key"] == "inactive-flag")
- assert inactive_flag["active"] is False
+ def test_get_feature_flags_for_teams_batch_keeps_referenced_inactive_drops_unreferenced(self):
+ self._create_referenced_and_unreferenced_inactive_flags()
+
+ result = _get_feature_flags_for_teams_batch([self.team])
+
+ self._assert_keeps_referenced_inactive_drops_unreferenced(result[self.team.id]["flags"])
def test_get_feature_flags_for_service_excludes_encrypted_remote_config(self):
"""Test that encrypted remote config flags are excluded from cache.
@@ -1127,7 +1103,7 @@ class TestServiceFlagsDataFormat(BaseTest):
fixture_path = _REPO_ROOT / "rust" / "feature-flags" / "tests" / "fixtures" / "hypercache_contract.json"
fixture = json.loads(fixture_path.read_text())
- # --- Create test data mirroring the 4 fixture flag variants ---
+ # --- Create test data mirroring the fixture flag variants ---
cohort = Cohort.objects.create(
team=self.team,
@@ -1306,6 +1282,55 @@ class TestServiceFlagsDataFormat(BaseTest):
},
)
+ # 6) referenced-disabled-flag: inactive but referenced by 7), so both writers
+ # keep the row and blank its filters. Created with real targeting so the
+ # fixture's empty shape proves the blank, not an empty input.
+ referenced_disabled = FeatureFlag.objects.create(
+ team=self.team,
+ key="referenced-disabled-flag",
+ name="Referenced disabled flag",
+ created_by=self.user,
+ active=False,
+ version=1,
+ evaluation_runtime="all",
+ bucketing_identifier=None,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100, "variant": None}],
+ "multivariate": None,
+ "payloads": {},
+ },
+ )
+
+ # 7) disabled-dependent-flag: active, its condition points at 6)
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="disabled-dependent-flag",
+ name="Dependent on disabled flag",
+ created_by=self.user,
+ version=1,
+ evaluation_runtime="all",
+ bucketing_identifier=None,
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": str(referenced_disabled.id),
+ "label": "referenced-disabled-flag",
+ "operator": "flag_evaluates_to",
+ "type": "flag",
+ "value": False,
+ }
+ ],
+ "rollout_percentage": 100,
+ "variant": None,
+ }
+ ],
+ "multivariate": None,
+ "payloads": {},
+ },
+ )
+
result = _get_feature_flags_for_service(self.team)
# --- Deep recursive schema comparison ---
@@ -2566,6 +2591,70 @@ class TestManagementCommands(BaseTest):
# Restore original batch function
FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.hypercache.batch_load_fn = original_batch_fn
+ def test_verify_tolerates_old_shape_cache_with_extra_unevaluable_flag(self):
+ # Entries written before unreferenced unevaluable flags were dropped still hold
+ # rows the DB side no longer produces. Reporting those as STALE_IN_CACHE would
+ # flag every pre-existing entry as drifted at once.
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="active-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ update_flags_cache(self.team)
+
+ cached_data, _source = flags_hypercache.get_from_cache_with_source(self.team)
+ assert cached_data is not None
+ # Simulate an old-shape entry by injecting an extra unreferenced-inactive flag
+ # dict that a pre-change writer would have included but the DB side never
+ # produces anymore.
+ cached_data["flags"].append(
+ {
+ "id": 999999,
+ "team_id": self.team.id,
+ "key": "old-shape-unreferenced-inactive",
+ "active": False,
+ "deleted": False,
+ "filters": {"groups": []},
+ }
+ )
+ flags_hypercache.set_cache_value(self.team, cached_data)
+
+ result = verify_team_flags(self.team)
+
+ self.assertEqual(result["status"], "match")
+
+ def test_verify_reports_missing_referenced_inactive_flag(self):
+ # A referenced inactive flag stays in the expected payload, so a cache entry
+ # missing that row is a real gap the stale-row suppression must not swallow.
+ dep = FeatureFlag.objects.create(
+ team=self.team,
+ key="referenced-inactive-flag",
+ created_by=self.user,
+ active=False,
+ filters=_dependency_filters(),
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="dependent-flag",
+ created_by=self.user,
+ filters=_dependency_filters(dep.id),
+ )
+ update_flags_cache(self.team)
+
+ cached_data, _source = flags_hypercache.get_from_cache_with_source(self.team)
+ assert cached_data is not None
+ cached_data["flags"] = [f for f in cached_data["flags"] if f["id"] != dep.id]
+ flags_hypercache.set_cache_value(self.team, cached_data)
+
+ result = verify_team_flags(self.team, verbose=True)
+
+ self.assertEqual(result["status"], "mismatch")
+ self.assertEqual(result["issue"], "DATA_MISMATCH")
+ missing = [d for d in result["diffs"] if d["type"] == "MISSING_IN_CACHE"]
+ self.assertEqual(len(missing), 1)
+ self.assertEqual(missing[0]["flag_id"], dep.id)
+
@override_settings(
FLAGS_REDIS_URL=None,
@@ -3056,17 +3145,26 @@ class TestGetTeamsWithFlagsQueryset(BaseTest):
assert team_ids.count(self.team.id) == 1
+def _dependency_filters(*dep_ids: int) -> dict:
+ return {
+ "groups": [
+ {
+ "properties": [
+ {"type": "flag", "key": str(dep_id), "value": ["true"], "operator": "exact"} for dep_id in dep_ids
+ ],
+ "rollout_percentage": 100,
+ }
+ ]
+ }
+
+
def _make_flag(id: int, key: str, deps: list[int] | None = None, active: bool = True, deleted: bool = False) -> dict:
- """Helper to build a serialized flag dict with optional flag dependencies."""
- properties = []
- for dep_id in deps or []:
- properties.append({"type": "flag", "key": str(dep_id), "value": ["true"], "operator": "exact"})
return {
"id": id,
"key": key,
"active": active,
"deleted": deleted,
- "filters": {"groups": [{"properties": properties, "rollout_percentage": 100}]},
+ "filters": _dependency_filters(*(deps or [])),
}
@@ -3133,7 +3231,7 @@ class TestBlankInactiveFilters:
)
def test_blanks_only_unevaluatable_flags(self, _name, flag, expect_blanked):
# `payloads` makes clearing only `groups` distinguishable from replacing the whole
- # dict. A partial clear would keep keys the Rust writer drops, splitting the etag.
+ # dict. A partial clear would keep keys the Rust writer's blank shape never has.
flag["filters"]["payloads"] = {"true": "payload"}
original_filters = copy.deepcopy(flag["filters"])
@@ -3156,6 +3254,77 @@ class TestBlankInactiveFilters:
assert flag["filters"] == original_filters
+class TestDropUnreferencedUnevaluableFlags:
+ @parameterized.expand(
+ [
+ (
+ "active_flags_always_kept",
+ [_make_flag(1, "flag_a"), _make_flag(2, "flag_b")],
+ {1, 2},
+ ),
+ (
+ "unreferenced_inactive_flag_dropped",
+ [_make_flag(1, "flag_a"), _make_flag(2, "flag_b", active=False)],
+ {1},
+ ),
+ (
+ "unreferenced_deleted_flag_dropped",
+ [_make_flag(1, "flag_a"), _make_flag(2, "flag_b", deleted=True)],
+ {1},
+ ),
+ (
+ "inactive_flag_referenced_by_active_dependent_kept",
+ [_make_flag(1, "flag_a", deps=[2]), _make_flag(2, "flag_b", active=False)],
+ {1, 2},
+ ),
+ (
+ "deleted_flag_referenced_by_active_dependent_kept",
+ [_make_flag(1, "flag_a", deps=[2]), _make_flag(2, "flag_b", deleted=True)],
+ {1, 2},
+ ),
+ ]
+ )
+ def test_drop_unreferenced_unevaluable_flags(self, _name, flags, expected_ids):
+ result = _drop_unreferenced_unevaluable_flags(flags)
+
+ assert {f["id"] for f in result} == expected_ids
+
+ def test_absent_active_key_keeps_flag(self):
+ # A serializer regression that stops emitting ``active`` must fail toward
+ # keeping the flag rather than silently dropping it from the payload.
+ flag = _make_flag(2, "flag_b")
+ del flag["active"]
+
+ result = _drop_unreferenced_unevaluable_flags([_make_flag(1, "flag_a"), flag])
+
+ assert {f["id"] for f in result} == {1, 2}
+
+ def test_two_hop_chain_keeps_referenced_but_drops_unreferenced_transitive(self):
+ # Active A(1) -> inactive B(2) -> inactive C(3). B is kept because A references
+ # it, but B is itself unevaluable, so its reference to C does not count: C has
+ # no evaluable referrer and is dropped.
+ flags = [
+ _make_flag(1, "flag_a", deps=[2]),
+ _make_flag(2, "flag_b", deps=[3], active=False),
+ _make_flag(3, "flag_c", active=False),
+ ]
+
+ result = _drop_unreferenced_unevaluable_flags(flags)
+
+ assert {f["id"] for f in result} == {1, 2}
+
+ def test_preserves_order(self):
+ flags = [
+ _make_flag(3, "flag_c", deps=[1]),
+ _make_flag(2, "flag_b", active=False),
+ _make_flag(1, "flag_a"),
+ ]
+
+ result = _drop_unreferenced_unevaluable_flags(flags)
+
+ assert [f["id"] for f in result] == [3, 1]
+
+
class TestComputeFlagDependencies:
def test_no_dependencies(self):
flags = [_make_flag(1, "flag_a"), _make_flag(2, "flag_b")]
@@ -3384,8 +3553,18 @@ class TestBlankInactiveFiltersInPayload(BaseTest):
disabled = FeatureFlag.objects.create(
team=self.team, key="disabled-flag", created_by=self.user, active=False, filters=self._targeting()
)
+ # An active dependent references `disabled` via a dependency property so it
+ # survives the drop step (kept, then blanked) instead of being removed as
+ # unreferenced.
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="dependent-flag",
+ created_by=self.user,
+ filters=_dependency_filters(disabled.id),
+ )
# The archived_flag_must_be_disabled constraint means archived flags are always
- # inactive, so they are blanked by the same check rather than one of their own.
+ # inactive. Unlike `disabled`, nothing references `archived`, so it is dropped
+ # from the payload entirely rather than kept-and-blanked.
archived = FeatureFlag.objects.create(
team=self.team,
key="archived-flag",
@@ -3399,10 +3578,9 @@ class TestBlankInactiveFiltersInPayload(BaseTest):
def _assert_blanked(self, flags_data, active, disabled, archived):
by_id = {f["id"]: f for f in flags_data}
- assert by_id.keys() == {active.id, disabled.id, archived.id}
+ assert archived.id not in by_id
assert by_id[active.id]["filters"] == self._targeting()
assert by_id[disabled.id]["filters"] == {"groups": []}
- assert by_id[archived.id]["filters"] == {"groups": []}
def test_single_team_payload_blanks_inactive_filters(self):
active, disabled, archived = self._create_flags()
@@ -3418,6 +3596,26 @@ class TestBlankInactiveFiltersInPayload(BaseTest):
self._assert_blanked(result[self.team.id]["flags"], active, disabled, archived)
+ def test_dropped_flag_absent_from_dependency_metadata(self):
+ # `archived` is dropped entirely (unreferenced), so it must not appear in
+ # dependency_stages or as a transitive_deps key. `disabled` is kept because
+ # `dependent-flag` references it, and that reference is what dependency
+ # metadata is built from.
+ active, disabled, archived = self._create_flags()
+
+ result = _get_feature_flags_for_service(self.team)
+ metadata = result["evaluation_metadata"]
+
+ staged_ids = {flag_id for stage in metadata["dependency_stages"] for flag_id in stage}
+ assert archived.id not in staged_ids
+ assert str(archived.id) not in metadata["transitive_deps"]
+
+ assert disabled.id in staged_ids
+ dependent = next(f for f in result["flags"] if f["key"] == "dependent-flag")
+ assert metadata["transitive_deps"][str(dependent["id"])] == [disabled.id]
+ # The referenced flag survives the drop, so no dependent is missing a dep.
+ assert metadata["flags_with_missing_deps"] == []
+
def test_dependency_on_disabled_flag_survives_blanking(self):
disabled = FeatureFlag.objects.create(
team=self.team, key="disabled-dep", created_by=self.user, active=False, filters=self._targeting()
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index 08c11c121595..b722fbf82f35 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -51,6 +51,7 @@ pub async fn build_flags_cache(
team_id: TeamId,
) -> Result<HypercacheFlagsWrapper, FlagError> {
let mut flags = FeatureFlagList::from_pg(pg_reader.clone(), team_id).await?;
+ retain_evaluable_and_referenced_flags(&mut flags);
let evaluation_metadata = compute_flag_dependencies(&flags)?;
let cohorts = fetch_referenced_cohorts(pg_reader, team_id, &flags).await?;
blank_inactive_filters(&mut flags);
@@ -73,6 +74,21 @@ fn is_evaluable(flag: &FeatureFlag) -> bool {
flag.active && !flag.deleted
}
+/// Keep the flags worth caching: evaluable ones, plus unevaluable ones that another
+/// flag's dependency conditions reference — those pre-seed as false in the matcher,
+/// so a dependent's `flag_evaluates_to: false` condition still matches.
+///
+/// Mirrors Python's `_drop_unreferenced_unevaluable_flags()` in
+/// `products/feature_flags/backend/flags_cache.py`, where the full rationale lives.
+fn retain_evaluable_and_referenced_flags(flags: &mut Vec<FeatureFlag>) {
+ let referenced_ids: HashSet<FeatureFlagId> = flags
+ .iter()
+ .flat_map(active_flag_properties)
+ .filter_map(|p| p.get_feature_flag_id())
+ .collect();
+ flags.retain(|flag| is_evaluable(flag) || referenced_ids.contains(&flag.id));
+}
+
/// Empty the `filters` of flags that can never be evaluated, so the unreachable
/// blob stops occupying Redis, S3, and the service's in-memory cache.
///
@@ -805,6 +821,75 @@ mod tests {
);
}
+ // -------------------------------------------------------------------------
+ // retain_evaluable_and_referenced_flags tests
+ // -------------------------------------------------------------------------
+
+ #[test_case(true, false, true ; "active flag kept")]
+ #[test_case(false, false, false ; "unreferenced inactive flag dropped")]
+ #[test_case(true, true, false ; "deleted flag dropped")]
+ fn test_retain_unreferenced_flag(active: bool, deleted: bool, expect_kept: bool) {
+ let mut flags = vec![make_flag(
+ 1,
+ "flag_a",
+ active,
+ vec![group_with_properties(vec![])],
+ )];
+ flags[0].deleted = deleted;
+
+ retain_evaluable_and_referenced_flags(&mut flags);
+
+ assert_eq!(flags.iter().any(|f| f.id == 1), expect_kept);
+ }
+
+ #[test]
+ fn test_retain_keeps_deleted_flag_referenced_by_active_dependent() {
+ // Mirrors Python's deleted_flag_referenced_by_active_dependent_kept case, so a
+ // Rust-only edit that drops deleted flags before consulting references fails here
+ // instead of splitting the two writers' flag sets.
+ let mut flags = vec![
+ make_flag(1, "dep", true, vec![group_with_properties(vec![])]),
+ make_flag(
+ 2,
+ "dependent",
+ true,
+ vec![group_with_properties(vec![flag_dep_property(1)])],
+ ),
+ ];
+ flags[0].deleted = true;
+
+ retain_evaluable_and_referenced_flags(&mut flags);
+
+ let ids: Vec<i32> = flags.iter().map(|f| f.id).collect();
+ assert_eq!(ids, vec![1, 2]);
+ }
+
+ #[test]
+ fn test_retain_truncates_chains_at_the_first_unevaluable_hop() {
+ // active 3 → inactive 2 → inactive 1: flag 2 stays (it pre-seeds as false
+ // for flag 3's condition); flag 1 goes (flag 2's conditions are never read).
+ let mut flags = vec![
+ make_flag(1, "tail", false, vec![group_with_properties(vec![])]),
+ make_flag(
+ 2,
+ "middle",
+ false,
+ vec![group_with_properties(vec![flag_dep_property(1)])],
+ ),
+ make_flag(
+ 3,
+ "head",
+ true,
+ vec![group_with_properties(vec![flag_dep_property(2)])],
+ ),
+ ];
+
+ retain_evaluable_and_referenced_flags(&mut flags);
+
+ let ids: Vec<i32> = flags.iter().map(|f| f.id).collect();
+ assert_eq!(ids, vec![2, 3]);
+ }
+
// -------------------------------------------------------------------------
// blank_inactive_filters tests
// -------------------------------------------------------------------------
@@ -821,8 +906,8 @@ mod tests {
)];
flags[0].deleted = deleted;
// Populated beyond `groups` so clearing only `groups` is distinguishable from a
- // full reset. A partial clear would keep keys Python never writes, splitting the
- // etag between the two writers.
+ // full reset. A partial clear would keep keys the Python writer's blank shape
+ // never has, so the two writers' entries would disagree.
flags[0].filters.payloads = Some(serde_json::json!({"true": "payload"}));
flags[0].filters.early_exit = Some(true);
let before = serde_json::to_value(&flags[0].filters).unwrap();
@@ -843,10 +928,10 @@ mod tests {
}
#[tokio::test]
- async fn test_build_flags_cache_blanks_inactive_filters() {
- // Covers the wiring rather than the helper: the two cache-writing binaries call
- // `build_flags_cache`, so an edit that stops it blanking would split the etag from
- // the Python writer while every `blank_inactive_filters` test stayed green.
+ async fn test_build_flags_cache_drops_unreferenced_and_blanks_referenced() {
+ // Covers the wiring rather than the helpers: the two cache-writing binaries call
+ // `build_flags_cache`, so an edit that stops it dropping or blanking would split
+ // the payload from the Python writer while every helper test stayed green.
let context = TestContext::new(None).await;
let team = context
.insert_new_team(None)
@@ -857,25 +942,42 @@ mod tests {
"groups": [{"properties": [], "rollout_percentage": 100}],
"payloads": {"true": "payload"},
});
- let inactive = FeatureFlagRow {
- key: "disabled-flag".to_string(),
+ let disabled_row = |key: &str| FeatureFlagRow {
+ key: key.to_string(),
active: false,
filters: targeting.clone(),
..base_flag_row(team.id)
};
- let active = FeatureFlagRow {
- key: "active-flag".to_string(),
- filters: targeting.clone(),
- ..base_flag_row(team.id)
- };
- let inactive = context
- .insert_flag(team.id, Some(inactive))
+ let referenced = context
+ .insert_flag(team.id, Some(disabled_row("referenced-disabled-flag")))
.await
- .expect("Failed to insert inactive flag");
- let active = context
- .insert_flag(team.id, Some(active))
+ .expect("Failed to insert referenced inactive flag");
+ let unreferenced = context
+ .insert_flag(team.id, Some(disabled_row("unreferenced-disabled-flag")))
.await
- .expect("Failed to insert active flag");
+ .expect("Failed to insert unreferenced inactive flag");
+ let dependent = context
+ .insert_flag(
+ team.id,
+ Some(FeatureFlagRow {
+ key: "active-flag".to_string(),
+ filters: serde_json::json!({
+ "groups": [{
+ "properties": [{
+ "key": referenced.id.to_string(),
+ "type": "flag",
+ "value": "false",
+ "operator": "flag_evaluates_to",
+ }],
+ "rollout_percentage": 100,
+ }],
+ "payloads": {"true": "payload"},
+ }),
+ ..base_flag_row(team.id)
+ }),
+ )
+ .await
+ .expect("Failed to insert dependent flag");
let wrapper = build_flags_cache(context.non_persons_reader.clone(), team.id)
.await
@@ -883,17 +985,32 @@ mod tests {
let by_id: HashMap<i32, &FeatureFlag> = wrapper.flags.iter().map(|f| (f.id, f)).collect();
assert_eq!(
- serde_json::to_value(&by_id[&inactive.id].filters).unwrap(),
+ by_id.keys().copied().collect::<HashSet<_>>(),
+ HashSet::from([referenced.id, dependent.id])
+ );
+ assert_eq!(
+ serde_json::to_value(&by_id[&referenced.id].filters).unwrap(),
serde_json::json!({"groups": []})
);
- // Asserted field-wise rather than against `targeting`, because a JSONB round trip
- // through `Option<f64>` renders `rollout_percentage` as 100.0 and serde_json holds
- // integer and float numbers unequal.
- let active_filters = &by_id[&active.id].filters;
- assert_eq!(active_filters.groups.len(), 1);
+ // Asserted field-wise rather than against the inserted JSON, because a JSONB round
+ // trip through `Option<f64>` renders `rollout_percentage` as 100.0 and serde_json
+ // holds integer and float numbers unequal.
+ let dependent_filters = &by_id[&dependent.id].filters;
+ assert_eq!(dependent_filters.groups.len(), 1);
assert_eq!(
- active_filters.payloads,
+ dependent_filters.payloads,
Some(serde_json::json!({"true": "payload"}))
);
+
+ // Metadata is computed on the post-drop set.
+ let meta = &wrapper.evaluation_metadata;
+ let staged_ids: HashSet<i32> = meta.dependency_stages.iter().flatten().copied().collect();
+ assert_eq!(staged_ids, HashSet::from([referenced.id, dependent.id]));
+ assert!(!meta.transitive_deps.contains_key(&unreferenced.id));
+ assert_eq!(
+ meta.transitive_deps[&dependent.id],
+ HashSet::from([referenced.id])
+ );
+ assert!(meta.flags_with_missing_deps.is_empty());
}
}
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index 16870cf55c1f..4c860796e298 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -1181,7 +1181,7 @@ mod tests {
);
// Verify flags parsed correctly
- assert_eq!(flags.len(), 5, "Expected 5 flags in contract fixture");
+ assert_eq!(flags.len(), 7, "Expected 7 flags in contract fixture");
// Full flag with all optional fields
let full_flag = &flags[0];
@@ -1237,14 +1237,27 @@ mod tests {
assert_eq!(missing_dep_flag.key, "missing-dep-flag");
assert_eq!(missing_dep_flag.filters.groups.len(), 1);
+ // Referenced disabled flag: both writers keep it for the dependency below,
+ // with filters blanked to the empty shape.
+ let referenced_disabled = &flags[5];
+ assert_eq!(referenced_disabled.key, "referenced-disabled-flag");
+ assert!(!referenced_disabled.active);
+ assert!(referenced_disabled.filters.groups.is_empty());
+
+ // Its dependent: an active flag whose condition points at the disabled flag.
+ let disabled_dependent = &flags[6];
+ assert_eq!(disabled_dependent.key, "disabled-dependent-flag");
+ assert_eq!(disabled_dependent.filters.groups.len(), 1);
+
// Verify evaluation_metadata parsed correctly
let meta = metadata;
assert_eq!(meta.dependency_stages.len(), 2);
- assert_eq!(meta.dependency_stages[0], vec![1, 2, 3, 5]);
- assert_eq!(meta.dependency_stages[1], vec![4]);
+ assert_eq!(meta.dependency_stages[0], vec![1, 2, 3, 5, 6]);
+ assert_eq!(meta.dependency_stages[1], vec![4, 7]);
assert_eq!(meta.flags_with_missing_deps, vec![5]);
- assert_eq!(meta.transitive_deps.len(), 5);
+ assert_eq!(meta.transitive_deps.len(), 7);
assert!(meta.transitive_deps[&4].contains(&2));
+ assert!(meta.transitive_deps[&7].contains(&6));
// Verify cohorts parsed correctly
let cohorts = cohorts.expect("cohorts should be present in contract fixture");
diff --git a/rust/feature-flags/tests/fixtures/hypercache_contract.json b/rust/feature-flags/tests/fixtures/hypercache_contract.json
index bea8259d3432..415071c4078f 100644
--- a/rust/feature-flags/tests/fixtures/hypercache_contract.json
+++ b/rust/feature-flags/tests/fixtures/hypercache_contract.json
@@ -179,12 +179,62 @@
"evaluation_runtime": "all",
"bucketing_identifier": null,
"evaluation_contexts": []
+ },
+ {
+ "id": 6,
+ "team_id": 99,
+ "name": "Referenced disabled flag",
+ "key": "referenced-disabled-flag",
+ "has_experiment": false,
+ "filters": {
+ "groups": []
+ },
+ "deleted": false,
+ "active": false,
+ "ensure_experience_continuity": false,
+ "version": 1,
+ "evaluation_runtime": "all",
+ "bucketing_identifier": null,
+ "evaluation_contexts": []
+ },
+ {
+ "id": 7,
+ "team_id": 99,
+ "name": "Dependent on disabled flag",
+ "key": "disabled-dependent-flag",
+ "has_experiment": false,
+ "filters": {
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": "6",
+ "label": "referenced-disabled-flag",
+ "operator": "flag_evaluates_to",
+ "type": "flag",
+ "value": false
+ }
+ ],
+ "rollout_percentage": 100,
+ "variant": null
+ }
+ ],
+ "multivariate": null,
+ "payloads": {}
+ },
+ "deleted": false,
+ "active": true,
+ "ensure_experience_continuity": false,
+ "version": 1,
+ "evaluation_runtime": "all",
+ "bucketing_identifier": null,
+ "evaluation_contexts": []
}
],
"evaluation_metadata": {
"dependency_stages": [
- [1, 2, 3, 5],
- [4]
+ [1, 2, 3, 5, 6],
+ [4, 7]
],
"flags_with_missing_deps": [5],
"transitive_deps": {
@@ -192,7 +242,9 @@
"2": [],
"3": [],
"4": [2],
- "5": []
+ "5": [],
+ "6": [],
+ "7": [6]
}
},
"cohorts": [