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): omit unsupported configs from the internal flags cache (#104427)

Anders3ecb810f818a
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index b2d370503d40..8123284693fd 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -47,9 +47,7 @@ Each recognized v2 ingress increments `flags_v2_config_parse_total` with a fixed
These outcomes cover cache and PostgreSQL reads and contain no configuration values.
The internal batch evaluation endpoint rejects a non-v1 target with HTTP 400 and `unsupported_config_format` before it pages the team, so cohort generation treats the failure as permanent.
-The Rust cache builder fails a team's rebuild on an evaluable non-v1 document, the way Python does.
-The cache builder consumer labels flag data parsing failures `config_format` in metrics and dead-letter queue headers and sends them to that queue without retrying.
-Inactive and deleted non-v1 flags do not fail the team's rebuild.
+The Rust and Python cache builders omit a non-v1 flag and its dependents instead of failing the team's rebuild, as the [service cache section](./hypercache-system.md#service-cache-rust) describes.
`/remote_config` stays outside this boundary: it reads `filters.payloads["true"]` raw, as Django's shadow-compared view does.
This boundary does not make legacy definitions producers or older cache writers safe for persisted v2 rows.
Those paths need independent exclusion and deployment-floor protection before such rows can exist.
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 20c37e26eea7..ec619976a8a7 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -95,12 +95,12 @@ ETags are computed as SHA256 hashes of the JSON content.
## Service cache (Rust)
-The feature-flags Rust evaluation service uses a separate HyperCache instance defined in `posthog/models/feature_flag/flags_cache.py`. Unlike the local evaluation cache (which serves SDKs with cohort definitions and group type mappings), the service cache provides raw flag data plus pre-computed dependency metadata so the Rust service can evaluate flags in the correct order without recomputing the dependency graph on every request.
+The feature-flags Rust evaluation service uses a separate HyperCache instance defined in `products/feature_flags/backend/flags_cache.py`. Unlike the local evaluation cache (which serves SDKs with cohort definitions and group type mappings), the service cache provides raw flag data plus pre-computed dependency metadata so the Rust service can evaluate flags in the correct order without recomputing the dependency graph on every request.
### Cache instance
```python
-# posthog/models/feature_flag/flags_cache.py
+# products/feature_flags/backend/flags_cache.py
flags_hypercache = HyperCache(
namespace="feature_flags",
value="flags.json",
@@ -115,14 +115,23 @@ 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), 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`.
-Cohort references and flag dependencies are read from each flag's `filters` through `products/feature_flags/backend/facade/references.py`, which runs `detect_config_format` before it reads a v1 key.
-A flag stored in any other config format raises `ConfigFormatError` rather than reading as a flag with no references; in this cache that fails the team's rebuild the way any malformed document does, and `HyperCache.update_cache` keeps the existing entry and ETag.
-Inactive and deleted flags are skipped before that read (`_is_unevaluable`), so they are not classified.
+Before anything serializes or reads a flag, `_omit_unsupported_flags` classifies each stored `filters` document with `detect_config_format` (`products/feature_flags/backend/facade/config.py`).
+Only a config version 1 document (no `version`, or a numeric 1) is published.
+A v2 document, an unsupported discriminator, a document that is not a JSON object, or an evaluable v1 document whose release conditions cannot be read is omitted, together with every flag whose dependency conditions reference it, transitively.
+That applies to inactive and archived rows too, so an inactive v2 or non-object row is never blanked into a v1-shaped `{"groups": []}` entry, and a dependent with `flag_evaluates_to: false` on it never matches against a target the matcher never evaluated.
+The rebuild still succeeds with the remaining flags, the stored rows are not modified, and the omitted ids are logged.
+Unevaluable v1 rows are not read (`_is_unevaluable`), so a disabled row with an unreadable document keeps its established behavior: kept and blanked when referenced, dropped otherwise.
+Cohort references and flag dependencies are then read from the surviving flags' `filters` through `products/feature_flags/backend/facade/references.py`.
-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.
+Because inactive flags are filtered 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, blanking, and config-format rejection: an evaluable non-v1 document fails that team's build there too, so the two writers cannot publish different answers for the same row.
+`build_flags_cache` in `rust/feature-flags/src/flags/cache_builder.rs` writes the same entry and applies the same omission, drop, and blanking rule: `omit_unsupported_flags` classifies the raw documents that `from_pg_keeping_undecodable` loads.
+Both builders run the same fixture, `rust/feature-flags/tests/fixtures/flags_cache_config_formats.json`.
+One known divergence remains: Rust decodes v1 documents into typed structs, so an evaluable row it cannot decode (a property filter without a `type` key, for example) is omitted there with its dependents, while Python, which only reads the cohort and flag references, still publishes it.
+`verify_team_flags` reports and repairs such a team, attributed to the writer that produced it.
+An entry written before this rule can hold an inactive non-v1 row already blanked to `{"groups": []}`; its cached bytes cannot recover the original format, so the entry is rebuilt from the database rows by the next invalidation, refresh sweep, or verifier repair rather than reclassified in place.
+Until then an unreferenced blanked row is inert for the matcher, and an active dependent of one reports as `STALE_IN_CACHE` and triggers the repair.
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.
Verifier fixes on the flags cache carry a `writer` label (`posthog_hypercache_verify_fixes_total{cache_type="flags", writer="rust"|"python"|"unknown"}`), attributed by evaluating the same routing flag (`get_team_primary_flags_writer` in `flags_cache.py`): a fix on a rust-routed team is the parity signal that the Rust builder diverged, which the unattributed counter blends into Python's baseline repair noise. `unknown` means the routing flag couldn't be evaluated at fix time, so an attribution outage can't masquerade as a clean Rust ramp.
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.
@@ -592,7 +601,7 @@ Django signals automatically invalidate the cache when models change.
All signal handlers use `transaction.on_commit()` to avoid race conditions:
```python
-# posthog/models/feature_flag/flags_cache.py
+# products/feature_flags/backend/flags_cache.py
@receiver([post_save, post_delete], sender=FeatureFlag)
def feature_flag_changed_flags_cache(sender, instance, **kwargs):
transaction.on_commit(lambda: update_team_service_flags_cache.delay(instance.team_id))
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 09ed364c472e..d3df3ebaf485 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -26,7 +26,8 @@ Manual operations:
clear_flags_cache(team_id)
"""
-from collections import defaultdict
+from collections import defaultdict, deque
+from collections.abc import Mapping
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal
@@ -67,10 +68,12 @@ from posthog.storage.hypercache_manager import (
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.dependencies import extract_cohort_dependencies
from products.experiments.backend.models.experiment import Experiment, live_experiment_exists
+from products.feature_flags.backend.facade.config import detect_config_format
from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_ids
from products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidation
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags
+from products.feature_flags.backend.types import FlagProperty
logger = structlog.get_logger(__name__)
@@ -95,26 +98,89 @@ def _is_unevaluable(flag_data: dict[str, Any]) -> bool:
return not flag_data.get("active", True) or flag_data.get("deleted", False)
+def _parse_dependency_ids(properties: list[FlagProperty]) -> set[int]:
+ """The integer flag ids the flag-reference properties name; any other ``key`` is skipped."""
+ dep_ids: set[int] = set()
+ for prop in properties:
+ try:
+ dep_ids.add(int(prop["key"]))
+ except (ValueError, KeyError, TypeError):
+ continue
+ return dep_ids
+
+
def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:
"""
Extract direct flag dependency IDs from a serialized flag's filters.
- Parses the ``key`` of each flag-reference property as an integer flag ID.
Inactive/deleted flags return empty deps before their filters are read, to
- match Rust's extract_dependencies behavior. Any other flag stored in a config
- format other than version 1 raises ``ConfigFormatError``, which fails the whole
- team's rebuild; ``HyperCache.update_cache`` then keeps the previous entry and ETag.
+ match Rust's extract_dependencies behavior. Only flags that passed
+ ``_omit_unsupported_flags`` are serialized, so every other document here is a
+ readable config version 1.
"""
if _is_unevaluable(flag_data):
return set()
+ return _parse_dependency_ids(flag_dependency_properties(flag_data.get("filters", {})))
- dep_ids: set[int] = set()
- for prop in flag_dependency_properties(flag_data.get("filters", {})):
- try:
- dep_ids.add(int(prop["key"]))
- except (ValueError, KeyError, TypeError):
+
+def _stored_dependency_ids(flag: FeatureFlag) -> set[int] | None:
+ """The flag ids a stored row's release conditions reference, or ``None`` when this
+ cache cannot carry the row.
+
+ A non-object or non-v1 document is rejected whatever the row's lifecycle, so an
+ inactive v2 row is never blanked into a v1-shaped entry. An unevaluable v1 object is
+ not read, since ``_blank_inactive_filters`` empties it; an evaluable one whose
+ conditions cannot be read is rejected instead of failing the team.
+ """
+ filters = flag.filters
+ if not isinstance(filters, Mapping):
+ return None
+ if detect_config_format(filters).kind != "v1":
+ return None
+ if not flag.active or flag.deleted:
+ return set()
+ try:
+ return _parse_dependency_ids(flag_dependency_properties(filters))
+ except (AttributeError, TypeError):
+ return None
+
+
+def _omit_unsupported_flags(team_id: int, flags: list[FeatureFlag]) -> list[FeatureFlag]:
+ """Drop the stored rows this cache cannot carry, and the rows whose dependency
+ conditions reference one, transitively.
+
+ A dependent goes with its target because the matcher pre-seeds every kept
+ unevaluable id as false: an unsupported target left in that bucket would satisfy a
+ ``flag_evaluates_to: false`` condition it never evaluated, and one dropped without
+ its dependents would leave them resolving a missing dependency. Ordinary inactive v1
+ targets keep their established kept-and-seeded-false behavior. Stored rows are not
+ modified; ``build_flags_cache`` in rust/feature-flags/src/flags/cache_builder.rs
+ applies the same rules, so both writers publish the same flag set.
+ """
+ excluded: set[int] = set()
+ dependents: dict[int, set[int]] = defaultdict(set)
+ for flag in flags:
+ dependency_ids = _stored_dependency_ids(flag)
+ if dependency_ids is None:
+ excluded.add(flag.id)
continue
- return dep_ids
+ for dependency_id in dependency_ids:
+ dependents[dependency_id].add(flag.id)
+ unsupported = sorted(excluded)
+ queue = deque(excluded)
+ while queue:
+ for dependent_id in dependents.get(queue.popleft(), ()):
+ if dependent_id not in excluded:
+ excluded.add(dependent_id)
+ queue.append(dependent_id)
+ if excluded:
+ logger.warning(
+ "Omitted flags the service cache cannot carry",
+ team_id=team_id,
+ unsupported_flag_ids=unsupported,
+ dependent_flag_ids=sorted(excluded.difference(unsupported)),
+ )
+ return [flag for flag in flags if flag.id not in excluded]
# Cohort model fields that change only during recalculation, not definition edits.
@@ -148,9 +214,8 @@ _COHORT_RECALCULATION_FIELDS = frozenset(
def _extract_cohort_ids_from_flag_filters(flags_data: list[dict[str, Any]]) -> set[int]:
"""Extract cohort IDs directly referenced in active flag filters.
- Inactive/deleted flags are skipped before their filters are read. Any other flag
- stored in a config format other than version 1 raises ``ConfigFormatError``,
- which fails the whole team's rebuild.
+ Inactive/deleted flags are skipped before their filters are read; every other
+ flag here passed ``_omit_unsupported_flags``.
"""
cohort_ids: set[int] = set()
for flag in flags_data:
@@ -407,7 +472,8 @@ def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:
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.
+ key as a list of flag dictionaries. Rows stored in a config format this cache
+ cannot carry, and their dependents, are omitted (``_omit_unsupported_flags``).
Encrypted remote config flags are excluded since they can only be accessed via
the dedicated /remote_config endpoint which handles decryption. Including them
@@ -419,7 +485,7 @@ def _get_feature_flags_for_service(team: Team) -> dict[str, Any]:
dependency metadata (stages, missing deps, transitive deps), and cohorts contains
serialized cohort definitions referenced by the flags (including transitive deps).
"""
- flags = get_feature_flags(team=team, exclude_encrypted_payloads=True)
+ flags = _omit_unsupported_flags(team.id, get_feature_flags(team=team, exclude_encrypted_payloads=True))
flags_data = serialize_feature_flags(flags)
cohorts = _get_referenced_cohorts(team.id, flags_data)
payload = _build_flags_payload(flags_data, cohorts)
@@ -491,7 +557,7 @@ def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str,
flags_data_by_team: dict[int, list[dict[str, Any]]] = {}
all_cohort_ids: set[int] = set()
for team in teams:
- team_flags = flags_by_team_id.get(team.id, [])
+ team_flags = _omit_unsupported_flags(team.id, flags_by_team_id.get(team.id, []))
flags_data = serialize_feature_flags(team_flags)
flags_data_by_team[team.id] = flags_data
all_cohort_ids.update(_extract_cohort_ids_from_flag_filters(flags_data))
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index 47a1adc6ae88..2fba92a16df1 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -22,10 +22,12 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core.management.base import OutputWrapper
from django.db import connection
+from django.db.models import JSONField, Value
from django.test import SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
+from structlog.testing import capture_logs
from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATION
from posthog.models import Team
@@ -576,7 +578,7 @@ class TestServiceFlagsCache(BaseTest):
flag.refresh_from_db()
assert flag.filters == stored_filters
- def test_update_flags_cache_keeps_existing_entry_when_a_flag_has_unsupported_format(self):
+ def test_update_flags_cache_publishes_without_unsupported_flag_and_its_dependent(self):
FeatureFlag.objects.create(
team=self.team,
key="v1-flag",
@@ -587,22 +589,191 @@ class TestServiceFlagsCache(BaseTest):
etag_before = flags_hypercache.get_etag(self.team)
# A v2 discriminator over v1-looking groups: reading it as v1 would publish the
- # document into the service payload instead of failing this team's rebuild.
+ # document into the service payload, and failing the team would freeze v1-flag's
+ # cached targeting at whatever it was before the row arrived.
unsupported_filters = {"version": 2, "groups": [{"properties": [], "rollout_percentage": 100}]}
unsupported = FeatureFlag.objects.create(
team=self.team, key="unsupported-format", created_by=self.user, filters=unsupported_filters
)
+ FeatureFlag.objects.create(
+ team=self.team, key="dependent", created_by=self.user, filters=_dependency_filters(unsupported.id)
+ )
- assert update_flags_cache(self.team) is False
+ assert update_flags_cache(self.team) is True
cached = get_flags_from_cache(self.team)
assert cached is not None
assert [f["key"] for f in cached] == ["v1-flag"]
+ # The published bytes are those of the v1-only team, so the content ETag is unchanged.
assert flags_hypercache.get_etag(self.team) == etag_before
unsupported.refresh_from_db()
assert unsupported.filters == unsupported_filters
+def _insert_config_format_fixture(team: Team, user) -> tuple[dict, dict[str, FeatureFlag]]:
+ fixture = json.loads(
+ (_REPO_ROOT / "rust" / "feature-flags" / "tests" / "fixtures" / "flags_cache_config_formats.json").read_text()
+ )
+ flags = {
+ row["key"]: FeatureFlag.objects.create(
+ team=team,
+ key=row["key"],
+ created_by=user,
+ active=row["active"],
+ archived=row.get("archived", False),
+ filters={},
+ )
+ for row in fixture["flags"]
+ }
+ for row in fixture["flags"]:
+ filters = copy.deepcopy(row["filters"])
+ groups = filters.get("groups") if isinstance(filters, dict) else None
+ for group in groups if isinstance(groups, list) else []:
+ for prop in group.get("properties") or []:
+ if prop.get("type") == "flag":
+ reference = prop["key"]
+ prop["key"] = str(
+ fixture["missing_dependency_id"] if reference == "$missing" else flags[reference].id
+ )
+ flags[row["key"]].filters = filters
+ # Written like a stored row, past the model save hooks that assume a v1 document.
+ # A JSON null needs an expression, or the ORM writes SQL NULL and the column refuses it.
+ FeatureFlag.objects.filter(id=flags[row["key"]].id).update(
+ filters=Value(None, output_field=JSONField()) if filters is None else filters
+ )
+ return fixture, flags
+
+
+@override_settings(FLAGS_REDIS_URL="redis://test")
+class TestOmitUnsupportedFlags(BaseTest):
+ def setUp(self):
+ super().setUp()
+ clear_flags_cache(self.team, kinds=["redis", "s3"])
+
+ def _assert_fixture_payload(self, payload: dict, fixture: dict, flags: dict[str, FeatureFlag]) -> None:
+ published = {f["id"]: f for f in payload["flags"]}
+ assert {f["key"] for f in payload["flags"]} == {r["key"] for r in fixture["flags"] if r["expect"] == "kept"}
+ for row in fixture["flags"]:
+ if row["expect"] != "kept":
+ continue
+ filters = published[flags[row["key"]].id]["filters"]
+ if row.get("blanked"):
+ assert filters == {"groups": []}, row["key"]
+ else:
+ assert filters == flags[row["key"]].filters, row["key"]
+
+ metadata = payload["evaluation_metadata"]
+ expected_missing = sorted(flags[r["key"]].id for r in fixture["flags"] if r.get("missing_dependency"))
+ assert metadata["flags_with_missing_deps"] == expected_missing
+ staged = {flag_id for stage in metadata["dependency_stages"] for flag_id in stage}
+ assert staged == set(published) - {flags["cycle-a"].id, flags["cycle-b"].id}
+ assert metadata["transitive_deps"][str(flags["depends-true-on-v1-true"].id)] == [flags["v1-boolean-true"].id]
+
+ def test_single_and_batch_builders_omit_unsupported_configs_and_their_dependents(self):
+ fixture, flags = _insert_config_format_fixture(self.team, self.user)
+ stored = {key: copy.deepcopy(flag.filters) for key, flag in flags.items()}
+
+ with capture_logs() as log_events:
+ single = _get_feature_flags_for_service(self.team)
+ batch = _get_feature_flags_for_teams_batch([self.team])[self.team.id]
+
+ self._assert_fixture_payload(single, fixture, flags)
+ assert {f["id"]: f for f in batch["flags"]} == {f["id"]: f for f in single["flags"]}
+ assert batch["evaluation_metadata"] == single["evaluation_metadata"]
+ assert batch["cohorts"] == single["cohorts"] == []
+ for key, flag in flags.items():
+ flag.refresh_from_db()
+ assert flag.filters == stored[key], key
+
+ # The warning is the only operator-visible record of what a team's cache left out.
+ def omitted_ids(expect: str) -> list[int]:
+ return sorted(flags[row["key"]].id for row in fixture["flags"] if row["expect"] == expect)
+
+ expected = {
+ "team_id": self.team.id,
+ "unsupported_flag_ids": omitted_ids("unsupported"),
+ "dependent_flag_ids": omitted_ids("dependent"),
+ }
+ omissions = [e for e in log_events if e["event"] == "Omitted flags the service cache cannot carry"]
+ assert [{k: e[k] for k in expected} for e in omissions] == [expected, expected]
+
+ def test_unsupported_flag_in_one_team_leaves_other_teams_in_the_batch_intact(self):
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ FeatureFlag.objects.create(
+ team=self.team, key="unsupported", created_by=self.user, filters={"version": 2, "groups": "junk"}
+ )
+ FeatureFlag.objects.create(
+ team=other_team,
+ key="v1-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+
+ result = _get_feature_flags_for_teams_batch([self.team, other_team])
+
+ assert result[self.team.id]["flags"] == []
+ assert [f["key"] for f in result[other_team.id]["flags"]] == ["v1-flag"]
+
+ def test_cohorts_are_collected_from_surviving_flags_only(self):
+ def cohort(name: str) -> Cohort:
+ return Cohort.objects.create(
+ team=self.team,
+ name=name,
+ filters={"properties": {"type": "OR", "values": [{"key": "email", "value": "a", "type": "person"}]}},
+ )
+
+ def cohort_filters(cohort_id: int, **extra) -> dict:
+ return {
+ **extra,
+ "groups": [{"properties": [{"type": "cohort", "value": cohort_id}], "rollout_percentage": 100}],
+ }
+
+ kept_cohort, unsupported_cohort, dependent_cohort = cohort("kept"), cohort("unsupported"), cohort("dependent")
+ FeatureFlag.objects.create(
+ team=self.team, key="v1-flag", created_by=self.user, filters=cohort_filters(kept_cohort.id)
+ )
+ unsupported = FeatureFlag.objects.create(
+ team=self.team,
+ key="unsupported",
+ created_by=self.user,
+ filters=cohort_filters(unsupported_cohort.id, version=2),
+ )
+ dependent_filters = _dependency_filters(unsupported.id)
+ dependent_filters["groups"][0]["properties"].append({"type": "cohort", "value": dependent_cohort.id})
+ FeatureFlag.objects.create(team=self.team, key="dependent", created_by=self.user, filters=dependent_filters)
+
+ single = _get_feature_flags_for_service(self.team)
+ batch = _get_feature_flags_for_teams_batch([self.team])[self.team.id]
+
+ assert [c["id"] for c in single["cohorts"]] == [kept_cohort.id]
+ assert [c["id"] for c in batch["cohorts"]] == [kept_cohort.id]
+
+ @patch("products.feature_flags.backend.tasks.publish_shadow_invalidation")
+ def test_celery_task_publishes_the_omitted_payload(self, mock_publish_shadow_invalidation):
+ from products.feature_flags.backend.tasks import update_team_service_flags_cache
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="v1-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ unsupported = FeatureFlag.objects.create(
+ team=self.team, key="unsupported", created_by=self.user, filters={"version": 2, "rules": []}
+ )
+ FeatureFlag.objects.create(
+ team=self.team, key="dependent", created_by=self.user, filters=_dependency_filters(unsupported.id)
+ )
+
+ update_team_service_flags_cache(self.team.id)
+
+ cached = get_flags_from_cache(self.team)
+ assert cached is not None
+ assert [f["key"] for f in cached] == ["v1-flag"]
+ assert flags_hypercache.get_etag(self.team) is not None
+ mock_publish_shadow_invalidation.assert_called_once_with(self.team.id)
+
+
@override_settings(FLAGS_REDIS_URL="redis://test")
class TestHasExperimentField(BaseTest):
"""has_experiment reflects whether a flag has a non-deleted linked experiment."""
diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rs
index 96c726d0d7d2..6e593162acf8 100644
--- a/rust/feature-flags/src/bin/flags_cache_builder.rs
+++ b/rust/feature-flags/src/bin/flags_cache_builder.rs
@@ -10,7 +10,7 @@
//! 1. Batch-fetch up to N messages, bounded by a ~500ms coalesce window.
//! 2. Dedupe by `team_id` — an edit session firing 20 saves becomes one build.
//! 3. Build each unique team once, with bounded retries.
-//! 4. Route teams with permanent failures or exhausted retries to the DLQ.
+//! 4. Route teams that exhaust their retry budget to the DLQ.
//! 5. Commit offsets as a batch (only after the build outcome is decided).
//!
//! The lazy request-path fill stays as the final safety net: a stuck consumer
@@ -49,7 +49,6 @@ use tokio_util::sync::CancellationToken;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;
-use feature_flags::api::errors::FlagError;
use feature_flags::flags::cache_builder::build_flags_cache;
use feature_flags::flags::cache_invalidation::{FlagsCacheInvalidation, Source};
use feature_flags::flags::cache_shadow::{
@@ -870,7 +869,7 @@ async fn shadow_compare(
) -> ShadowOutcome {
let built = match build_flags_cache(pg_reader.clone(), team_id).await {
Ok(built) => built,
- Err(e) => return ShadowOutcome::Failed(BuildFailure::from_build(e)),
+ Err(e) => return ShadowOutcome::Failed(BuildFailure::database(e)),
};
let live = match live_reader
@@ -906,7 +905,6 @@ async fn shadow_compare(
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter)]
enum FailureCategory {
Database,
- ConfigFormat,
CacheParse,
Redis,
S3,
@@ -918,7 +916,6 @@ impl FailureCategory {
fn as_label(&self) -> &'static str {
match self {
Self::Database => "database",
- Self::ConfigFormat => "config_format",
Self::CacheParse => "cache_parse",
Self::Redis => "redis",
Self::S3 => "s3",
@@ -928,30 +925,24 @@ impl FailureCategory {
}
}
-/// A terminal build failure tagged with its cause so metrics and DLQ headers can
-/// distinguish invalid configuration from infrastructure failures.
+/// A terminal build failure tagged with the tier that failed, so the error metric
+/// and DLQ headers can attribute it — that tier (database / redis / s3 / serialize)
+/// is the triage signal the DLQ exists to provide.
struct BuildFailure {
category: FailureCategory,
message: String,
}
impl BuildFailure {
- fn from_build(err: FlagError) -> Self {
- let category = if err.error_code() == "flag_data_parsing_error" {
- FailureCategory::ConfigFormat
- } else {
- FailureCategory::Database
- };
+ /// A failure reading flag/cohort state from Postgres (the `build_flags_cache`
+ /// step). The whole step is DB-bound on this path, so it's attributed wholesale.
+ fn database(err: impl std::fmt::Display) -> Self {
Self {
- category,
+ category: FailureCategory::Database,
message: err.to_string(),
}
}
- fn should_retry(&self, attempt: u32, max_attempts: u32) -> bool {
- self.category != FailureCategory::ConfigFormat && attempt < max_attempts
- }
-
/// A failure reading the live entry during a shadow compare. `Json`/`Pickle`
/// mean the cached bytes didn't parse into the typed model (`cache_parse` —
/// distinct from the write path's `serialize`); everything else is the Redis
@@ -1010,7 +1001,7 @@ async fn build_with_retry(
return Ok(());
}
Err(failure) => {
- if !failure.should_retry(attempt, cfg.build_max_attempts) {
+ if attempt >= cfg.build_max_attempts {
return Err(failure);
}
metrics::counter!(BUILD_RETRIES).increment(1);
@@ -1046,7 +1037,7 @@ async fn build_once(
) -> Result<PersistOutcome, BuildFailure> {
let cache = build_flags_cache(pg_reader.clone(), team_id)
.await
- .map_err(BuildFailure::from_build)?;
+ .map_err(BuildFailure::database)?;
persist_flags_cache(writer, team_id, &cache, ttl_seconds)
.await
.map_err(BuildFailure::from_persist)
@@ -1262,8 +1253,7 @@ mod tests {
use super::{
fold_message, max_per_partition, precreate_counters, retry_backoff, truncate_for_header,
- BuildFailure, FlagError, ShadowOutcome, ShadowOutcomeLabel, Source, TeamBatch,
- DLQ_ERROR_HEADER_MAX,
+ BuildFailure, ShadowOutcome, ShadowOutcomeLabel, Source, TeamBatch, DLQ_ERROR_HEADER_MAX,
};
// (partition, offset) pairs; keyed and valued by the two fields.
@@ -1303,6 +1293,34 @@ mod tests {
)
}
+ #[tokio::test]
+ async fn build_once_persists_the_team_without_its_unsupported_flags() {
+ use common_hypercache::writer::HyperCacheWriter;
+ use common_redis::MockRedisClient;
+ use feature_flags::flags::cache_writer::make_cache_config;
+ use feature_flags::utils::test_utils::{
+ dummy_s3_client, insert_v1_and_v2_flags, published_flag_keys, TestContext,
+ };
+ use std::sync::Arc;
+
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ insert_v1_and_v2_flags(&context, team.id).await;
+ let redis = Arc::new(MockRedisClient::new());
+ let writer = HyperCacheWriter::new(
+ redis.clone(),
+ dummy_s3_client(),
+ make_cache_config("us-east-1", "test-bucket", None),
+ );
+
+ let outcome = super::build_once(&context.non_persons_reader, &writer, team.id, 60)
+ .await
+ .unwrap_or_else(|failure| panic!("{}", failure.message));
+
+ assert_eq!(published_flag_keys(&redis), ["v1-flag"]);
+ assert!(!outcome.etag.is_empty());
+ }
+
#[test]
fn coalesce_keeps_oldest_emitted_at_regardless_of_arrival_order() {
// Same team, timestamps arriving newest-first: the oldest must still win,
@@ -1489,20 +1507,11 @@ mod tests {
}
#[test]
- fn build_failure_classifies_build_errors_and_skips_config_format_retries() {
- for (err, expected_category, retryable) in [
- (FlagError::DatabaseUnavailable, "database", true),
- (
- FlagError::flag_data_parsing("unsupported feature flag configuration format"),
- "config_format",
- false,
- ),
- ] {
- let failure = BuildFailure::from_build(err);
- assert_eq!(failure.category.as_label(), expected_category);
- assert_eq!(failure.should_retry(1, 3), retryable);
- assert!(!failure.should_retry(3, 3));
- }
+ fn build_failure_attributes_build_step_to_database() {
+ assert_eq!(
+ BuildFailure::database("pg unreachable").category.as_label(),
+ "database"
+ );
}
#[test]
@@ -1615,7 +1624,7 @@ mod tests {
ShadowOutcomeLabel::LiveEntryMissing,
),
(
- ShadowOutcome::Failed(BuildFailure::from_build(FlagError::DatabaseUnavailable)),
+ ShadowOutcome::Failed(BuildFailure::database("pg unreachable")),
ShadowOutcomeLabel::Error,
),
(
@@ -1654,8 +1663,6 @@ mod tests {
"flags_cache_builder_build_retries_total{}",
"flags_cache_builder_builds_total{reason=cache_parse,result=failure,source=edit}",
"flags_cache_builder_builds_total{reason=cache_parse,result=failure,source=refresh}",
- "flags_cache_builder_builds_total{reason=config_format,result=failure,source=edit}",
- "flags_cache_builder_builds_total{reason=config_format,result=failure,source=refresh}",
"flags_cache_builder_builds_total{reason=database,result=failure,source=edit}",
"flags_cache_builder_builds_total{reason=database,result=failure,source=refresh}",
"flags_cache_builder_builds_total{reason=other,result=failure,source=edit}",
@@ -1674,7 +1681,6 @@ mod tests {
"flags_cache_builder_messages_received_total{}",
"flags_cache_builder_parse_errors_total{}",
"flags_cache_shadow_build_failures_total{category=cache_parse}",
- "flags_cache_shadow_build_failures_total{category=config_format}",
"flags_cache_shadow_build_failures_total{category=database}",
"flags_cache_shadow_build_failures_total{category=other}",
"flags_cache_shadow_build_failures_total{category=redis}",
diff --git a/rust/feature-flags/src/bin/warm-flags-cache.rs b/rust/feature-flags/src/bin/warm-flags-cache.rs
index 58bb29d787a2..fb6afa797f6b 100644
--- a/rust/feature-flags/src/bin/warm-flags-cache.rs
+++ b/rust/feature-flags/src/bin/warm-flags-cache.rs
@@ -890,6 +890,31 @@ mod tests {
assert!(msg.contains("1000"), "message should cite the IDs: {msg}");
}
+ #[tokio::test]
+ async fn warm_team_persists_the_team_without_its_unsupported_flags() {
+ use common_redis::MockRedisClient;
+ use feature_flags::flags::cache_writer::make_cache_config;
+ use feature_flags::utils::test_utils::{
+ dummy_s3_client, insert_v1_and_v2_flags, published_flag_keys, TestContext,
+ };
+
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ insert_v1_and_v2_flags(&context, team.id).await;
+ let redis = Arc::new(MockRedisClient::new());
+ let writer = HyperCacheWriter::new(
+ redis.clone(),
+ dummy_s3_client(),
+ make_cache_config("us-east-1", "test-bucket", None),
+ );
+
+ warm_team(context.non_persons_reader.clone(), &writer, team.id, 60)
+ .await
+ .expect("warm_team should succeed");
+
+ assert_eq!(published_flag_keys(&redis), ["v1-flag"]);
+ }
+
/// Regression for the warmer overwriting Django's etag. set() unconditionally
/// DELs `<key>:etag`, which silently re-arms the FlagDefinitionsCache slow
/// path for every team the warmer touches. Lock down that persist_flags_cache
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index e354cd223600..18ed24fe4943 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -12,6 +12,7 @@ use common_types::TeamId;
use crate::api::errors::FlagError;
use crate::cohorts::cohort_models::{Cohort, CohortId};
+use crate::flags::feature_flag_list::{UndecodableDocument, UndecodableFlags};
use crate::flags::flag_models::{
EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters,
HypercacheFlagsWrapper,
@@ -50,12 +51,9 @@ pub async fn build_flags_cache(
pg_reader: PostgresReader,
team_id: TeamId,
) -> Result<HypercacheFlagsWrapper, FlagError> {
- let mut flags = FeatureFlagList::from_pg(pg_reader.clone(), team_id).await?;
- // Python's builder (`facade/references.py`) raises `ConfigFormatError` here and fails
- // the whole team rebuild; both writers of this entry must agree.
- for flag in flags.iter().filter(|flag| is_evaluable(flag)) {
- flag.filters.require_v1()?;
- }
+ let (mut flags, undecodable) =
+ FeatureFlagList::from_pg_keeping_undecodable(pg_reader.clone(), team_id).await?;
+ omit_unsupported_flags(team_id, &mut flags, &undecodable);
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?;
@@ -79,6 +77,57 @@ pub(crate) fn is_evaluable(flag: &FeatureFlag) -> bool {
flag.active && !flag.deleted
}
+/// Drop the stored rows this cache cannot carry, and their dependents transitively:
+/// non-v1 and non-object documents whatever their lifecycle, and evaluable v1 objects the
+/// typed decoder rejected. Mirrors Python's `_omit_unsupported_flags()` in
+/// `products/feature_flags/backend/flags_cache.py`, where the rationale lives.
+fn omit_unsupported_flags(
+ team_id: TeamId,
+ flags: &mut Vec<FeatureFlag>,
+ undecodable: &UndecodableFlags,
+) {
+ let unsupported: HashSet<FeatureFlagId> = flags
+ .iter()
+ .filter(|flag| {
+ !flag.filters.is_v1()
+ || match undecodable.get(&flag.id) {
+ Some(UndecodableDocument::NotAnObject) => true,
+ Some(UndecodableDocument::UnreadableV1Object) => is_evaluable(flag),
+ None => false,
+ }
+ })
+ .map(|flag| flag.id)
+ .collect();
+ let mut dependents: HashMap<FeatureFlagId, Vec<FeatureFlagId>> = HashMap::new();
+ for flag in flags.iter() {
+ for dependency_id in extract_direct_flag_dependency_ids(flag) {
+ dependents.entry(dependency_id).or_default().push(flag.id);
+ }
+ }
+ let mut excluded = unsupported.clone();
+ let mut pending: Vec<FeatureFlagId> = unsupported.iter().copied().collect();
+ while let Some(id) = pending.pop() {
+ for &dependent_id in dependents.get(&id).into_iter().flatten() {
+ if excluded.insert(dependent_id) {
+ pending.push(dependent_id);
+ }
+ }
+ }
+ if !excluded.is_empty() {
+ let mut unsupported_flag_ids: Vec<_> = unsupported.iter().copied().collect();
+ unsupported_flag_ids.sort_unstable();
+ let mut dependent_flag_ids: Vec<_> = excluded.difference(&unsupported).copied().collect();
+ dependent_flag_ids.sort_unstable();
+ tracing::warn!(
+ team_id,
+ ?unsupported_flag_ids,
+ ?dependent_flag_ids,
+ "Omitted flags the service cache cannot carry"
+ );
+ }
+ flags.retain(|flag| !excluded.contains(&flag.id));
+}
+
/// 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.
@@ -1034,23 +1083,132 @@ mod tests {
assert!(meta.flags_with_missing_deps.is_empty());
}
- #[test]
- fn test_blank_inactive_filters_blanks_every_config_format() {
- for version in [
- serde_json::json!(1),
- serde_json::json!(2),
- serde_json::json!(3),
- serde_json::json!(null),
- ] {
- let flag: FeatureFlag = serde_json::from_value(serde_json::json!({
- "id": 1, "team_id": 1, "key": "inactive", "active": false,
- "filters": {"version": version, "groups": [{"rollout_percentage": 100}]}
- }))
- .unwrap();
- let mut flags = vec![flag];
- blank_inactive_filters(&mut flags);
- let after = serde_json::to_value(&flags[0]).unwrap();
- assert_eq!(after["filters"], serde_json::json!({"groups": []}));
+ /// Insert the shared config-format fixture for one team and return each fixture
+ /// key's row id. Dependency properties name fixture keys, so rows go in with a
+ /// placeholder document first and get their real filters once every id is known.
+ async fn insert_config_format_fixture(
+ context: &TestContext,
+ team_id: i32,
+ ) -> (serde_json::Value, HashMap<String, i32>) {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../tests/fixtures/flags_cache_config_formats.json"
+ ))
+ .unwrap();
+ let mut ids: HashMap<String, i32> = HashMap::new();
+ for flag in fixture["flags"].as_array().unwrap() {
+ let key = flag["key"].as_str().unwrap();
+ let inserted = context
+ .insert_flag(
+ team_id,
+ Some(FeatureFlagRow {
+ key: key.to_string(),
+ active: flag["active"].as_bool().unwrap(),
+ filters: serde_json::json!({}),
+ ..base_flag_row(team_id)
+ }),
+ )
+ .await
+ .expect("Failed to insert fixture flag");
+ ids.insert(key.to_string(), inserted.id);
+ }
+ let missing_id = fixture["missing_dependency_id"].as_i64().unwrap();
+ let mut connection = context.non_persons_writer.get_connection().await.unwrap();
+ for flag in fixture["flags"].as_array().unwrap() {
+ let mut filters = flag["filters"].clone();
+ if let Some(groups) = filters.get_mut("groups").and_then(|g| g.as_array_mut()) {
+ for property in groups
+ .iter_mut()
+ .filter_map(|group| group.get_mut("properties")?.as_array_mut())
+ .flatten()
+ .filter(|property| property["type"] == "flag")
+ {
+ let reference = property["key"].as_str().unwrap();
+ let id = if reference == "$missing" {
+ missing_id
+ } else {
+ i64::from(ids[reference])
+ };
+ property["key"] = serde_json::json!(id.to_string());
+ }
+ }
+ sqlx::query("UPDATE posthog_featureflag SET filters = $1::jsonb WHERE id = $2")
+ .bind(filters.to_string())
+ .bind(ids[flag["key"].as_str().unwrap()])
+ .execute(&mut *connection)
+ .await
+ .unwrap();
+ }
+ (fixture, ids)
+ }
+
+ #[tokio::test]
+ async fn test_build_flags_cache_omits_unsupported_configs_and_their_dependents() {
+ let context = TestContext::new(None).await;
+ let team = context
+ .insert_new_team(None)
+ .await
+ .expect("Failed to insert team");
+ let (fixture, ids) = insert_config_format_fixture(&context, team.id).await;
+
+ let wrapper = build_flags_cache(context.non_persons_reader.clone(), team.id)
+ .await
+ .expect("Failed to build flags cache");
+
+ let rows = fixture["flags"].as_array().unwrap();
+ let published: HashMap<i32, &FeatureFlag> =
+ wrapper.flags.iter().map(|f| (f.id, f)).collect();
+ let expected_keys: HashSet<&str> = rows
+ .iter()
+ .filter(|flag| flag["expect"] == "kept")
+ .map(|flag| flag["key"].as_str().unwrap())
+ .collect();
+ let published_keys: HashSet<&str> = wrapper.flags.iter().map(|f| f.key.as_str()).collect();
+ assert_eq!(published_keys, expected_keys);
+ for flag in rows {
+ let key = flag["key"].as_str().unwrap();
+ if flag["expect"] != "kept" {
+ continue;
+ }
+ let filters = serde_json::to_value(&published[&ids[key]].filters).unwrap();
+ if flag["blanked"] == true {
+ assert_eq!(filters, serde_json::json!({"groups": []}), "{key}");
+ } else {
+ // Group count and payloads rather than the whole document, because a
+ // JSONB round trip renders `rollout_percentage` as a float.
+ let stored_groups = flag["filters"]["groups"].as_array().map_or(0, Vec::len);
+ assert_eq!(
+ filters["groups"].as_array().unwrap().len(),
+ stored_groups,
+ "{key}"
+ );
+ assert_eq!(
+ filters.get("payloads"),
+ flag["filters"].get("payloads"),
+ "{key}"
+ );
+ }
}
+
+ let meta = &wrapper.evaluation_metadata;
+ let mut expected_missing: Vec<i32> = rows
+ .iter()
+ .filter(|flag| flag["missing_dependency"] == true)
+ .map(|flag| ids[flag["key"].as_str().unwrap()])
+ .collect();
+ expected_missing.sort_unstable();
+ assert_eq!(meta.flags_with_missing_deps, expected_missing);
+ let staged: HashSet<i32> = meta.dependency_stages.iter().flatten().copied().collect();
+ let published_ids: HashSet<i32> = published.keys().copied().collect();
+ assert_eq!(
+ staged,
+ published_ids
+ .difference(&HashSet::from([ids["cycle-a"], ids["cycle-b"]]))
+ .copied()
+ .collect::<HashSet<_>>()
+ );
+ assert_eq!(
+ meta.transitive_deps[&ids["depends-true-on-v1-true"]],
+ HashSet::from([ids["v1-boolean-true"]])
+ );
}
}
diff --git a/rust/feature-flags/src/flags/config_format.rs b/rust/feature-flags/src/flags/config_format.rs
index c15e617bf577..a7bb776c5b34 100644
--- a/rust/feature-flags/src/flags/config_format.rs
+++ b/rust/feature-flags/src/flags/config_format.rs
@@ -5,6 +5,7 @@ use std::sync::Arc;
use crate::api::errors::FlagError;
use crate::flags::config_v2;
+use crate::flags::feature_flag_list::UndecodableDocument;
use crate::flags::flag_models::FlagFilters;
use crate::metrics::consts::FLAG_V2_PARSE_COUNTER;
@@ -100,23 +101,42 @@ impl FlagFilters {
}
}
+#[derive(Debug, thiserror::Error)]
+#[error("{error}")]
+pub(crate) struct FilterDecodeError {
+ pub(crate) error: serde_json::Error,
+ pub(crate) document: UndecodableDocument,
+}
+
#[cfg(test)]
-pub(crate) fn decode_filters(value: Value) -> Result<FlagFilters, serde_json::Error> {
- decode_raw_filters(serde_json::value::to_raw_value(&value)?)
+pub(crate) fn decode_filters(value: Value) -> Result<FlagFilters, FilterDecodeError> {
+ let raw = serde_json::value::to_raw_value(&value).expect("a Value always serializes");
+ decode_raw_filters(raw)
}
-pub(crate) fn decode_raw_filters(raw: Box<RawValue>) -> Result<FlagFilters, serde_json::Error> {
+pub(crate) fn decode_raw_filters(raw: Box<RawValue>) -> Result<FlagFilters, FilterDecodeError> {
let (format, document) = match serde_json::from_str::<FilterDocument<true>>(raw.get()) {
Ok(decoded) => (decoded.format, Ok(decoded.document)),
Err(error) => {
// An unrepresentable number must stay a per-flag v2 failure. Only
// failed Value reads need another scan to recover the discriminator.
- let probe = serde_json::from_str::<FilterDocument<false>>(raw.get())?;
+ let probe =
+ serde_json::from_str::<FilterDocument<false>>(raw.get()).map_err(|error| {
+ FilterDecodeError {
+ error,
+ document: UndecodableDocument::NotAnObject,
+ }
+ })?;
(probe.format, Err(error))
}
};
if format == ConfigFormat::V1 {
- serde_json::from_value(Value::Object(document?))
+ document
+ .and_then(|document| serde_json::from_value(Value::Object(document)))
+ .map_err(|error| FilterDecodeError {
+ error,
+ document: UndecodableDocument::UnreadableV1Object,
+ })
} else {
let parsed_v2 = (format == ConfigFormat::V2).then(|| {
config_v2::validate_raw_document(&raw)?;
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index e15d1f544281..2c20ceed37ae 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -2,8 +2,8 @@ use crate::api::errors::FlagError;
use crate::cohorts::cohort_models::Cohort;
use crate::database::get_connection_with_metrics;
use crate::flags::flag_models::{
- EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, FlagPropertyGroup,
- HypercacheFlagsWrapper,
+ EvaluationMetadata, FeatureFlag, FeatureFlagId, FeatureFlagList, FeatureFlagRow, FlagFilters,
+ FlagPropertyGroup, HypercacheFlagsWrapper,
};
use crate::metrics::consts::{
FLAG_MALFORMED_FILTER_COUNTER, FLAG_MALFORMED_FILTER_READ_COUNTER, TOMBSTONE_COUNTER,
@@ -11,11 +11,21 @@ use crate::metrics::consts::{
use common_database::PostgresReader;
use common_types::TeamId;
use metrics::counter;
+use std::collections::HashMap;
use std::sync::Arc;
/// Parsed hypercache result: flags, evaluation metadata, optional preloaded cohorts.
type HypercacheParseResult = (Vec<FeatureFlag>, EvaluationMetadata, Option<Vec<Cohort>>);
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UndecodableDocument {
+ NotAnObject,
+ UnreadableV1Object,
+}
+
+/// Rows `from_pg_keeping_undecodable` kept with blank filters, and why.
+pub type UndecodableFlags = HashMap<FeatureFlagId, UndecodableDocument>;
+
/// `Arc<[FeatureFlag]>` with regexes pre-compiled. Every constructor routes
/// through [`PreparedFlags::seal`] (or `from_arc` for already-sealed input),
/// so a value of this type is guaranteed to have been through
@@ -126,6 +136,18 @@ impl FeatureFlagList {
client: PostgresReader,
team_id: TeamId,
) -> Result<Vec<FeatureFlag>, FlagError> {
+ let (mut flags, undecodable) = Self::from_pg_keeping_undecodable(client, team_id).await?;
+ flags.retain(|flag| !undecodable.contains_key(&flag.id));
+ Ok(flags)
+ }
+
+ /// Like `from_pg`, but a row whose `filters` document could not be decoded stays in
+ /// the list with blank filters and is reported in `UndecodableFlags`, so the cache
+ /// builder can classify it and its dependents.
+ pub async fn from_pg_keeping_undecodable(
+ client: PostgresReader,
+ team_id: TeamId,
+ ) -> Result<(Vec<FeatureFlag>, UndecodableFlags), FlagError> {
let mut conn = get_connection_with_metrics(&client, "non_persons_reader", "fetch_flags")
.await
.map_err(|e| {
@@ -197,36 +219,19 @@ impl FeatureFlagList {
FlagError::internal(anyhow::Error::new(e).context(message))
})?;
- let mut malformed_filter_flags: u64 = 0;
+ let mut undecodable = UndecodableFlags::default();
let flags: Vec<FeatureFlag> = flags_row
.into_iter()
- .filter_map(|row| {
- match crate::flags::config_format::decode_raw_filters(row.filters.0) {
- Ok(filters) => Some(FeatureFlag {
- id: row.id,
- team_id: row.team_id,
- name: row.name,
- key: row.key,
- filters,
- deleted: row.deleted,
- active: row.active,
- ensure_experience_continuity: row.ensure_experience_continuity,
- version: row.version,
- evaluation_runtime: row.evaluation_runtime,
- evaluation_tags: row.evaluation_tags,
- bucketing_identifier: row.bucketing_identifier,
- has_experiment: row.has_experiment,
- }),
- Err(e) => {
+ .map(|row| {
+ let filters = crate::flags::config_format::decode_raw_filters(row.filters.0)
+ .unwrap_or_else(|e| {
// Serde fails the whole `filters` struct when a required field is
// absent, so one bad property filter costs the entire flag. A property
// filter with no `"type"` key does that, because
// PropertyFilter::prop_type has no default. Python does not parse these
- // filters, so it keeps such a flag when the flag is active or referenced,
- // and those drops are real builder divergences. An inactive, unreferenced
- // flag is dropped by both builders, so the counters below over-count it.
- // Skip the flag rather than fail the read, so the team keeps the rest.
- malformed_filter_flags += 1;
+ // filters, so it keeps such a flag when the flag is active, and those
+ // drops are real builder divergences. Either way the team keeps the
+ // rest of its flags, rather than failing the read.
tracing::warn!(
"Failed to deserialize filters for flag {} in team {}: {}",
row.key,
@@ -241,25 +246,39 @@ impl FeatureFlagList {
"component" => "feature_flag_list",
)
.increment(1);
-
- None
- }
+ undecodable.insert(row.id, e.document);
+ FlagFilters::default()
+ });
+ FeatureFlag {
+ id: row.id,
+ team_id: row.team_id,
+ name: row.name,
+ key: row.key,
+ filters,
+ deleted: row.deleted,
+ active: row.active,
+ ensure_experience_continuity: row.ensure_experience_continuity,
+ version: row.version,
+ evaluation_runtime: row.evaluation_runtime,
+ evaluation_tags: row.evaluation_tags,
+ bucketing_identifier: row.bucketing_identifier,
+ has_experiment: row.has_experiment,
}
})
.collect();
- if malformed_filter_flags > 0 {
- counter!(FLAG_MALFORMED_FILTER_COUNTER).increment(malformed_filter_flags);
+ if !undecodable.is_empty() {
+ counter!(FLAG_MALFORMED_FILTER_COUNTER).increment(undecodable.len() as u64);
counter!(FLAG_MALFORMED_FILTER_READ_COUNTER).increment(1);
}
tracing::debug!(
"Successfully fetched {} flags from database for team {}",
- flags.len(),
+ flags.len() - undecodable.len(),
team_id
);
- Ok(flags)
+ Ok((flags, undecodable))
}
}
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 555c4c11e34d..5df9281dbf2c 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -6,7 +6,10 @@ use crate::{
flag_group_type_mapping::{
GroupTypeCacheManager, GroupTypeFetchError, GroupTypeMapping, GroupTypeMappingFetcher,
},
- flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow},
+ flag_models::{
+ EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow,
+ HypercacheFlagsWrapper,
+ },
},
properties::property_models::PropertyType,
team::team_models::Team,
@@ -16,7 +19,7 @@ use async_trait::async_trait;
use chrono::{DateTime, Utc};
use common_database::{get_pool, Client, CustomDatabaseError};
use common_hypercache::{HyperCacheConfig, HyperCacheReader};
-use common_redis::{Client as RedisClientTrait, RedisClient};
+use common_redis::{Client as RedisClientTrait, MockRedisClient, MockRedisValue, RedisClient};
use common_types::{Person, PersonId};
use rand::{distributions::Alphanumeric, Rng};
use serde_json::{json, Value};
@@ -275,6 +278,48 @@ pub fn dummy_s3_client() -> Arc<dyn common_hypercache::S3Client + Send + Sync> {
Arc::new(AlwaysMissS3Client)
}
+pub async fn insert_v1_and_v2_flags(context: &TestContext, team_id: i32) {
+ for (key, filters) in [
+ (
+ "v1-flag",
+ json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),
+ ),
+ (
+ "v2-flag",
+ json!({"version": 2, "return_type": "boolean", "default_value": false, "rules": []}),
+ ),
+ ] {
+ context
+ .insert_flag(
+ team_id,
+ Some(FeatureFlagRow {
+ team_id,
+ key: key.to_string(),
+ name: Some(String::new()),
+ filters,
+ active: true,
+ evaluation_runtime: Some("all".to_string()),
+ ..Default::default()
+ }),
+ )
+ .await
+ .expect("Failed to insert flag");
+ }
+}
+
+pub fn published_flag_keys(redis: &MockRedisClient) -> Vec<String> {
+ let written = redis
+ .get_calls()
+ .into_iter()
+ .find(|call| call.op == "pipeline_setex" && call.key.ends_with("/flags.json"))
+ .expect("payload write");
+ let MockRedisValue::StringWithTTLAndFormat(payload, _, _) = written.value else {
+ panic!("unexpected write {:?}", written.value)
+ };
+ let wrapper: HypercacheFlagsWrapper = serde_json::from_str(&payload).unwrap();
+ wrapper.flags.into_iter().map(|flag| flag.key).collect()
+}
+
/// Create a HyperCacheReader for tests using the provided Redis client.
/// Uses default test configuration for S3 (which won't be used in most tests
/// since Redis should have the data).
diff --git a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json
new file mode 100644
index 000000000000..090aa1949330
--- /dev/null
+++ b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json
@@ -0,0 +1,340 @@
+{
+ "description": "Stored feature flag rows for one team, and what the internal flags.json builders must publish for each. Both the Python builders (products/feature_flags/backend/flags_cache.py) and the Rust builder (rust/feature-flags/src/flags/cache_builder.rs) run this file. A `type: flag` property whose `key` names another fixture key references that row; the harness rewrites it to the inserted id before building. `$missing` becomes `missing_dependency_id`. `expect` is `kept` when the row appears in the published payload; otherwise it is `unsupported` (a document the builders reject, logged under unsupported_flag_ids), `dependent` (a row whose dependency conditions reference an unsupported row, transitively, logged under dependent_flag_ids) or `omitted` (left out for another reason); `blanked` marks a kept row whose filters are published as {\"groups\": []}; `missing_dependency` marks a kept row listed in flags_with_missing_deps.",
+ "missing_dependency_id": 2147480000,
+ "flags": [
+ {
+ "key": "v1-boolean-true",
+ "active": true,
+ "filters": { "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "kept"
+ },
+ {
+ "key": "v1-boolean-false",
+ "active": true,
+ "filters": { "groups": [{ "properties": [], "rollout_percentage": 0 }] },
+ "expect": "kept"
+ },
+ {
+ "key": "v1-multivariate-payload",
+ "active": true,
+ "filters": {
+ "groups": [{ "properties": [], "rollout_percentage": 100 }],
+ "multivariate": {
+ "variants": [
+ { "key": "control", "rollout_percentage": 50 },
+ { "key": "test", "rollout_percentage": 50 }
+ ]
+ },
+ "payloads": { "control": "{\"plan\": \"control\"}", "test": "{\"plan\": \"test\"}" }
+ },
+ "expect": "kept"
+ },
+ {
+ "key": "v1-explicit-version-1",
+ "active": true,
+ "filters": { "version": 1, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "kept"
+ },
+ {
+ "key": "v1-explicit-version-1.0",
+ "active": true,
+ "filters": { "version": 1.0, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "kept"
+ },
+ {
+ "key": "v1-empty-document",
+ "active": true,
+ "filters": {},
+ "expect": "kept"
+ },
+ {
+ "key": "v1-inactive-referenced",
+ "active": false,
+ "filters": { "groups": [{ "properties": [], "rollout_percentage": 100 }], "payloads": { "true": "x" } },
+ "expect": "kept",
+ "blanked": true
+ },
+ {
+ "key": "v1-inactive-unreferenced",
+ "active": false,
+ "filters": { "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "omitted",
+ "reason": "established trim of unreferenced inactive rows"
+ },
+ {
+ "key": "v1-inactive-unreadable-referenced",
+ "active": false,
+ "filters": { "groups": "never read" },
+ "expect": "kept",
+ "blanked": true
+ },
+ {
+ "key": "v2-valid-active",
+ "active": true,
+ "filters": {
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": null,
+ "rules": [
+ {
+ "id": "a1a1a1a1-a1a1-4a1a-8a1a-a1a1a1a1a1a1",
+ "rule_type": "targeted_release",
+ "targeting": { "properties": [{ "key": "account_tier", "type": "person", "operator": "exact", "value": "preview" }] },
+ "value": true
+ },
+ {
+ "id": "b2b2b2b2-b2b2-4b2b-8b2b-b2b2b2b2b2b2",
+ "rule_type": "percentage_rollout",
+ "targeting": { "properties": [] },
+ "value": true,
+ "rollout_percentage": 33.33,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview"
+ }
+ ]
+ },
+ "expect": "unsupported"
+ },
+ {
+ "key": "v2-malformed-active",
+ "active": true,
+ "filters": { "version": 2, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "v2-valid-inactive",
+ "active": false,
+ "filters": { "version": 2, "return_type": "boolean", "default_value": false, "rules": [] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "v2-valid-archived",
+ "active": false,
+ "archived": true,
+ "filters": { "version": 2, "return_type": "boolean", "default_value": false, "rules": [] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "unsupported-version-3",
+ "active": true,
+ "filters": { "version": 3, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "unsupported-version-1.5",
+ "active": true,
+ "filters": { "version": 1.5, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "unsupported-version-null",
+ "active": true,
+ "filters": { "version": null, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "unsupported-version-true",
+ "active": true,
+ "filters": { "version": true, "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "unsupported-version-string",
+ "active": true,
+ "filters": { "version": "1", "groups": [{ "properties": [], "rollout_percentage": 100 }] },
+ "expect": "unsupported"
+ },
+ {
+ "key": "malformed-v1-groups-string",
+ "active": true,
+ "filters": { "groups": "not a list" },
+ "expect": "unsupported"
+ },
+ {
+ "key": "malformed-non-object-document",
+ "active": true,
+ "filters": ["not", "an", "object"],
+ "expect": "unsupported"
+ },
+ {
+ "key": "malformed-non-object-inactive",
+ "active": false,
+ "filters": ["not", "an", "object"],
+ "expect": "unsupported"
+ },
+ {
+ "key": "malformed-null-document",
+ "active": true,
+ "filters": null,
+ "expect": "unsupported"
+ },
+ {
+ "key": "depends-false-on-non-object-inactive",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "malformed-non-object-inactive", "type": "flag", "value": "false", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "depends-true-on-v2-valid-active",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v2-valid-active", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "depends-false-on-v2-valid-inactive",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v2-valid-inactive", "type": "flag", "value": "false", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "depends-false-on-v2-inactive-with-later-condition",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v2-valid-inactive", "type": "flag", "value": "false", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100,
+ "variant": "blue"
+ },
+ { "properties": [], "rollout_percentage": 100, "variant": "green" }
+ ],
+ "multivariate": {
+ "variants": [
+ { "key": "blue", "rollout_percentage": 50 },
+ { "key": "green", "rollout_percentage": 50 }
+ ]
+ }
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "depends-on-malformed-v1",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "malformed-v1-groups-string", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "transitive-dependent",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "depends-true-on-v2-valid-active", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "dependent"
+ },
+ {
+ "key": "depends-false-on-inactive-v1",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v1-inactive-referenced", "type": "flag", "value": "false", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept"
+ },
+ {
+ "key": "depends-false-on-inactive-unreadable-v1",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v1-inactive-unreadable-referenced", "type": "flag", "value": "false", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept"
+ },
+ {
+ "key": "depends-true-on-v1-true",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "v1-boolean-true", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept"
+ },
+ {
+ "key": "depends-on-missing-target",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "$missing", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept",
+ "missing_dependency": true
+ },
+ {
+ "key": "cycle-a",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "cycle-b", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept",
+ "missing_dependency": true
+ },
+ {
+ "key": "cycle-b",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [{ "key": "cycle-a", "type": "flag", "value": "true", "operator": "flag_evaluates_to" }],
+ "rollout_percentage": 100
+ }
+ ]
+ },
+ "expect": "kept",
+ "missing_dependency": true
+ }
+ ]
+}
diff --git a/rust/feature-flags/tests/test_config_format.rs b/rust/feature-flags/tests/test_config_format.rs
index 125535f73663..b49f6c66b60d 100644
--- a/rust/feature-flags/tests/test_config_format.rs
+++ b/rust/feature-flags/tests/test_config_format.rs
@@ -202,9 +202,16 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: bool
.bind(raw).bind(team.id).bind(key).execute(&mut *connection).await?;
}
drop(connection);
- assert!(build_flags_cache(db.non_persons_reader.clone(), team.id)
- .await
- .is_err());
+ // The cache builder omits every non-v1 row instead of failing the team; the
+ // evaluator's PostgreSQL fallback below still sees them.
+ let mut built: Vec<String> = build_flags_cache(db.non_persons_reader.clone(), team.id)
+ .await?
+ .flags
+ .into_iter()
+ .map(|flag| flag.key)
+ .collect();
+ built.sort();
+ assert_eq!(built, vec!["absent", "one", "one-float", "one-rounded"]);
}
let stored = if cached {
let reader = HyperCacheReader::new_with_s3_client(