: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
feat(flags): evaluate supported v2 flags and cache them beside v1 (#105890)
Andersd17748374db9
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.mdindex 8123284693fd..50871c0a4592 100644--- a/docs/internal/feature-flags/flag-evaluation-engine.md+++ b/docs/internal/feature-flags/flag-evaluation-engine.md@@ -7,7 +7,7 @@ The Rust feature flags service evaluates flags using a deterministic, hash-basedStored configuration dispatch reads `filters.version`; the row's `FeatureFlag.version` remains a concurrency counter.An absent discriminator or numeric 1 (including 1.0) selects v1.Numeric 2 (including 2.0) selects the closed v2 parser; other discriminator values are unsupported.-The service does not evaluate any non-v1 format, including a successfully parsed v2 configuration.+The service evaluates v1 and a successfully parsed v2 configuration; every other non-v1 document is rejected per flag.The classification converts the discriminator to correctly rounded binary64, matching Python's `detect_config_format` (`products/feature_flags/backend/facade/config.py`) and its cache producer's normalization.Cache and PostgreSQL ingress classify the original document before decoding v1 fields.@@ -38,7 +38,7 @@ Parser fixtures from harness release 1.6.0 are pinned under contract version 2.1The Rust suite checks parser field sets, limits, and literals against the released schema and registry.Definitions-feed artifacts belong to the future definitions route and are not part of this parser pin.-The evaluator classifies them once per request, next to `filtered_out_flag_ids`, rather than failing per flag inside `get_match`: an eligible non-v1 flag gets a `flag_data_parsing_error` response entry, is skipped by regex, cohort, dependency, and property preparation, and is pre-seeded false like any other skipped flag, so a dependent's `flag_evaluates_to: false` condition still resolves.+The evaluator classifies eligible non-v1 flags once per request, next to `filtered_out_flag_ids`, rather than failing per flag inside `get_match`: an eligible non-v1 flag whose document the v2 parser did not accept gets a `flag_data_parsing_error` response entry, is skipped by regex, cohort, dependency, and property preparation, and is pre-seeded false like any other skipped flag, so a dependent's `flag_evaluates_to: false` condition still resolves.Detailed responses mark them failed.The legacy `/flags` map and `/decide?v=3` retain false entries with `errorsWhileComputingFlags=true`; older `/decide` formats omit them.Healthy siblings still evaluate, and request eligibility remains unchanged.@@ -47,17 +47,22 @@ Each recognized v2 ingress increments `flags_v2_config_parse_total` with a fixedThese 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 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.+The Rust and Python cache builders omit an unsupported 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; the PostgreSQL fallback applies the same omission, so a Redis miss does not change which flags a team serves.`/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.To roll back parsing, remove its reader consumer first while retaining opaque non-v1 reads and evaluator/producer rejection.Never restore a reader that interprets v2 data as v1.-The dormant `evaluate_v2::Evaluator` consumes the reader's successful typed person-boolean config by reference.+The `evaluate_v2::Evaluator` consumes the reader's successful typed person-boolean config by reference.The reader compiles each regex predicate once at parse time and stores it on the cached config, counted as a fixed `ESTIMATED_COMPILED_REGEX_BYTES` (2048) per compiled regex, as v1 does; an invalid pattern is stored rather than rejected, so its error surfaces only when evaluation reaches it.-The evaluator does not participate in the service cache or HTTP dispatch.Its caller supplies the resolved person distinct ID, complete or partial properties (or unavailable context), timezone, exact-matching setting, and a fixed evaluation time.+`get_match` runs it for an active flag whose parse succeeded, with the request distinct ID as the subject (hash key overrides, device identifiers and experience continuity do not apply), the team timezone and exact-matching setting, and the matcher's request time.+Person properties come from the same override-and-database acquisition v1 conditions use: a v2 predicate key absent from the request overrides triggers database preparation, and the merged map is `Complete` once the database was consulted or the request restricted evaluation to its overrides (`only_use_override_person_properties`, which the historical `test_evaluation` endpoint sets with the reconstructed property set, so a missing key means not set, as for v1), and `Partial` when the overrides covered every predicate key without a database read.+A request always carries its distinct ID as an override, so a predicate never sees `Unavailable` context; that variant is passed only for a rule set without predicates, where it is never read.+The typed outcome is projected onto the existing match shape and reaches every response format unchanged: a targeting match sets `enabled` to the rule value with `condition_match` and the rule index, a terminal rollout miss and no rule match set `enabled` to the flag default (`false` for a null default) with `out_of_rollout_bound` or `no_condition_match`, never a variant or a payload.+An evaluation error (missing context, an invalid property value, an invalid regex, a hash failure) returns that flag with `failed: true`, `enabled: false` and the `flag_evaluation_error` reason, and sets `errorsWhileComputingFlags`, so a configured `false` stays distinct from an error and from omission.+Detailed condition analysis describes v1 release conditions, so a v2 flag reports an empty `conditions` list when a request asks for it; the field stays present because Django's `test_evaluation` reads its absence as a rejected internal request.The core truncates only the hashing subject to 200 Unicode scalar values without normalization; device and experience-continuity overrides are not part of this input.The service adapter must retain eligibility and load/merge property context before invoking it.@@ -77,10 +82,10 @@ The comparison is inclusive, including hash zero at 0%.An empty subject always misses; a nonempty subject at 100% bypasses hashing.Repeated seeds reuse their hash within one evaluation.The evaluator has no database access, writes, events, identity allocation, or gate decisions.-Public response projection and mixed-format service-cache/fallback integration require separate consumers.+`get_match` is its response consumer; the cache builders and the PostgreSQL fallback carry supported v2 rows beside v1.Evaluator fixtures from harness release 1.8.0 are pinned under contract version 2.2.0.`SOURCE.json` lists the vendored subset; its README, manifest, and checksum index keep the upstream bytes, and the integrity test checks each vendored file against that index.-Rollback can remove this dormant consumer while retaining the format-aware readers and rejection required by stored data.+To roll back evaluation, remove the `get_match` dispatch first; supported v2 rows then follow the per-request rejection path, and the format-aware readers required by stored data stay.The production `v1_bucketing` functions accept prescribed hashes for contract tests.Rollout returns included at 100% before identifier resolution or hashing; other percentages use `hash <= percentage / 100.0`.diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex ec619976a8a7..3cf584a6ea41 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -116,9 +116,10 @@ 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`.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.+A config version 1 document (no `version`, or a numeric 1) is published, and so is an active config version 2 document that the shared validator (`validate_config`, under the deployed `MAX_FEATURE_FLAG_FILTER_SIZE_BYTES`) admits; that document is published verbatim and carries no cohort or flag references.+Any other 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 Rust reader parses the published v2 document again; a document Python admits but Rust rejects is served as that one flag with `failed: true` and the `flag_data_parsing_error` reason while the team's other flags evaluate.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`.@@ -126,7 +127,8 @@ Cohort references and flag dependencies are then read from the surviving flags'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 omission, drop, and blanking rule: `omit_unsupported_flags` classifies the raw documents that `from_pg_keeping_undecodable` loads.+`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, keeping an active v2 row whose parse succeeded.+The service's PostgreSQL fallback runs the same classification, so a Redis miss serves the flag set the cache would have carried.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.diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.pyindex c8c0477fdab1..83898f319549 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py@@ -314,7 +314,7 @@ class TestV2PilotLifecycle(AdmittedV2TestCase):assert "pilot-flag" not in {f["key"] for f in _get_flags_response_for_local_evaluation_batch([self.team])[self.team.id]["flags"]}- assert "pilot-flag" not in {f["key"] for f in _get_feature_flags_for_service(self.team)["flags"]}+ assert "pilot-flag" in {f["key"] for f in _get_feature_flags_for_service(self.team)["flags"]}replacement = config(targeted(rule_id=stored["rules"][0]["id"], value=False),diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex d3df3ebaf485..63aa6516245b 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -26,6 +26,7 @@ Manual operations:clear_flags_cache(team_id)"""+import sysfrom collections import defaultdict, dequefrom collections.abc import Mappingfrom datetime import UTC, datetime, timedelta@@ -116,18 +117,49 @@ def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:Inactive/deleted flags return empty deps before their filters are read, tomatch 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.+ readable config version 1 or a supported v2 document, which has no dependencies."""- if _is_unevaluable(flag_data):+ if not _reads_v1_conditions(flag_data):return set()return _parse_dependency_ids(flag_dependency_properties(flag_data.get("filters", {})))+def _reads_v1_conditions(flag_data: dict[str, Any]) -> bool:+ """Whether a serialized flag's release conditions are read: evaluable, and a v1+ document (a kept v2 document has no cohort or flag references)."""+ return not _is_unevaluable(flag_data) and detect_config_format(flag_data.get("filters", {})).kind == "v1"+++def _validates_v2(filters: Mapping[str, Any]) -> bool:+ """Whether the shared validator admits a v2 document under the deployed filter-size+ limit, the bound the Rust reader also applies. Rust may still reject what it cannot+ read; the service then returns that one flag with ``failed: true`` and a+ ``flag_data_parsing_error`` reason and still evaluates the rest.+ """+ # Deferred: the validator imports posthog.hogql, which must stay off the django.setup() path.+ from products.feature_flags.backend.facade.config_validation import ( # noqa: PLC0415+ ConfigValidationError,+ ValidationLimits,+ validate_config,+ )++ limits = ValidationLimits(+ max_config_bytes=settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES, max_metadata_bytes=sys.maxsize+ )+ try:+ validate_config(filters, limits=limits)+ except ConfigValidationError:+ return False+ return True++def _stored_dependency_ids(flag: FeatureFlag) -> set[int] | None:"""The flag ids a stored row's release conditions reference, or ``None`` when thiscache cannot carry the row.- A non-object or non-v1 document is rejected whatever the row's lifecycle, so an+ A non-object document and an unsupported discriminator are rejected whatever the+ row's lifecycle. A v2 document is carried verbatim, with no dependencies, only when+ the row is active and ``_validates_v2`` admits it. Any other v2 row is rejected, so aninactive v2 row is never blanked into a v1-shaped entry. An unevaluable v1 object isnot read, since ``_blank_inactive_filters`` empties it; an evaluable one whoseconditions cannot be read is rejected instead of failing the team.@@ -135,7 +167,10 @@ def _stored_dependency_ids(flag: FeatureFlag) -> set[int] | None:filters = flag.filtersif not isinstance(filters, Mapping):return None- if detect_config_format(filters).kind != "v1":+ kind = detect_config_format(filters).kind+ if kind == "v2":+ return set() if flag.active and not flag.deleted and _validates_v2(filters) else None+ if kind != "v1":return Noneif not flag.active or flag.deleted:return set()@@ -219,7 +254,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 _is_unevaluable(flag):+ if not _reads_v1_conditions(flag):continuecohort_ids |= referenced_cohort_ids(flag.get("filters", {}))return cohort_idsdiff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 2fba92a16df1..5623bd19b87e 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -697,6 +697,16 @@ class TestOmitUnsupportedFlags(BaseTest):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_supported_v2_row_is_dropped_over_the_deployed_limit(self):+ flag = FeatureFlag.objects.create(team=self.team, key="v2-flag", created_by=self.user, filters={})+ FeatureFlag.objects.filter(id=flag.id).update(+ filters={"version": 2, "return_type": "boolean", "default_value": None, "rules": []}+ )++ assert [f["key"] for f in _get_feature_flags_for_service(self.team)["flags"]] == ["v2-flag"]+ with override_settings(MAX_FEATURE_FLAG_FILTER_SIZE_BYTES=32):+ assert _get_feature_flags_for_service(self.team)["flags"] == []+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(diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rsindex 93d598915b68..828a3b8b12b8 100644--- a/rust/feature-flags/src/api/errors.rs+++ b/rust/feature-flags/src/api/errors.rs@@ -163,6 +163,13 @@ impl FlagError {}}+ pub fn flag_evaluation(details: impl std::fmt::Debug) -> Self {+ FlagError::InternalError {+ code: "flag_evaluation_error",+ cause: anyhow::anyhow!("Flag evaluation failed: {details:?}"),+ }+ }+pub fn batch_evaluation_panicked() -> Self {FlagError::InternalError {code: "batch_evaluation_panicked",diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex c6b8e70a78a8..d53e94e53bb4 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -432,7 +432,7 @@ pub struct FlagDetails {pub key: String,pub enabled: bool,pub variant: Option<String>,- #[serde(skip_serializing_if = "std::ops::Not::not")]+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]pub failed: bool,pub reason: FlagEvaluationReason,pub metadata: FlagDetailsMetadata,@@ -534,18 +534,23 @@ impl FromFeatureAndMatch for FlagDetails {payload: flag_match.payload.clone(),has_experiment: flag.has_experiment,},- conditions: if detailed_analysis {- Some(Self::build_condition_analysis(- flag,- flag_match,- property_values,- group_property_values,- flag_evaluation_results,- matching_context,- ))- } else {- None- },+ // The analysis describes v1 release conditions, so a v2 flag reports none. The+ // field stays present: Django's `test_evaluation` reads its absence as a+ // rejected internal request.+ conditions: detailed_analysis.then(|| {+ if flag.filters.is_v1() {+ Self::build_condition_analysis(+ flag,+ flag_match,+ property_values,+ group_property_values,+ flag_evaluation_results,+ matching_context,+ )+ } else {+ Vec::new()+ }+ }),}}diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rsindex 6e593162acf8..e8a3a8edd800 100644--- a/rust/feature-flags/src/bin/flags_cache_builder.rs+++ b/rust/feature-flags/src/bin/flags_cache_builder.rs@@ -1299,13 +1299,13 @@ mod tests {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,+ dummy_s3_client, insert_v1_v2_and_unsupported_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;+ insert_v1_v2_and_unsupported_flags(&context, team.id).await;let redis = Arc::new(MockRedisClient::new());let writer = HyperCacheWriter::new(redis.clone(),@@ -1317,7 +1317,7 @@ mod tests {.await.unwrap_or_else(|failure| panic!("{}", failure.message));- assert_eq!(published_flag_keys(&redis), ["v1-flag"]);+ assert_eq!(published_flag_keys(&redis), ["v1-flag", "v2-flag"]);assert!(!outcome.etag.is_empty());}diff --git a/rust/feature-flags/src/bin/warm-flags-cache.rs b/rust/feature-flags/src/bin/warm-flags-cache.rsindex fb6afa797f6b..a75e2467c14e 100644--- a/rust/feature-flags/src/bin/warm-flags-cache.rs+++ b/rust/feature-flags/src/bin/warm-flags-cache.rs@@ -895,12 +895,12 @@ mod tests {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,+ dummy_s3_client, insert_v1_v2_and_unsupported_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;+ insert_v1_v2_and_unsupported_flags(&context, team.id).await;let redis = Arc::new(MockRedisClient::new());let writer = HyperCacheWriter::new(redis.clone(),@@ -912,7 +912,7 @@ mod tests {.await.expect("warm_team should succeed");- assert_eq!(published_flag_keys(&redis), ["v1-flag"]);+ assert_eq!(published_flag_keys(&redis), ["v1-flag", "v2-flag"]);}/// Regression for the warmer overwriting Django's etag. set() unconditionallydiff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rsindex 18ed24fe4943..51429b738593 100644--- a/rust/feature-flags/src/flags/cache_builder.rs+++ b/rust/feature-flags/src/flags/cache_builder.rs@@ -51,9 +51,7 @@ pub async fn build_flags_cache(pg_reader: PostgresReader,team_id: TeamId,) -> Result<HypercacheFlagsWrapper, FlagError> {- let (mut flags, undecodable) =- FeatureFlagList::from_pg_keeping_undecodable(pg_reader.clone(), team_id).await?;- omit_unsupported_flags(team_id, &mut flags, &undecodable);+ let mut flags = load_supported_flags(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?;@@ -77,10 +75,21 @@ pub(crate) fn is_evaluable(flag: &FeatureFlag) -> bool {flag.active && !flag.deleted}+/// The team's rows minus those this cache cannot carry; the PostgreSQL fallback loads here too.+pub(crate) async fn load_supported_flags(+ pg_reader: PostgresReader,+ team_id: TeamId,+) -> Result<Vec<FeatureFlag>, FlagError> {+ let (mut flags, undecodable) =+ FeatureFlagList::from_pg_keeping_undecodable(pg_reader, team_id).await?;+ omit_unsupported_flags(team_id, &mut flags, &undecodable);+ Ok(flags)+}+/// 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.+/// non-v1 documents unless active and their v2 parse succeeded, 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`.fn omit_unsupported_flags(team_id: TeamId,flags: &mut Vec<FeatureFlag>,@@ -89,15 +98,20 @@ fn omit_unsupported_flags(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,- }+ if !flag.filters.is_v1() {+ return !(is_evaluable(flag) && flag.filters.supported_v2().is_some());+ }+ match undecodable.get(&flag.id) {+ Some(UndecodableDocument::NotAnObject) => true,+ Some(UndecodableDocument::UnreadableV1Object) => is_evaluable(flag),+ None => false,+ }}).map(|flag| flag.id).collect();+ if unsupported.is_empty() {+ return;+ }let mut dependents: HashMap<FeatureFlagId, Vec<FeatureFlagId>> = HashMap::new();for flag in flags.iter() {for dependency_id in extract_direct_flag_dependency_ids(flag) {@@ -113,18 +127,16 @@ fn omit_unsupported_flags(}}}- 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"- );- }+ 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));}@@ -1169,9 +1181,11 @@ mod tests {if flag["expect"] != "kept" {continue;}- let filters = serde_json::to_value(&published[&ids[key]].filters).unwrap();+ let filters = serde_json::to_value(published[&ids[key]]).unwrap()["filters"].take();if flag["blanked"] == true {assert_eq!(filters, serde_json::json!({"groups": []}), "{key}");+ } else if flag["filters"]["version"] == 2 {+ assert_eq!(filters, flag["filters"], "{key}");} else {// Group count and payloads rather than the whole document, because a// JSONB round trip renders `rollout_percentage` as a float.diff --git a/rust/feature-flags/src/flags/config_format.rs b/rust/feature-flags/src/flags/config_format.rsindex a7bb776c5b34..757cd5ff14b9 100644--- a/rust/feature-flags/src/flags/config_format.rs+++ b/rust/feature-flags/src/flags/config_format.rs@@ -94,11 +94,29 @@ impl FlagFilters {if self.is_v1() {Ok(())} else {- Err(FlagError::flag_data_parsing(- "unsupported feature flag configuration format",- ))+ Err(Self::unsupported_format())}}++ pub(crate) fn supported_v2(&self) -> Option<&config_v2::Config> {+ self.non_v1.as_ref()?.parsed_v2.as_ref()?.as_ref().ok()+ }++ pub(crate) fn is_supported(&self) -> bool {+ self.is_v1() || self.supported_v2().is_some()+ }++ pub(crate) fn require_supported(&self) -> Result<(), FlagError> {+ if self.is_supported() {+ Ok(())+ } else {+ Err(Self::unsupported_format())+ }+ }++ fn unsupported_format() -> FlagError {+ FlagError::flag_data_parsing("unsupported feature flag configuration format")+ }}#[derive(Debug, thiserror::Error)]diff --git a/rust/feature-flags/src/flags/evaluate_v2.rs b/rust/feature-flags/src/flags/evaluate_v2.rsindex f10969517c8e..8dd0a37f9a85 100644--- a/rust/feature-flags/src/flags/evaluate_v2.rs+++ b/rust/feature-flags/src/flags/evaluate_v2.rs@@ -11,6 +11,7 @@ use super::config_v2::{Config, Outcome, RolloutMiss, Rule};use super::flag_matching_utils::calculate_hash;use super::flag_request::MAX_DISTINCT_ID_LEN;use super::v1_bucketing::is_in_rollout;+use crate::api::errors::FlagError;use crate::handler::canonical_log::truncate_chars;use crate::properties::property_matching::{match_property_input, FlagMatchingError, PropertyMatchInput, PropertyMatchingContext,@@ -53,6 +54,12 @@ pub enum EvaluationError {Hash,}+impl From<EvaluationError> for FlagError {+ fn from(error: EvaluationError) -> Self {+ FlagError::flag_evaluation(error)+ }+}+#[derive(Clone, Copy)]pub enum PersonProperties<'a> {Complete(&'a HashMap<String, Value>),diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex f29e7434a5bd..2470fc1d02f2 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -7,6 +7,8 @@ use crate::cohorts::cohort_operations::{};use crate::cohorts::membership::{CohortMembershipProvider, NoOpCohortMembershipProvider};use crate::database::{pool_names, PostgresRouter};+use crate::flags::config_v2::Config;+use crate::flags::evaluate_v2::{Evaluation, EvaluationContext, Evaluator, PersonProperties};use crate::flags::flag_group_type_mapping::{GroupTypeCacheManager, GroupTypeIndex, GroupTypeMapping,};@@ -40,6 +42,7 @@ use crate::properties::property_models::{PropertyFilter, PropertyType};use crate::rayon_dispatcher::RayonDispatcher;use crate::utils::graph_utils::PrecomputedDependencyGraph;use anyhow::Result;+use chrono::{DateTime, Utc};use chrono_tz::Tz;use common_metrics::{histogram, inc, timing_guard, timing_guard_high_precision};use common_types::collections::HashMapExt;@@ -403,6 +406,8 @@ pub struct FeatureFlagMatcher {/// relative dates), so flag evaluation matches HogQL/ClickHouse cohort behavior./// Parsed once per request and reused across every property comparison.timezone: Tz,+ /// Request evaluation time. Only v2 relative-date predicates read it; tests pin it.+ now: DateTime<Utc>,}/// Lightweight snapshot of a flag's identity fields, saved before moving@@ -473,9 +478,15 @@ impl FeatureFlagMatcher {detailed_analysis: false,only_use_override_person_properties: false,timezone: Tz::UTC,+ now: Utc::now(),}}+ pub fn with_now(mut self, now: DateTime<Utc>) -> Self {+ self.now = now;+ self+ }+/// Sets the team timezone used to interpret naive datetime filter values./// Defaults to UTC; production must thread the team's timezone through so flag/// evaluation agrees with HogQL/ClickHouse cohort membership near day boundaries.@@ -866,7 +877,7 @@ impl FeatureFlagMatcher {if self.filtered_out_flag_ids.contains(&flag.id) {continue;}- if let Err(error) = flag.filters.require_v1() {+ if let Err(error) = flag.filters.require_supported() {evaluated_flags_map.insert(flag.key.clone(),FlagDetails::create_error(flag, &error, None),@@ -883,7 +894,7 @@ impl FeatureFlagMatcher {let flags: Vec<&FeatureFlag> = evaluation_stages.iter().flatten()- .filter(|flag| flag.filters.is_v1())+ .filter(|flag| flag.filters.is_supported()).collect();// Handle hash key override errors by creating error responses for flags that need experience continuity@@ -891,6 +902,7 @@ impl FeatureFlagMatcher {let hash_key_error = FlagError::HashKeyOverrideError;for flag in flags.iter().filter(|flag| {!self.filtered_out_flag_ids.contains(&flag.id)+ && flag.filters.is_v1()&& flag.ensure_experience_continuity.unwrap_or(false)}) {evaluated_flags_map.insert(@@ -1418,6 +1430,9 @@ impl FeatureFlagMatcher {hash_key_overrides: Option<&HashMap<String, String>>,request_hash_key_override: &Option<String>,) -> Result<FeatureFlagMatch, FlagError> {+ if let Some(config) = flag.filters.supported_v2() {+ return self.get_match_v2(config, person_property_overrides);+ }flag.filters.require_v1()?;// Seed with the lowest-priority "could not evaluate" reason so any real evaluation// result outranks it via `get_highest_priority_match_evaluation`. NoGroupType is@@ -1688,6 +1703,63 @@ impl FeatureFlagMatcher {})}+ /// Projects a v2 outcome onto the v1 match shape: `enabled` is the boolean value (null+ /// default is false), never a variant or payload; the subject is the request distinct ID.+ fn get_match_v2(+ &self,+ config: &Config,+ person_property_overrides: Option<&HashMap<String, Value>>,+ ) -> Result<FeatureFlagMatch, FlagError> {+ // A config without predicates never reads properties, so skip the merge.+ let merged = if config.rules.iter().any(|rule| !rule.targeting.is_empty()) {+ Some(self.get_person_properties(person_property_overrides)?)+ } else {+ None+ };+ // An overrides-only request treats its map as authoritative, as v1 does.+ let properties = match &merged {+ Some(map)+ if self.only_use_override_person_properties+ || self.flag_evaluation_state.get_person_properties().is_some() =>+ {+ PersonProperties::Complete(map)+ }+ Some(map) if person_property_overrides.is_some() => PersonProperties::Partial(map),+ _ => PersonProperties::Unavailable,+ };+ let evaluation = Evaluator::new(config).evaluate(&EvaluationContext {+ person_identifier: &self.distinct_id,+ properties,+ timezone: self.timezone,+ use_explicit_exact_matching: self.use_explicit_exact_matching,+ now: self.now,+ })?;+ let (matches, reason, condition_index) = match evaluation {+ Evaluation::TargetingMatch { value, rule } => (+ value,+ FeatureFlagMatchReason::ConditionMatch,+ Some(rule.index),+ ),+ Evaluation::RolloutMiss { value, rule } => (+ value.unwrap_or(false),+ FeatureFlagMatchReason::OutOfRolloutBound,+ Some(rule.index),+ ),+ Evaluation::NoRuleMatch { value } => (+ value.unwrap_or(false),+ FeatureFlagMatchReason::NoConditionMatch,+ None,+ ),+ };+ Ok(FeatureFlagMatch {+ matches,+ variant: None,+ reason,+ condition_index,+ payload: None,+ })+ }+/// This function determines the highest priority match evaluation for feature flag conditions./// It compares the current match reason with a new match reason and returns the higher priority one./// The priority is determined by the ordering of FeatureFlagMatchReason variants.diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rsindex 188b1197127f..b3acacb63504 100644--- a/rust/feature-flags/src/flags/flag_operations.rs+++ b/rust/feature-flags/src/flags/flag_operations.rs@@ -39,11 +39,20 @@ impl FeatureFlag {/// OR if the flag has a group property filter that `group_filter_needs_db` selects/// (the caller owns the request's group context — see/// `FeatureFlagMatcher::group_filter_needs_db_prep`)+ ///+ /// A supported v2 flag needs it only when a predicate key is absent from the overrides.pub fn requires_db_preparation(&self,overrides: &HashMap<String, Value>,group_filter_needs_db: &dyn Fn(&PropertyFilter, Option<GroupTypeIndex>) -> bool,) -> bool {+ if let Some(config) = self.filters.supported_v2() {+ return config+ .rules+ .iter()+ .flat_map(|rule| &rule.targeting)+ .any(|predicate| !overrides.contains_key(&predicate.key));+ }self.filters.requires_db_properties(overrides, &self.key, group_filter_needs_db)|| self.filters.requires_cohort_filters()@@ -1332,6 +1341,29 @@ mod tests {}}+ #[test]+ fn test_v2_requires_db_preparation_only_when_a_predicate_key_is_missing() {+ let flag: FeatureFlag = serde_json::from_value(json!({+ "id": 1, "team_id": 1, "key": "v2", "active": true,+ "filters": {"version": 2, "return_type": "boolean", "default_value": false, "rules": [+ {"id": "a1a1a1a1-a1a1-4a1a-8a1a-a1a1a1a1a1a1", "rule_type": "targeted_release",+ "value": true, "targeting": {"properties": [+ {"key": "a", "type": "person", "operator": "exact", "value": "1", "negation": false},+ {"key": "b", "type": "person", "operator": "exact", "value": "2", "negation": false}+ ]}}+ ]}+ }))+ .unwrap();++ assert!(+ flag.requires_db_preparation(&HashMap::from([("a".into(), json!("1"))]), &|_, _| true)+ );+ assert!(!flag.requires_db_preparation(+ &HashMap::from([("a".into(), json!("1")), ("b".into(), json!("2"))]),+ &|_, _| true+ ));+ }+#[test]fn test_does_not_require_db_preparation_if_holdout_set() {use crate::flags::flag_models::Holdout;diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rsindex cdd6ebed8d4b..c48c8ca1bd40 100644--- a/rust/feature-flags/src/flags/flag_service.rs+++ b/rust/feature-flags/src/flags/flag_service.rs@@ -2,7 +2,7 @@ use crate::{api::errors::FlagError,flags::{flag_definitions_cache::FlagDefinitionsCache,- flag_models::{FeatureFlagList, HypercacheFlagsWrapper, PreparedFlagDefinitions},+ flag_models::{HypercacheFlagsWrapper, PreparedFlagDefinitions},},handler::canonical_log::with_canonical_log,metrics::consts::{@@ -282,7 +282,11 @@ impl FlagService {);// PG has no dependency metadata, so all flags go in a single stage.- let flags = FeatureFlagList::from_pg(self.pg_client.clone(), team_id).await?;+ let flags = crate::flags::cache_builder::load_supported_flags(+ self.pg_client.clone(),+ team_id,+ )+ .await?;let evaluation_metadata =crate::flags::flag_models::EvaluationMetadata::single_stage(&flags);let wrapper = HypercacheFlagsWrapper {@@ -307,7 +311,7 @@ mod tests {feature_flag_list::PreparedFlags,flag_definitions_cache::FlagDefinitionsCache,flag_models::{- EvaluationMetadata, FeatureFlag, FlagFilters, FlagPropertyGroup,+ EvaluationMetadata, FeatureFlag, FeatureFlagList, FlagFilters, FlagPropertyGroup,HypercacheFlagsWrapper,},test_helpers::{hypercache_test_key, update_flags_in_hypercache},diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 539a0ae3a558..a7172346e511 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -7615,7 +7615,18 @@ mod tests {key: "test-flag-normal".mock_into());- let flags = flag_list_with_metadata(vec![flag_with_continuity, flag_without_continuity]);+ let v2_flag_with_continuity: FeatureFlag = serde_json::from_value(json!({+ "id": 3, "team_id": team.id, "key": "test-flag-v2-continuity", "active": true,+ "ensure_experience_continuity": true,+ "filters": {"version": 2, "return_type": "boolean", "default_value": false, "rules": []}+ }))+ .unwrap();++ let flags = flag_list_with_metadata(vec![+ flag_with_continuity,+ flag_without_continuity,+ v2_flag_with_continuity,+ ]);// Build dependency graph for the flagslet precomputed = PrecomputedDependencyGraph::build(&flags, None);@@ -7669,6 +7680,13 @@ mod tests {"Normal flag should not have hash override error");}++ let v2_response = &response.flags["test-flag-v2-continuity"];+ assert!(+ !v2_response.failed,+ "v2 flag with continuity should evaluate despite the hash override error"+ );+ assert_eq!(v2_response.reason.code, "no_condition_match");}#[tokio::test]diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex 5df9281dbf2c..a4e8a3ff3068 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -278,7 +278,7 @@ 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) {+pub async fn insert_v1_v2_and_unsupported_flags(context: &TestContext, team_id: i32) {for (key, filters) in [("v1-flag",@@ -288,6 +288,7 @@ pub async fn insert_v1_and_v2_flags(context: &TestContext, team_id: i32) {"v2-flag",json!({"version": 2, "return_type": "boolean", "default_value": false, "rules": []}),),+ ("v3-flag", json!({"version": 3})),] {context.insert_flag(@@ -317,7 +318,9 @@ pub fn published_flag_keys(redis: &MockRedisClient) -> Vec<String> {panic!("unexpected write {:?}", written.value)};let wrapper: HypercacheFlagsWrapper = serde_json::from_str(&payload).unwrap();- wrapper.flags.into_iter().map(|flag| flag.key).collect()+ let mut keys: Vec<String> = wrapper.flags.into_iter().map(|flag| flag.key).collect();+ keys.sort();+ keys}/// Create a HyperCacheReader for tests using the provided Redis client.diff --git a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.jsonindex 090aa1949330..2bf9c4c98c8b 100644--- a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json+++ b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json@@ -1,5 +1,5 @@{- "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.",+ "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 (a supported active config version 2 row is kept verbatim); otherwise it is `unsupported` (a document the builders reject, including an inactive or archived version 2 row, 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": [{@@ -94,7 +94,7 @@}]},- "expect": "unsupported"+ "expect": "kept"},{"key": "v2-malformed-active",@@ -102,6 +102,29 @@"filters": { "version": 2, "groups": [{ "properties": [], "rollout_percentage": 100 }] },"expect": "unsupported"},+ {+ "key": "v2-unsupported-family-active",+ "active": true,+ "filters": {+ "version": 2,+ "return_type": "boolean",+ "default_value": false,+ "rules": [+ {+ "id": "e5e5e5e5-e5e5-4e5e-8e5e-e5e5e5e5e5e5",+ "rule_type": "experiment",+ "targeting": { "properties": [] },+ "experiment_id": 1,+ "rollout_percentage": 100,+ "on_rollout_miss": "continue",+ "assignment_algorithm": "sha1_60_v1",+ "seed": "release-experiment",+ "variants": [{ "key": "control", "value": false, "rollout_percentage": 100 }]+ }+ ]+ },+ "expect": "unsupported"+ },{"key": "v2-valid-inactive","active": false,@@ -193,7 +216,7 @@}]},- "expect": "dependent"+ "expect": "kept"},{"key": "depends-false-on-v2-valid-inactive",@@ -253,7 +276,7 @@}]},- "expect": "dependent"+ "expect": "kept"},{"key": "depends-false-on-inactive-v1",diff --git a/rust/feature-flags/tests/test_config_format.rs b/rust/feature-flags/tests/test_config_format.rsindex b49f6c66b60d..302516746114 100644--- a/rust/feature-flags/tests/test_config_format.rs+++ b/rust/feature-flags/tests/test_config_format.rs@@ -13,7 +13,7 @@ use feature_flags::flags::flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, HypercacheFlagsWrapper,};use feature_flags::utils::test_utils::{- mock_group_type_cache, setup_redis_client, update_team_in_hypercache,+ flag_list_with_metadata, mock_group_type_cache, setup_redis_client, update_team_in_hypercache,write_flags_wire_json_to_redis, TestContext,};use rstest::rstest;@@ -28,14 +28,14 @@ fn documents() -> Vec<(String, Value, bool, bool)> {"fixtures/rules_v2_parser/2.1.0/fixtures/config/valid/boolean_targeted_and_percentage_rollout.json")).unwrap();cases.push((- "rejected-valid-v2".to_string(),+ "evaluated-valid-v2".to_string(),supported.clone(),true,false,));let mut rounded = supported.clone();rounded["version"] = json!("__rounds_to_two__");- cases.push(("rejected-rounded-v2".to_string(), rounded, true, false));+ cases.push(("evaluated-rounded-v2".to_string(), rounded, true, false));let mut near_one = supported.clone();near_one["version"] = json!("__below_one__");cases.push(("rejected-below-one".to_string(), near_one, true, false));@@ -133,7 +133,7 @@ const RAW_NUMBERS: &[(&str, &str, &str)] = &[("one-rounded", "__rounds_to_one__", "1.0000000000000001"),("rejected-below-one", "__below_one__", "0.9999999999999999"),(- "rejected-rounded-v2",+ "evaluated-rounded-v2","__rounds_to_two__","2.0000000000000001",),@@ -160,14 +160,9 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: booldb.insert_flag(team.id,Some(FeatureFlagRow {- team_id: team.id,- key,- name: Some(String::new()),- filters,- active,deleted,version: Some(2),- ..Default::default()+ ..row(team.id, &key, filters, active)}),).await?;@@ -202,8 +197,8 @@ 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);- // The cache builder omits every non-v1 row instead of failing the team; the- // evaluator's PostgreSQL fallback below still sees them.+ // The cache builder keeps the supported v2 rows and omits every other non-v1+ // row instead of failing the team; the service's PostgreSQL fallback does the same.let mut built: Vec<String> = build_flags_cache(db.non_persons_reader.clone(), team.id).await?.flags@@ -211,7 +206,7 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: bool.map(|flag| flag.key).collect();built.sort();- assert_eq!(built, vec!["absent", "one", "one-float", "one-rounded"]);+ assert_eq!(built, EVALUATED);}let stored = if cached {let reader = HyperCacheReader::new_with_s3_client(@@ -233,8 +228,8 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: boolFeatureFlagList::from_pg(db.non_persons_reader.clone(), team.id).await?};for (key, valid) in [- ("rejected-valid-v2", true),- ("rejected-rounded-v2", true),+ ("evaluated-valid-v2", true),+ ("evaluated-rounded-v2", true),("rejected-overprecise-v2", false),] {let flag = stored.iter().find(|flag| flag.key == key).unwrap();@@ -252,37 +247,11 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: bool}let server = common::ServerHandle::for_config(DEFAULT_TEST_CONFIG.clone()).await;let client = reqwest::Client::new();- let payload = json!({"token": team.api_token, "distinct_id": "example-person"});+ let payload = json!({"token": team.api_token, "distinct_id": "example-person",+ "person_properties": {"account_tier": "preview"}});+ let rejected_rows_reach_matcher = cached;- for (endpoint, version, errors_reported, shape) in [- ("flags", "2", true, Shape::Detailed),- (- "flags",- "1",- true,- Shape::Map {- keeps_rejected_as_false: true,- },- ),- ("decide", "1", false, Shape::EnabledKeys),- (- "decide",- "2",- false,- Shape::Map {- keeps_rejected_as_false: false,- },- ),- (- "decide",- "3",- true,- Shape::Map {- keeps_rejected_as_false: true,- },- ),- ("decide", "4", true, Shape::Detailed),- ] {+ for (endpoint, version, has_error_field, shape) in FORMATS {let response = client.post(format!("http://{}/flags?v={version}&config=false",@@ -295,19 +264,30 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: boolassert_eq!(response.status(), 200, "{endpoint} v{version}");assert_eq!(response.headers()["content-type"], "application/json");let body: Value = response.json().await?;- if errors_reported {- assert_eq!(body["errorsWhileComputingFlags"], true, "{body}");+ if has_error_field {+ assert_eq!(+ body["errorsWhileComputingFlags"], rejected_rows_reach_matcher,+ "{body}"+ );} else {assert!(body.get("errorsWhileComputingFlags").is_none(), "{body}");}match shape {Shape::Detailed => {- for key in ["absent", "one", "one-float", "one-rounded"] {+ for key in EVALUATED {assert_eq!(body["flags"][key]["enabled"], true, "{body}");assert_eq!(body["flags"][key]["metadata"]["version"], 2, "{body}");+ assert!(body["flags"][key].get("failed").is_none(), "{body}");+ assert!(body["flags"][key]["variant"].is_null(), "{body}");+ assert_eq!(body["flags"][key]["reason"]["code"], "condition_match");+ if key.starts_with("evaluated-") {+ assert!(body["flags"][key]["metadata"]["payload"].is_null());+ }}for (key, _, active, deleted) in &docs {- if key.starts_with("rejected-") {+ if key.starts_with("rejected-") && !rejected_rows_reach_matcher {+ assert!(body["flags"].get(key).is_none(), "{body}");+ } else if key.starts_with("rejected-") {assert_eq!(body["flags"][key]["failed"], true, "{body}");assert_eq!(body["flags"][key]["reason"]["code"],@@ -326,22 +306,14 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: boolShape::EnabledKeys => {let mut keys = body["featureFlags"].as_array().unwrap().clone();keys.sort_by(|a, b| a.as_str().cmp(&b.as_str()));- assert_eq!(- keys,- vec![- json!("absent"),- json!("one"),- json!("one-float"),- json!("one-rounded")- ]- );+ assert_eq!(keys, EVALUATED.map(Value::from));}- Shape::Map {- keeps_rejected_as_false,- } => {- let mut expected =- json!({"absent": true, "one": true, "one-float": true, "one-rounded": true});- if keeps_rejected_as_false {+ Shape::Map { enabled_only } => {+ let mut expected = json!({});+ for key in EVALUATED {+ expected[key] = json!(true);+ }+ if rejected_rows_reach_matcher && !enabled_only {for (key, _, _, _) in &docs {if key.starts_with("rejected-") {expected[key] = json!(false);@@ -359,26 +331,72 @@ async fn config_dispatch_preserves_siblings_and_wire_errors(#[case] cached: boolenum Shape {Detailed,EnabledKeys,- Map { keeps_rejected_as_false: bool },+ Map { enabled_only: bool },}-#[tokio::test]-async fn non_v1_rejects_before_preparation_and_missing_dependency_default() {- let db = TestContext::new(None).await;- let cohort_cache = Arc::new(CohortCacheManager::new(- db.non_persons_reader.clone(),- None,- None,- ));- let mut matcher = FeatureFlagMatcher::new(+const FORMATS: [(&str, &str, bool, Shape); 6] = [+ ("flags", "2", true, Shape::Detailed),+ (+ "flags",+ "1",+ true,+ Shape::Map {+ enabled_only: false,+ },+ ),+ ("decide", "1", false, Shape::EnabledKeys),+ ("decide", "2", false, Shape::Map { enabled_only: true }),+ (+ "decide",+ "3",+ true,+ Shape::Map {+ enabled_only: false,+ },+ ),+ ("decide", "4", true, Shape::Detailed),+];++fn row(team_id: i32, key: &str, filters: Value, active: bool) -> FeatureFlagRow {+ FeatureFlagRow {+ team_id,+ key: key.to_string(),+ name: Some(String::new()),+ filters,+ active,+ ..Default::default()+ }+}++fn matcher(db: &TestContext) -> FeatureFlagMatcher {+ FeatureFlagMatcher::new("example-person".to_string(),None,1,db.create_postgres_router(),- cohort_cache,+ Arc::new(CohortCacheManager::new(+ db.non_persons_reader.clone(),+ None,+ None,+ )),mock_group_type_cache(HashMap::new()),None,- );+ )+}++const EVALUATED: [&str; 6] = [+ "absent",+ "evaluated-rounded-v2",+ "evaluated-valid-v2",+ "one",+ "one-float",+ "one-rounded",+];++#[tokio::test]+async fn non_v1_rejects_before_preparation_and_missing_dependency_default() {+ let db = TestContext::new(None).await;+ let mut matcher = matcher(&db);let flag: FeatureFlag = serde_json::from_value(json!({"id": 1, "team_id": 1, "key": "rejected", "active": true,"ensure_experience_continuity": true,@@ -416,20 +434,7 @@ async fn non_v1_rejects_before_preparation_and_missing_dependency_default() {#[tokio::test]async fn a_dependent_v1_flag_still_matches_against_a_non_v1_dependency() {let db = TestContext::new(None).await;- let cohort_cache = Arc::new(CohortCacheManager::new(- db.non_persons_reader.clone(),- None,- None,- ));- let mut matcher = FeatureFlagMatcher::new(- "example-person".to_string(),- None,- 1,- db.create_postgres_router(),- cohort_cache,- mock_group_type_cache(HashMap::new()),- None,- );+ let mut matcher = matcher(&db);let flags: Vec<FeatureFlag> = serde_json::from_value(json!([{"id": 1, "team_id": 1, "key": "blocker", "active": true,"filters": {"version": 2, "groups": [{"rollout_percentage": 100}]}},@@ -461,3 +466,199 @@ async fn a_dependent_v1_flag_still_matches_against_a_non_v1_dependency() {assert!(response.flags["dependent"].enabled);assert!(response.errors_while_computing_flags);}++#[rstest]+#[case::redis(true)]+#[case::postgres_fallback(false)]+#[tokio::test]+async fn mixed_team_projects_supported_v2_beside_v1(#[case] cached: bool) -> Result<()> {+ let db = TestContext::new(None).await;+ let team = db.insert_new_team(None).await?;+ let redis = setup_redis_client(Some(DEFAULT_TEST_CONFIG.redis_url.clone())).await;+ update_team_in_hypercache(redis.clone(), &team).await?;+ for (distinct_id, tier) in [("example-person", "preview"), ("other-person", "standard")] {+ db.insert_person(+ team.id,+ distinct_id.to_string(),+ Some(json!({"account_tier": tier})),+ )+ .await?;+ }+ let v2 = |default_value: Value, rules: Value| json!({"version": 2, "return_type": "boolean", "default_value": default_value, "rules": rules});+ let targeted = json!([{"id": "a1a1a1a1-a1a1-4a1a-8a1a-a1a1a1a1a1a1", "rule_type": "targeted_release",+ "targeting": {"properties": [{"key": "account_tier", "type": "person", "operator": "exact", "value": "preview"}]},+ "value": true}]);+ let malformed = db+ .insert_flag(+ team.id,+ Some(row(+ team.id,+ "v2-malformed",+ json!({"version": 2, "groups": [{"rollout_percentage": 100}]}),+ true,+ )),+ )+ .await?;+ for (key, filters, active) in [+ (+ "v1-on",+ json!({"groups": [{"rollout_percentage": 100}]}),+ true,+ ),+ (+ "v1-off",+ json!({"groups": [{"rollout_percentage": 0}]}),+ true,+ ),+ ("v2-targeted", v2(json!(false), targeted), true),+ ("v2-default-null", v2(Value::Null, json!([])), true),+ ("v2-inactive", v2(json!(true), json!([])), false),+ (+ "v1-depends-on-malformed",+ json!({"groups": [{"rollout_percentage": 100, "properties": [+ {"type": "flag", "key": malformed.id.to_string(), "value": false, "operator": "flag_evaluates_to"}]}]}),+ true,+ ),+ (+ "unsupported-version",+ json!({"version": 3, "groups": [{"rollout_percentage": 100}]}),+ true,+ ),+ ] {+ db.insert_flag(team.id, Some(row(team.id, key, filters, active)))+ .await?;+ }+ let wrapper = build_flags_cache(db.non_persons_reader.clone(), team.id).await?;+ let mut built: Vec<&str> = wrapper.flags.iter().map(|flag| flag.key.as_str()).collect();+ built.sort();+ assert_eq!(built, ["v1-off", "v1-on", "v2-default-null", "v2-targeted"]);+ if cached {+ write_flags_wire_json_to_redis(redis.clone(), team.id, serde_json::to_string(&wrapper)?)+ .await?;+ }++ let server = common::ServerHandle::for_config(DEFAULT_TEST_CONFIG.clone()).await;+ let client = reqwest::Client::new();+ for (distinct_id, targeted_value) in [("example-person", true), ("other-person", false)] {+ let payload = json!({"token": team.api_token, "distinct_id": distinct_id});+ let expected = json!({"v1-on": true, "v1-off": false,+ "v2-targeted": targeted_value, "v2-default-null": false});+ let enabled_keys = || {+ let mut keys: Vec<Value> = expected+ .as_object()+ .unwrap()+ .iter()+ .filter(|(_, value)| **value == true)+ .map(|(key, _)| json!(key))+ .collect();+ keys.sort_by(|a, b| a.as_str().cmp(&b.as_str()));+ keys+ };+ for (endpoint, version, has_error_field, shape) in FORMATS {+ let body: Value = client+ .post(format!(+ "http://{}/flags?v={version}&config=false",+ server.addr+ ))+ .header("X-Original-Endpoint", endpoint)+ .json(&payload)+ .send()+ .await?+ .error_for_status()?+ .json()+ .await?;+ if has_error_field {+ assert_eq!(body["errorsWhileComputingFlags"], false, "{body}");+ }+ match shape {+ Shape::Detailed => {+ let flags = body["flags"].as_object().unwrap();+ assert_eq!(flags.len(), 4, "{body}");+ for (key, value) in expected.as_object().unwrap() {+ assert_eq!(flags[key]["enabled"], *value, "{body}");+ assert!(flags[key].get("failed").is_none(), "{body}");+ assert!(flags[key]["variant"].is_null(), "{body}");+ assert!(flags[key]["metadata"]["payload"].is_null(), "{body}");+ }+ assert_eq!(+ flags["v2-default-null"]["reason"]["code"],+ "no_condition_match"+ );+ assert_eq!(+ flags["v2-targeted"]["reason"]["code"],+ if targeted_value {+ "condition_match"+ } else {+ "no_condition_match"+ }+ );+ }+ Shape::EnabledKeys => {+ let mut keys = body["featureFlags"].as_array().unwrap().clone();+ keys.sort_by(|a, b| a.as_str().cmp(&b.as_str()));+ assert_eq!(keys, enabled_keys(), "{body}");+ }+ Shape::Map { enabled_only } => {+ let mut map = expected.clone();+ if enabled_only {+ map.as_object_mut()+ .unwrap()+ .retain(|_, value| value == true);+ } else {+ assert_eq!(body["featureFlagPayloads"], json!({}), "{body}");+ }+ assert_eq!(body["featureFlags"], map, "{endpoint} v{version}");+ }+ }+ }+ let single: Value = client+ .post(format!("http://{}/flags?v=2&config=false", server.addr))+ .json(&json!({"token": team.api_token, "distinct_id": distinct_id, "flag_keys": ["v2-targeted"]}))+ .send()+ .await?+ .error_for_status()?+ .json()+ .await?;+ assert_eq!(single["flags"].as_object().unwrap().len(), 1, "{single}");+ assert_eq!(single["flags"]["v2-targeted"]["enabled"], targeted_value);+ assert_eq!(single["errorsWhileComputingFlags"], false);+ }+ Ok(())+}++#[tokio::test]+async fn detailed_analysis_is_empty_for_a_v2_flag_and_kept_for_v1() {+ let db = TestContext::new(None).await;+ let mut matcher = matcher(&db).with_detailed_analysis(true);+ let flags: Vec<FeatureFlag> = serde_json::from_value(json!([+ {"id": 1, "team_id": 1, "key": "v1", "active": true,+ "filters": {"groups": [{"rollout_percentage": 100}]}},+ {"id": 2, "team_id": 1, "key": "v2", "active": true,+ "filters": {"version": 2, "return_type": "boolean", "default_value": false, "rules": [+ {"id": "a1a1a1a1-a1a1-4a1a-8a1a-a1a1a1a1a1a1", "rule_type": "targeted_release",+ "targeting": {"properties": []}, "value": true}]}}+ ]))+ .unwrap();+ let response = matcher+ .evaluate_all_feature_flags(+ flag_list_with_metadata(flags),+ None,+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();+ assert!(!response.errors_while_computing_flags);+ assert_eq!(+ response.flags["v1"].conditions.as_ref().map(Vec::len),+ Some(1)+ );+ assert!(response.flags["v2"].enabled);+ assert_eq!(+ response.flags["v2"].conditions.as_ref().map(Vec::len),+ Some(0)+ );+}diff --git a/rust/feature-flags/tests/test_rules_v2_evaluation.rs b/rust/feature-flags/tests/test_rules_v2_evaluation.rsindex cc5dae34e1b0..52b66cbe86b2 100644--- a/rust/feature-flags/tests/test_rules_v2_evaluation.rs+++ b/rust/feature-flags/tests/test_rules_v2_evaluation.rs@@ -2,7 +2,7 @@ use std::collections::{BTreeMap, BTreeSet};use std::sync::Arc;use feature_flags::flags::config_v2::{Outcome, ParseError};-use feature_flags::flags::evaluate_v2::{Evaluation, EvaluationError, Evaluator};+use feature_flags::flags::evaluate_v2::{Evaluation, EvaluationError, Evaluator, PersonProperties};use feature_flags::flags::feature_flag_list::PreparedFlags;use feature_flags::flags::flag_matching_utils::calculate_hash;use feature_flags::flags::flag_request::MAX_DISTINCT_ID_LEN;@@ -175,7 +175,7 @@ fn parsed_configs_match_every_core_case_without_mutating_cached_inputs() {}#[tokio::test]-async fn corpus_eligibility_uses_the_request_boundary_and_valid_v2_stays_closed() {+async fn corpus_eligibility_uses_the_request_boundary_and_valid_v2_is_evaluated() {use feature_flags::config::DEFAULT_TEST_CONFIG;use feature_flags::utils::test_utils::{insert_flags_for_team_in_redis, insert_new_team_in_redis, setup_redis_client,@@ -230,11 +230,9 @@ async fn corpus_eligibility_uses_the_request_boundary_and_valid_v2_stays_closed(.await.unwrap();assert_eq!(body["flags"]["healthy"]["enabled"], true);- assert_eq!(body["flags"]["eligible-v2"]["failed"], true);- assert_eq!(- body["flags"]["eligible-v2"]["reason"]["code"],- "flag_data_parsing_error"- );+ assert_eq!(body["flags"]["eligible-v2"]["enabled"], true);+ assert!(body["flags"]["eligible-v2"].get("failed").is_none());+ assert_eq!(body["errorsWhileComputingFlags"], false);for case in &cases {assert!(body["flags"].get(case["id"].as_str().unwrap()).is_none());assert_eq!(case["expected"], json!({"status":"omitted"}));@@ -380,3 +378,168 @@ fn evaluation_is_repeatable_and_diagnostics_do_not_retain_inputs() {assert!(matches!(result, Ok(Evaluation::TargetingMatch { .. })));assert!(!format!("{evaluator:?} {result:?}").contains("sensitive-seed"));}++/// Complete properties come from a stored person and run through the request path. The+/// service reads the person for a missing predicate key and treats an overrides-only+/// request as complete, so partial and unavailable context exist only below that path:+/// those cases reach `get_match` directly, with no preparation.+#[tokio::test]+async fn corpus_cases_project_through_the_matcher_and_the_legacy_formats() {+ use feature_flags::api::types::{+ DecideV1Response, DecideV2Response, FlagValue, FlagsResponse, LegacyFlagsResponse,+ };+ use feature_flags::cohorts::cohort_cache_manager::CohortCacheManager;+ use feature_flags::flags::flag_matching::FeatureFlagMatcher;+ use feature_flags::utils::test_utils::{+ flag_list_with_metadata, mock_group_type_cache, TestContext,+ };+ use std::collections::HashMap;++ let db = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ db.non_persons_reader.clone(),+ None,+ None,+ ));+ let (mut projected, mut direct, mut skipped) = (0, 0, 0);+ for case in corpus::cases() {+ let id = case["id"].as_str().unwrap();+ let properties = corpus::properties(&case);+ let context = corpus::context(&case, &properties);+ // White-box needs the hash seam, eligibility the request boundary.+ if matches!(+ case["family"].as_str().unwrap(),+ "white_box" | "eligibility"+ ) {+ skipped += 1;+ continue;+ }+ let team = db.insert_new_team(None).await.unwrap();+ let mut flag = corpus::read(&case);+ flag.team_id = team.id;+ let mut matcher = FeatureFlagMatcher::new(+ context.person_identifier.to_string(),+ None,+ team.id,+ db.create_postgres_router(),+ cohort_cache.clone(),+ mock_group_type_cache(HashMap::new()),+ None,+ )+ .with_timezone(context.timezone)+ .with_explicit_exact_matching(context.use_explicit_exact_matching)+ .with_now(context.now);+ let expected = &case["expected"];+ let failed = expected["status"] != "success";+ let enabled = expected["value"].as_bool().unwrap_or(false);+ let reason = match expected["reason"].as_str() {+ Some("targeting_match") => "condition_match",+ Some("rollout_miss") => "out_of_rollout_bound",+ _ => "no_condition_match",+ };+ let rule_index = expected["rule"]["index"].as_i64();+ let PersonProperties::Complete(_) = context.properties else {+ let overrides =+ matches!(context.properties, PersonProperties::Partial(_)).then_some(&properties);+ match matcher.get_match(&flag, overrides, None, None, &None) {+ Ok(outcome) => {+ assert!(!failed, "{id}");+ assert_eq!(+ (+ outcome.matches,+ outcome.reason.to_string(),+ outcome.condition_index+ ),+ (enabled, reason.to_string(), rule_index.map(|i| i as usize)),+ "{id}"+ );+ assert_eq!((outcome.variant, outcome.payload), (None, None), "{id}");+ }+ Err(error) => {+ assert!(failed, "{id}");+ assert_eq!(+ error.evaluation_error_code(),+ "flag_evaluation_error",+ "{id}"+ );+ }+ }+ direct += 1;+ continue;+ };+ if !properties.is_empty() {+ db.insert_person(+ team.id,+ context.person_identifier.to_string(),+ Some(json!(properties)),+ )+ .await+ .unwrap();+ }+ let key = flag.key.clone();+ let response = matcher+ .evaluate_all_feature_flags(+ flag_list_with_metadata(vec![flag]),+ None,+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();+ let details = &response.flags[&key];+ assert_eq!(+ (+ details.failed,+ details.enabled,+ &details.variant,+ &details.metadata.payload+ ),+ (failed, enabled, &None, &None),+ "{id}"+ );+ assert_eq!(response.errors_while_computing_flags, failed, "{id}");+ if failed {+ let expected_code = if case["family"] == "parser" {+ "flag_data_parsing_error"+ } else {+ "flag_evaluation_error"+ };+ assert_eq!(details.reason.code, expected_code, "{id}");+ } else {+ assert_eq!(details.reason.code, reason, "{id}");+ assert_eq!(+ details.reason.condition_index.map(i64::from),+ rule_index,+ "{id}"+ );+ }+ let wire = serde_json::to_value(&response).unwrap();+ let reparse = || serde_json::from_value::<FlagsResponse>(wire.clone()).unwrap();+ let legacy = LegacyFlagsResponse::from_response(reparse());+ assert_eq!(+ legacy.feature_flags[&key],+ FlagValue::Boolean(enabled),+ "{id}"+ );+ assert!(legacy.feature_flag_payloads.is_empty(), "{id}");+ assert_eq!(+ DecideV1Response::from_response(reparse())+ .feature_flags+ .contains(&key),+ enabled,+ "{id}"+ );+ assert_eq!(+ DecideV2Response::from_response(reparse())+ .feature_flags+ .get(&key),+ enabled.then_some(FlagValue::Boolean(true)).as_ref(),+ "{id}"+ );+ projected += 1;+ }+ assert_eq!((projected, direct, skipped), (114, 8, 13));+}