: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
perf(flags): drop unreachable filters from cached inactive flags (#81463)
Phil Haack2448e460fe93
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 58e9e4dc8928..1ffcf202bae9 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -115,6 +115,14 @@ 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.+### Cache payload structure```jsondiff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 2c7e067d53a2..ebbea41fc506 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -74,6 +74,23 @@ logger = structlog.get_logger(__name__)FLAGS_CACHE_EXPIRY_SORTED_SET = "flags_cache_expiry"+def _is_unevaluable(flag_data: dict[str, Any]) -> bool:+ """Whether ``active``/``deleted`` make the matcher skip this serialized flag before+ it reads the filters.++ The matcher filters out more flags per request (survey, evaluation runtime,+ evaluation contexts), but those are request-scoped and must not gate what gets+ written to a cache shared by every request.++ Inverse of ``is_evaluable`` in rust/feature-flags/src/flags/cache_builder.rs. A+ flag missing ``active`` counts as evaluable so a serializer regression leaves the+ targeting in the payload instead of overwriting it. That protects the bytes only:+ Rust's ``FeatureFlag.active`` is ``#[serde(default)]``, so a payload without the+ field reads as inactive there and is filtered out regardless.+ """+ return not flag_data.get("active", True) or flag_data.get("deleted", False)++def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:"""Extract direct flag dependency IDs from a serialized flag's filters.@@ -82,7 +99,7 @@ def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:their key as an integer flag ID. Inactive/deleted flags return empty depsto match Rust's extract_dependencies behavior."""- if not flag_data.get("active", True) or flag_data.get("deleted", False):+ if _is_unevaluable(flag_data):return set()dep_ids: set[int] = set()@@ -135,7 +152,7 @@ def _extract_cohort_ids_from_flag_filters(flags_data: list[dict[str, Any]]) -> s"""cohort_ids: set[int] = set()for flag in flags_data:- if not flag.get("active", True) or flag.get("deleted", False):+ if _is_unevaluable(flag):continuefor group in flag.get("filters", {}).get("groups") or []:for prop in group.get("properties") or []:@@ -326,6 +343,43 @@ def _compute_flag_dependencies(flags_data: list[dict[str, Any]]) -> dict[str, An}+def _blank_inactive_filters(flags_data: list[dict[str, Any]]) -> None:+ """Empty the ``filters`` of flags that can never be evaluated, in place.++ The matcher skips these flags before it reads filters, so the blob is+ unreachable weight in Redis, in S3, and in the service's in-memory cache. The+ flag entry itself stays, so a dependency condition on it still resolves to+ false rather than raising DependencyNotFound.++ Order-independent: dependency and cohort extraction guard on ``_is_unevaluable``+ themselves.++ Not folded into ``serialize_feature_flags``, which+ ``set_feature_flags_for_team_in_cache`` also uses to populate the separate+ legacy ``team_feature_flags_{project_id}`` cache.+ """+ for flag in flags_data:+ 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.+ 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.++ Blanking lives here so no writer can assemble a payload without it. The Rust side+ reaches the same point through a single ``build_flags_cache``.+ """+ _blank_inactive_filters(flags_data)+ return {"flags": flags_data, "evaluation_metadata": evaluation_metadata, "cohorts": cohorts}++def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:"""Get feature flags for the feature-flags service.@@ -362,8 +416,7 @@ def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:cohort_count=len(cohorts),)- # Wrap in dict for HyperCache compatibility- return {"flags": flags_data, "evaluation_metadata": evaluation_metadata, "cohorts": cohorts}+ return _build_flags_payload(flags_data, evaluation_metadata, cohorts)def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str, Any]]:@@ -450,11 +503,7 @@ def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str,cohort_count=len(team_cohorts),)- result[team.id] = {- "flags": flags_data,- "evaluation_metadata": evaluation_metadata,- "cohorts": team_cohorts,- }+ result[team.id] = _build_flags_payload(flags_data, evaluation_metadata, team_cohorts)return result@@ -637,7 +686,7 @@ def verify_team_flags(if flag_id in cached_flags_by_id:db_flag = db_flags_by_id[flag_id]cached_flag = cached_flags_by_id[flag_id]- field_diffs = _compare_flag_fields(db_flag, cached_flag)+ field_diffs = _compare_flag_fields(db_flag, cached_flag, tolerate_blanked_filters=True)if field_diffs:diff = {"type": "FIELD_MISMATCH",@@ -743,7 +792,7 @@ def _strip_null_values(value: Any, in_group_level_list: bool = False) -> Any:return value-def _compare_flag_fields(db_flag: dict, cached_flag: dict) -> list[dict]:+def _compare_flag_fields(db_flag: dict, cached_flag: dict, *, tolerate_blanked_filters: bool = False) -> list[dict]:"""Compare field values between DB and cached versions of a flag.The DB serialization is treated as the source of truth: only keys present in@@ -759,10 +808,26 @@ def _compare_flag_fields(db_flag: dict, cached_flag: dict) -> list[dict]:are compared directly; ``MinimalFeatureFlagSerializer`` emits all top-levelkeys explicitly today, so there is no top-level absent/null divergence totolerate. See plans/verify-flags-cache-loose-comparison.md.++ ``tolerate_blanked_filters`` exempts ``filters`` when both sides agree the flag+ is unevaluable. Only the ``flags.json`` writers blank those filters, and entries+ predating that still hold the full blob while the two writers deploy+ independently, so the blob and ``{"groups": []}`` both occur and the matcher+ ignores either one. It is opt-in because ``local_evaluation`` shares this+ function for ``flags_with_cohorts.json``, which has a single writer and no+ blanking: there any ``filters`` difference is real drift worth repairing. A+ disagreement about ``active`` itself is reported in both modes."""field_diffs = []+ # Mirrors the writers' own predicate so a flag they blank is never reported as+ # unfixable drift.+ both_unevaluable = tolerate_blanked_filters and _is_unevaluable(db_flag) and _is_unevaluable(cached_flag)+for key in db_flag.keys():+ if key == "filters" and both_unevaluable:+ continue+db_val = db_flag[key]cached_val = cached_flag.get(key)diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 16c48fe58ab0..fb6758e5db0b 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -8,6 +8,7 @@ Tests cover:- Data format compatibility with service"""+import copyimport jsonfrom datetime import UTC, datetimefrom pathlib import Path@@ -33,6 +34,7 @@ from posthog.storage.cache_expiry_manager import CacheRefreshCountsfrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import (+ _blank_inactive_filters,_compare_flag_fields,_compute_flag_dependencies,_extract_cohort_ids_from_flag_filters,@@ -3121,6 +3123,39 @@ class TestExtractDirectDependencyIds:assert _extract_direct_dependency_ids(flag) == expected+class TestBlankInactiveFilters:+ @parameterized.expand(+ [+ ("active_flag_keeps_filters", _make_flag(1, "flag_a", deps=[2]), False),+ ("inactive_flag_blanked", _make_flag(1, "flag_a", deps=[2], active=False), True),+ ("deleted_flag_blanked", _make_flag(1, "flag_a", deps=[2], deleted=True), True),+ ]+ )+ 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.+ flag["filters"]["payloads"] = {"true": "payload"}+ original_filters = copy.deepcopy(flag["filters"])++ _blank_inactive_filters([flag])++ if expect_blanked:+ assert flag["filters"] == {"groups": []}+ else:+ assert flag["filters"] == original_filters++ def test_absent_active_key_keeps_filters(self):+ # A serializer that stops emitting ``active`` must not overwrite every flag's+ # targeting in the payload, so the default fails toward keeping filters.+ flag = _make_flag(1, "flag_a", deps=[2])+ del flag["active"]+ original_filters = copy.deepcopy(flag["filters"])++ _blank_inactive_filters([flag])++ assert flag["filters"] == original_filters++class TestComputeFlagDependencies:def test_no_dependencies(self):flags = [_make_flag(1, "flag_a"), _make_flag(2, "flag_b")]@@ -3335,6 +3370,82 @@ class TestComputeFlagDependenciesIntegration(BaseTest):assert ctx["dependency_stages"] == [[flag_c.id], [flag_b.id], [flag_a.id]]+@override_settings(FLAGS_REDIS_URL="redis://test")+class TestBlankInactiveFiltersInPayload(BaseTest):+ def _targeting(self):+ # `payloads` makes the blanked assertions prove the whole dict was replaced rather+ # than just `groups` emptied, which would leave keys the Rust writer drops.+ return {"groups": [{"properties": [], "rollout_percentage": 100}], "payloads": {"true": "payload"}}++ def _create_flags(self):+ active = FeatureFlag.objects.create(+ team=self.team, key="active-flag", created_by=self.user, filters=self._targeting()+ )+ disabled = FeatureFlag.objects.create(+ team=self.team, key="disabled-flag", created_by=self.user, active=False, filters=self._targeting()+ )+ # 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.+ archived = FeatureFlag.objects.create(+ team=self.team,+ key="archived-flag",+ created_by=self.user,+ active=False,+ archived=True,+ filters=self._targeting(),+ )+ return active, disabled, archived++ 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 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()++ result = _get_feature_flags_for_service(self.team)++ self._assert_blanked(result["flags"], active, disabled, archived)++ def test_batch_payload_blanks_inactive_filters(self):+ active, disabled, archived = self._create_flags()++ result = _get_feature_flags_for_teams_batch([self.team])++ self._assert_blanked(result[self.team.id]["flags"], active, disabled, archived)++ 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()+ )+ dependent = FeatureFlag.objects.create(+ team=self.team,+ key="dependent",+ created_by=self.user,+ filters={+ "groups": [+ {+ "properties": [+ {"type": "flag", "key": str(disabled.id), "value": ["true"], "operator": "exact"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )++ result = _get_feature_flags_for_service(self.team)++ # The disabled flag keeps its entry so the matcher can seed it as false rather+ # than failing the dependent flag with DependencyNotFound.+ assert {f["id"] for f in result["flags"]} == {disabled.id, dependent.id}+ assert result["evaluation_metadata"]["transitive_deps"][str(dependent.id)] == [disabled.id]++@override_settings(FLAGS_REDIS_URL="redis://test")class TestExtractCohortIdsFromFlagFilters(BaseTest):def test_extracts_cohort_ids_from_active_flag(self):@@ -3984,3 +4095,35 @@ class TestCompareFlagFieldsLooseness(unittest.TestCase):diffs = _compare_flag_fields(db_flag, cached_flag)self.assertEqual(len(diffs), 1)self.assertEqual(diffs[0]["field"], expected_field)++ def test_blanked_filters_tolerance_is_opt_in(self) -> None:+ # flags.json blanks an inactive flag's filters, so an entry still holding the full+ # blob is not drift there. flags_with_cohorts.json shares this function and never+ # blanks, so the same difference is real drift that a repair can settle.+ db_flag = _flag(active=False, filters={"groups": []})+ cached_flag = _flag(active=False, filters={"groups": [{"properties": [], "rollout_percentage": 100}]})++ self.assertEqual(_compare_flag_fields(db_flag, cached_flag, tolerate_blanked_filters=True), [])++ diffs = _compare_flag_fields(db_flag, cached_flag)+ self.assertEqual([d["field"] for d in diffs], ["filters"])++ @parameterized.expand(+ [+ # Even with the tolerance on, only a flag both sides agree is inactive gets it.+ # An active flag's filters are what the matcher evaluates, and a cache entry+ # still marked inactive after the flag was re-enabled is stale, so suppressing+ # either would hide targeting the matcher is using.+ ("both_active", True, True, {"filters"}),+ ("reenabled_but_cache_stale", True, False, {"active", "filters"}),+ ]+ )+ def test_tolerance_only_applies_when_both_sides_are_inactive(+ self, _name: str, db_active: bool, cached_active: bool, expected_fields: set[str]+ ) -> None:+ db_flag = _flag(active=db_active, filters={"groups": [{"properties": [], "rollout_percentage": 100}]})+ cached_flag = _flag(active=cached_active, filters={"groups": []})++ diffs = _compare_flag_fields(db_flag, cached_flag, tolerate_blanked_filters=True)++ self.assertEqual({d["field"] for d in diffs}, expected_fields)diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rsindex 67796ef25108..08c11c121595 100644--- a/rust/feature-flags/src/flags/cache_builder.rs+++ b/rust/feature-flags/src/flags/cache_builder.rs@@ -13,7 +13,8 @@ use common_types::TeamId;use crate::api::errors::FlagError;use crate::cohorts::cohort_models::{Cohort, CohortId};use crate::flags::flag_models::{- EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList, HypercacheFlagsWrapper,+ EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters,+ HypercacheFlagsWrapper,};use crate::properties::property_models::PropertyFilter;use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};@@ -49,9 +50,10 @@ pub async fn build_flags_cache(pg_reader: PostgresReader,team_id: TeamId,) -> Result<HypercacheFlagsWrapper, FlagError> {- let flags = FeatureFlagList::from_pg(pg_reader.clone(), team_id).await?;+ let mut flags = FeatureFlagList::from_pg(pg_reader.clone(), team_id).await?;let evaluation_metadata = compute_flag_dependencies(&flags)?;let cohorts = fetch_referenced_cohorts(pg_reader, team_id, &flags).await?;+ blank_inactive_filters(&mut flags);Ok(HypercacheFlagsWrapper {flags,@@ -60,9 +62,31 @@ pub async fn build_flags_cache(})}+/// Whether `active`/`deleted` let the matcher evaluate this flag. Anything failing this+/// lands in `filtered_out_flag_ids` before `filters` is read, so its filters cannot+/// affect a response.+///+/// Do not widen this to the rest of that set (survey, evaluation runtime, evaluation+/// contexts): those are request-scoped, so blanking on them would strip targeting that+/// other requests still need.+fn is_evaluable(flag: &FeatureFlag) -> bool {+ flag.active && !flag.deleted+}++/// 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.+///+/// Mirrors Python's `_blank_inactive_filters()` in+/// `products/feature_flags/backend/flags_cache.py`.+fn blank_inactive_filters(flags: &mut [FeatureFlag]) {+ for flag in flags.iter_mut().filter(|f| !is_evaluable(f)) {+ flag.filters = FlagFilters::default();+ }+}+/// Yields all property filters from an active, non-deleted flag's filter groups.fn active_flag_properties(flag: &FeatureFlag) -> impl Iterator<Item = &PropertyFilter> {- let groups = if flag.active && !flag.deleted {+ let groups = if is_evaluable(flag) {flag.filters.groups.as_slice()} else {&[]@@ -221,10 +245,24 @@ async fn load_cohorts_with_deps(#[cfg(test)]mod tests {use super::*;- use crate::flags::flag_models::{FlagFilters, FlagPropertyGroup};+ use crate::flags::flag_models::{FeatureFlagRow, FlagFilters, FlagPropertyGroup};use crate::properties::property_models::{OperatorType, PropertyFilter, PropertyType};+ use crate::utils::test_utils::TestContext;use test_case::test_case;+ /// A minimal insertable flag row. `id` is a placeholder; the insert helper returns the+ /// row with the real id.+ fn base_flag_row(team_id: i32) -> FeatureFlagRow {+ FeatureFlagRow {+ team_id,+ active: true,+ // `posthog_featureflag.name` is NOT NULL.+ name: Some(String::new()),+ evaluation_runtime: Some("all".to_string()),+ ..Default::default()+ }+ }+fn make_flag(id: i32, key: &str, active: bool, groups: Vec<FlagPropertyGroup>) -> FeatureFlag {FeatureFlag {id,@@ -766,4 +804,96 @@ mod tests {wrapper.evaluation_metadata.transitive_deps);}++ // -------------------------------------------------------------------------+ // blank_inactive_filters tests+ // -------------------------------------------------------------------------++ #[test_case(true, false, false ; "active flag keeps its filters")]+ #[test_case(false, false, true ; "inactive flag is blanked")]+ #[test_case(true, true, true ; "deleted flag is blanked")]+ fn test_blank_inactive_filters(active: bool, deleted: bool, expect_blanked: bool) {+ let mut flags = vec![make_flag(+ 1,+ "flag_a",+ active,+ vec![group_with_properties(vec![flag_dep_property(2)])],+ )];+ 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.+ 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();++ blank_inactive_filters(&mut flags);++ let after = serde_json::to_value(&flags[0].filters).unwrap();+ if expect_blanked {+ // Python's `_blank_inactive_filters()` writes exactly this into the same+ // hypercache entry. If this fails, reconcile the literal in that function+ // (products/feature_flags/backend/flags_cache.py) with this shape.+ assert_eq!(after, serde_json::json!({"groups": []}));+ } else {+ assert_eq!(after, before);+ }+ // The entry has to survive so a dependency on it seeds as false in the matcher.+ assert_eq!(flags[0].id, 1);+ }++ #[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.+ let context = TestContext::new(None).await;+ let team = context+ .insert_new_team(None)+ .await+ .expect("Failed to insert team");++ let targeting = serde_json::json!({+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": "payload"},+ });+ let inactive = FeatureFlagRow {+ key: "disabled-flag".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))+ .await+ .expect("Failed to insert inactive flag");+ let active = context+ .insert_flag(team.id, Some(active))+ .await+ .expect("Failed to insert active flag");++ let wrapper = build_flags_cache(context.non_persons_reader.clone(), team.id)+ .await+ .expect("Failed to build flags cache");++ 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(),+ 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);+ assert_eq!(+ active_filters.payloads,+ Some(serde_json::json!({"true": "payload"}))+ );+ }}