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): dispatch stored config formats before evaluation (#101470)

Anders4ee2ad5cc893
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 1fd71f66f187..35fc66e26f9e 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -4,6 +4,32 @@ The Rust feature flags service evaluates flags using a deterministic, hash-based
## Architecture overview
+Stored 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; every other value, 2 included, is a format this service does not evaluate.
+The classification matches Python's `detect_config_format` (`products/feature_flags/backend/facade/config.py`).
+
+Cache and PostgreSQL ingress classify the original document before decoding v1 fields.
+Non-v1 objects stay opaque in the filters passthrough map so cache round trips retain them and the cache byte budget includes them.
+
+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.
+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.
+Malformed v1 documents retain the existing ingress error behavior.
+
+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.
+`/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.
+
+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`.
+Variant selection adds each `weight / 100.0` from left to right and uses `hash < cumulative`.
+V1 returns no variant beyond the final boundary, including at hash 1.
+
```text
┌─────────────────────────────────────────────────────────────────┐
│ evaluate_all_feature_flags │
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index 2de46b43a609..2f2742e73a46 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -122,7 +122,7 @@ Inactive and deleted flags are skipped before that read (`_is_unevaluable`), so
Because that filtering happens before the matcher reads `filters`, an inactive flag can never affect a response, so the payload keeps only evaluable flags plus the inactive flags that another flag's dependency conditions reference.
A referenced entry is load-bearing: the matcher pre-seeds its id as false, so a dependent with `flag_evaluates_to: false` on a disabled flag still matches instead of missing a dependency.
`_drop_unreferenced_unevaluable_flags` removes the rest, `evaluation_metadata` is computed on the surviving set, and `_blank_inactive_filters` replaces the kept unevaluable flags' `filters` with an empty `{"groups": []}` before the payload is written.
-`build_flags_cache` in `rust/feature-flags/src/flags/cache_builder.rs` writes the same entry and applies the same drop and blanking.
+`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.
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.
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index f2ae90305c24..bb57c8e25729 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -107,6 +107,7 @@ pub enum BatchFlagEvaluationError {
FlagNotFound,
FlagInactive,
GroupAggregatedFlag,
+ UnsupportedConfigFormat,
VersionConflict { expected: i32, actual: i32 },
PropertyMatchingVersionConflict { expected: i16, actual: i16 },
Upstream(FlagError),
@@ -121,6 +122,7 @@ impl BatchFlagEvaluationError {
Self::FlagNotFound => "flag_not_found",
Self::FlagInactive => "flag_inactive",
Self::GroupAggregatedFlag => "group_aggregated_flag",
+ Self::UnsupportedConfigFormat => "unsupported_config_format",
Self::VersionConflict { .. } => "version_conflict",
Self::PropertyMatchingVersionConflict { .. } => "property_matching_version_conflict",
Self::Upstream(_) => "upstream_error",
@@ -169,6 +171,13 @@ impl IntoResponse for BatchFlagEvaluationError {
None,
None,
),
+ Self::UnsupportedConfigFormat => (
+ StatusCode::BAD_REQUEST,
+ "unsupported_config_format",
+ "Flag is stored in a configuration format this service does not evaluate".to_string(),
+ None,
+ None,
+ ),
Self::VersionConflict { expected, actual } => (
StatusCode::CONFLICT,
"version_conflict",
@@ -386,13 +395,18 @@ async fn handle_batch_flag_evaluation(
let target = &flags_vec[target_index];
// The Django caller already returns [] for group-aggregated and inactive flags
- // without calling us; these guards are defensive.
+ // without calling us; those two guards are defensive. The format check is not: nothing
+ // upstream filters a non-v1 stored config.
if target.get_group_type_index().is_some() {
return Err(BatchFlagEvaluationError::GroupAggregatedFlag);
}
if !target.active {
return Err(BatchFlagEvaluationError::FlagInactive);
}
+ target
+ .filters
+ .require_v1()
+ .map_err(|_| BatchFlagEvaluationError::UnsupportedConfigFormat)?;
let target_key = target.key.clone();
let expected_property_matching_version = request
diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rs
index 5686887a20a3..6524d6858d4b 100644
--- a/rust/feature-flags/src/api/remote_config.rs
+++ b/rust/feature-flags/src/api/remote_config.rs
@@ -193,6 +193,10 @@ pub async fn remote_config(
return Ok(StatusCode::NOT_FOUND.into_response());
};
+ // Raw filters, deliberately outside the fail-closed config-format boundary the
+ // evaluation paths use: Django's own view reads `payloads["true"]` just as raw and is
+ // shadow-compared against this one, so a Rust-only version guard would read as a
+ // permanent mismatch.
let stored = filters.get("payloads").and_then(|p| p.get("true"));
// Resolve the payload, mirroring Django's `Response(payloads["true"] or None)`: the stored
diff --git a/rust/feature-flags/src/bin/flags_cache_builder.rs b/rust/feature-flags/src/bin/flags_cache_builder.rs
index 5af4a2d9f4ae..8eaf874e8058 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 that exhaust their retry budget to the DLQ.
+//! 4. Route teams with permanent failures or exhausted retries 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,6 +49,7 @@ 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;
use feature_flags::flags::cache_shadow::{
@@ -811,7 +812,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::database(e)),
+ Err(e) => return ShadowOutcome::Failed(BuildFailure::from_build(e)),
};
let live = match live_reader
@@ -847,6 +848,7 @@ async fn shadow_compare(
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter)]
enum FailureCategory {
Database,
+ ConfigFormat,
CacheParse,
Redis,
S3,
@@ -858,6 +860,7 @@ 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",
@@ -867,24 +870,30 @@ impl FailureCategory {
}
}
-/// 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.
+/// A terminal build failure tagged with its cause so metrics and DLQ headers can
+/// distinguish invalid configuration from infrastructure failures.
struct BuildFailure {
category: FailureCategory,
message: String,
}
impl BuildFailure {
- /// 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 {
+ fn from_build(err: FlagError) -> Self {
+ let category = if err.error_code() == "flag_data_parsing_error" {
+ FailureCategory::ConfigFormat
+ } else {
+ FailureCategory::Database
+ };
Self {
- category: FailureCategory::Database,
+ category,
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
@@ -943,7 +952,7 @@ async fn build_with_retry(
return Ok(());
}
Err(failure) => {
- if attempt >= cfg.build_max_attempts {
+ if !failure.should_retry(attempt, cfg.build_max_attempts) {
return Err(failure);
}
metrics::counter!(BUILD_RETRIES).increment(1);
@@ -979,7 +988,7 @@ async fn build_once(
) -> Result<PersistOutcome, BuildFailure> {
let cache = build_flags_cache(pg_reader.clone(), team_id)
.await
- .map_err(BuildFailure::database)?;
+ .map_err(BuildFailure::from_build)?;
persist_flags_cache(writer, team_id, &cache, ttl_seconds)
.await
.map_err(BuildFailure::from_persist)
@@ -1194,7 +1203,8 @@ mod tests {
use super::{
fold_message, max_per_partition, precreate_counters, retry_backoff, truncate_for_header,
- BuildFailure, ShadowOutcome, ShadowOutcomeLabel, TeamBatch, DLQ_ERROR_HEADER_MAX,
+ BuildFailure, FlagError, ShadowOutcome, ShadowOutcomeLabel, TeamBatch,
+ DLQ_ERROR_HEADER_MAX,
};
// (partition, offset) pairs; keyed and valued by the two fields.
@@ -1354,11 +1364,20 @@ mod tests {
}
#[test]
- fn build_failure_attributes_build_step_to_database() {
- assert_eq!(
- BuildFailure::database("pg unreachable").category.as_label(),
- "database"
- );
+ 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));
+ }
}
#[test]
@@ -1471,7 +1490,7 @@ mod tests {
ShadowOutcomeLabel::LiveEntryMissing,
),
(
- ShadowOutcome::Failed(BuildFailure::database("pg unreachable")),
+ ShadowOutcome::Failed(BuildFailure::from_build(FlagError::DatabaseUnavailable)),
ShadowOutcomeLabel::Error,
),
(
@@ -1509,6 +1528,7 @@ mod tests {
const EXPECTED_PRECREATED_SERIES: &[&str] = &[
"flags_cache_builder_build_retries_total{}",
"flags_cache_builder_builds_total{reason=cache_parse,result=failure}",
+ "flags_cache_builder_builds_total{reason=config_format,result=failure}",
"flags_cache_builder_builds_total{reason=database,result=failure}",
"flags_cache_builder_builds_total{reason=other,result=failure}",
"flags_cache_builder_builds_total{reason=redis,result=failure}",
@@ -1521,6 +1541,7 @@ 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/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index 782078b19387..e354cd223600 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -51,6 +51,11 @@ pub async fn build_flags_cache(
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()?;
+ }
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?;
@@ -956,6 +961,21 @@ mod tests {
.insert_flag(team.id, Some(disabled_row("unreferenced-disabled-flag")))
.await
.expect("Failed to insert unreferenced inactive flag");
+ for (key, active, deleted) in [("inactive-v2", false, false), ("deleted-v2", true, true)] {
+ context
+ .insert_flag(
+ team.id,
+ Some(FeatureFlagRow {
+ key: key.to_string(),
+ active,
+ deleted,
+ filters: serde_json::json!({"version": 2}),
+ ..base_flag_row(team.id)
+ }),
+ )
+ .await
+ .expect("Failed to insert unevaluable v2 flag");
+ }
let dependent = context
.insert_flag(
team.id,
@@ -1013,4 +1033,24 @@ 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": []}));
+ }
+ }
}
diff --git a/rust/feature-flags/src/flags/config_format.rs b/rust/feature-flags/src/flags/config_format.rs
new file mode 100644
index 000000000000..b40b63332dce
--- /dev/null
+++ b/rust/feature-flags/src/flags/config_format.rs
@@ -0,0 +1,72 @@
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use serde_json::Value;
+
+use crate::api::errors::FlagError;
+use crate::flags::flag_models::FlagFilters;
+
+/// Mirrors Python's `detect_config_format` (products/feature_flags/backend/facade/config.py).
+fn is_v1_version(version: Option<&Value>) -> bool {
+ match version {
+ None => true,
+ // JSON booleans are not `Value::Number`, so `true` cannot read as 1 here.
+ Some(Value::Number(number)) => number.as_f64() == Some(1.0),
+ Some(_) => false,
+ }
+}
+
+impl FlagFilters {
+ pub(crate) fn is_v1(&self) -> bool {
+ is_v1_version(self.extra.get("version"))
+ }
+
+ pub(crate) fn require_v1(&self) -> Result<(), FlagError> {
+ if self.is_v1() {
+ Ok(())
+ } else {
+ Err(FlagError::flag_data_parsing(
+ "unsupported feature flag configuration format",
+ ))
+ }
+ }
+}
+
+pub(crate) fn decode_filters(value: Value) -> Result<FlagFilters, serde_json::Error> {
+ // An object is required even when the discriminator is absent.
+ let Value::Object(document) = value else {
+ return Err(serde::de::Error::custom("expected a filters object"));
+ };
+ if is_v1_version(document.get("version")) {
+ serde_json::from_value(Value::Object(document))
+ } else {
+ Ok(FlagFilters {
+ // Keep the document opaque: v1-looking fields may have unrelated types.
+ // The passthrough map also accounts for these bytes in the prepared cache.
+ extra: document,
+ ..Default::default()
+ })
+ }
+}
+
+pub(crate) fn deserialize_filters<'de, D>(deserializer: D) -> Result<FlagFilters, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ decode_filters(Value::deserialize(deserializer)?).map_err(serde::de::Error::custom)
+}
+
+/// The single place a `FlagFilters` turns back into stored JSON: the derived `Serialize`
+/// impl flattens `extra`, which for an opaque non-v1 document would emit the typed fields
+/// twice.
+pub(crate) fn serialize_filters<S>(filters: &FlagFilters, serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+{
+ if filters.is_v1() {
+ filters.serialize(serializer)
+ } else {
+ filters.extra.serialize(serializer)
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/rust/feature-flags/src/flags/config_format/tests.rs b/rust/feature-flags/src/flags/config_format/tests.rs
new file mode 100644
index 000000000000..00402ae3f7fd
--- /dev/null
+++ b/rust/feature-flags/src/flags/config_format/tests.rs
@@ -0,0 +1,98 @@
+use super::*;
+use crate::flags::cache_builder::{
+ compute_flag_dependencies, extract_cohort_ids_from_flag_filters,
+};
+use crate::flags::feature_flag_list::PreparedFlags;
+use crate::flags::flag_models::{
+ EvaluationMetadata, FeatureFlag, HypercacheFlagsWrapper, PreparedFlagDefinitions,
+};
+use serde_json::json;
+use std::sync::Arc;
+
+fn flag(filters: Value) -> Value {
+ json!({"id": 1, "team_id": 1, "key": "example", "active": true, "version": 2, "filters": filters})
+}
+
+#[test]
+fn v1_cache_round_trip_preserves_discriminator_and_unknown_fields() {
+ for version in [None, Some(json!(1)), Some(json!(1.0))] {
+ let mut filters = json!({
+ "groups": [{"aggregation_group_type_index": null, "extra_group": [1],
+ "properties": [{"key": "email", "type": "person", "value": "example.com", "operator": null, "negation": null, "group_type_index": null, "extra_property": true}]}],
+ "multivariate": {"extra_options": true, "variants": [{"key": "control", "name": null, "rollout_percentage": 100.0, "extra_variant": [2]}]},
+ "extra_top": {"nested": [null, false]}
+ });
+ if let Some(version) = version {
+ filters["version"] = version;
+ }
+ let decoded: FeatureFlag = serde_json::from_value(flag(filters.clone())).unwrap();
+ assert!(decoded.filters.is_v1());
+ assert_eq!(serde_json::to_value(&decoded).unwrap()["filters"], filters);
+ assert_eq!(decoded.version, Some(2));
+ }
+}
+
+#[test]
+fn non_v1_cache_documents_remain_opaque_and_keep_healthy_siblings() {
+ for version in [
+ json!(2),
+ json!(2.0),
+ json!(3),
+ json!(1.5),
+ json!("1"),
+ json!("2"),
+ json!(true),
+ json!(false),
+ Value::Null,
+ ] {
+ for groups in [
+ json!("not v1 groups"),
+ json!([{"properties": [{"type": "cohort", "key": "id", "value": 42}, {"type": "flag", "key": "999", "value": true}]}]),
+ ] {
+ let filters = json!({"version": version, "groups": groups, "multivariate": false, "feature_enrollment": "invalid", "opaque": "x".repeat(8192)});
+ let wrapper: HypercacheFlagsWrapper = serde_json::from_value(json!({
+ "flags": [flag(filters.clone()), {"id": 2, "team_id": 1, "key": "healthy", "active": true, "filters": {"groups": [{"rollout_percentage": 100}]}}],
+ "evaluation_metadata": {"dependency_stages": [[1, 2]], "flags_with_missing_deps": [], "transitive_deps": {"1": [], "2": []}}
+ })).unwrap();
+ assert!(!wrapper.flags[0].filters.is_v1());
+ assert_eq!(
+ serde_json::to_value(&wrapper).unwrap()["flags"][0]["filters"],
+ filters
+ );
+ assert_eq!(wrapper.flags[1].filters.groups.len(), 1);
+ assert!(extract_cohort_ids_from_flag_filters(&wrapper.flags).is_empty());
+ let metadata = compute_flag_dependencies(&wrapper.flags).unwrap();
+ assert_eq!(metadata.dependency_stages, vec![vec![1, 2]]);
+ assert!(metadata.flags_with_missing_deps.is_empty());
+ let prepared = PreparedFlagDefinitions {
+ flags: PreparedFlags::seal(wrapper.flags),
+ evaluation_metadata: Arc::new(EvaluationMetadata::default()),
+ cohorts: None,
+ };
+ assert!(prepared.estimated_size_bytes() > 8192);
+ assert!(prepared.flags[0].filters.groups.is_empty());
+ assert!(prepared.flags[0].filters.require_v1().is_err());
+ }
+ }
+}
+
+#[test]
+fn invalid_v1_filter_documents_keep_ingress_errors() {
+ for filters in [
+ Value::Null,
+ json!(false),
+ json!(1),
+ json!("filters"),
+ json!([]),
+ json!({"groups": null}),
+ json!({"groups": [{"properties": [{"key": "missing-type"}]}]}),
+ ] {
+ assert!(serde_json::from_value::<FeatureFlag>(flag(filters.clone())).is_err());
+ assert!(decode_filters(filters).is_err());
+ }
+ let mut missing = flag(json!({}));
+ missing.as_object_mut().unwrap().remove("filters");
+ assert!(serde_json::from_value::<FeatureFlag>(missing).is_err());
+ let empty: FeatureFlag = serde_json::from_value(flag(json!({}))).unwrap();
+ assert!(empty.filters.groups.is_empty());
+}
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index 4acf4c852fce..3bf10e30867a 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -198,7 +198,7 @@ impl FeatureFlagList {
let flags: Vec<FeatureFlag> = flags_row
.into_iter()
.filter_map(|row| {
- match serde_json::from_value(row.filters) {
+ match crate::flags::config_format::decode_filters(row.filters) {
Ok(filters) => Some(FeatureFlag {
id: row.id,
team_id: row.team_id,
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index a8250dbe0fe8..00ecc8a28b12 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -859,8 +859,32 @@ impl FeatureFlagMatcher {
let mut errors_while_computing_flags = overrides.hash_key_override_error;
let mut evaluated_flags_map = HashMap::new();
+ // Joining `filtered_out_flag_ids` pre-seeds the flag false below, like an inactive
+ // flag, so a dependent's `flag_evaluates_to: false` condition still resolves.
+ let mut unsupported_flag_ids: Vec<FeatureFlagId> = Vec::new();
+ for flag in evaluation_stages.iter().flatten() {
+ if self.filtered_out_flag_ids.contains(&flag.id) {
+ continue;
+ }
+ if let Err(error) = flag.filters.require_v1() {
+ evaluated_flags_map.insert(
+ flag.key.clone(),
+ FlagDetails::create_error(flag, &error, None),
+ );
+ unsupported_flag_ids.push(flag.id);
+ }
+ }
+ if !unsupported_flag_ids.is_empty() {
+ errors_while_computing_flags = true;
+ self.filtered_out_flag_ids.extend(unsupported_flag_ids);
+ }
+
// Collect flags from evaluation stages for preparation steps
- let flags: Vec<&FeatureFlag> = evaluation_stages.iter().flatten().collect();
+ let flags: Vec<&FeatureFlag> = evaluation_stages
+ .iter()
+ .flatten()
+ .filter(|flag| flag.filters.is_v1())
+ .collect();
// Handle hash key override errors by creating error responses for flags that need experience continuity
if overrides.hash_key_override_error && overrides.hash_key_overrides.is_none() {
@@ -1394,6 +1418,7 @@ impl FeatureFlagMatcher {
hash_key_overrides: Option<&HashMap<String, String>>,
request_hash_key_override: &Option<String>,
) -> Result<FeatureFlagMatch, FlagError> {
+ 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
// the floor: a pure-group flag whose only condition is skipped for missing context
@@ -2061,10 +2086,9 @@ impl FeatureFlagMatcher {
if let Some(holdout) = &flag.filters.holdout {
let percentage = holdout.exclusion_percentage_clamped();
- if percentage < 100.0
- && self.get_holdout_hash(flag, None, request_hash_key_override)?
- > (percentage / 100.0)
- {
+ if !crate::flags::v1_bucketing::is_in_rollout(percentage, || {
+ self.get_holdout_hash(flag, None, request_hash_key_override)
+ })? {
// User's hash is above the exclusion threshold — not in holdout
return Ok((false, None, FeatureFlagMatchReason::OutOfRolloutBound));
}
@@ -2209,17 +2233,16 @@ impl FeatureFlagMatcher {
hash_key_overrides: Option<&HashMap<String, String>>,
request_hash_key_override: &Option<String>,
) -> Result<(bool, FeatureFlagMatchReason), FlagError> {
- if rollout_percentage == 100.0 {
- return Ok((true, FeatureFlagMatchReason::ConditionMatch));
- }
- let hash = self.get_hash(
- feature_flag,
- "",
- aggregation_group_type_index,
- hash_key_overrides,
- request_hash_key_override,
- )?;
- if hash <= (rollout_percentage / 100.0) {
+ let included = crate::flags::v1_bucketing::is_in_rollout(rollout_percentage, || {
+ self.get_hash(
+ feature_flag,
+ "",
+ aggregation_group_type_index,
+ hash_key_overrides,
+ request_hash_key_override,
+ )
+ })?;
+ if included {
Ok((true, FeatureFlagMatchReason::ConditionMatch))
} else {
Ok((false, FeatureFlagMatchReason::OutOfRolloutBound))
@@ -2242,15 +2265,10 @@ impl FeatureFlagMatcher {
hash_key_overrides,
request_hash_key_override,
)?;
- let mut cumulative_percentage = 0.0;
-
- for variant in feature_flag.get_variants() {
- cumulative_percentage += variant.rollout_percentage / 100.0;
- if hash < cumulative_percentage {
- return Ok(Some(variant.key.clone()));
- }
- }
- Ok(None)
+ Ok(
+ crate::flags::v1_bucketing::select_variant(hash, feature_flag.get_variants())
+ .map(str::to_owned),
+ )
}
/// Get matching payload for a feature flag.
diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rs
index 6f043a8cf5d4..414dcc5f6679 100644
--- a/rust/feature-flags/src/flags/flag_models.rs
+++ b/rust/feature-flags/src/flags/flag_models.rs
@@ -279,6 +279,11 @@ pub struct FeatureFlag {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub key: String,
+ // Non-v1 documents stay opaque in `extra`; check the format before reading v1 fields.
+ #[serde(
+ deserialize_with = "crate::flags::config_format::deserialize_filters",
+ serialize_with = "crate::flags::config_format::serialize_filters"
+ )]
pub filters: FlagFilters,
#[serde(default)]
pub deleted: bool,
@@ -569,8 +574,11 @@ mod mock_impls {
impl MockFrom<FeatureFlag> for FeatureFlagRow {
fn mock_from(flag: FeatureFlag) -> Self {
- let filters = serde_json::to_value(&flag.filters)
- .expect("Mock: failed to serialize FeatureFlag.filters to JSON");
+ let filters = crate::flags::config_format::serialize_filters(
+ &flag.filters,
+ serde_json::value::Serializer,
+ )
+ .expect("Mock: failed to serialize FeatureFlag.filters to JSON");
FeatureFlagRow {
id: flag.id,
team_id: flag.team_id,
diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rs
index 4cb33a26e822..fdcba1b90d23 100644
--- a/rust/feature-flags/src/flags/flag_operations.rs
+++ b/rust/feature-flags/src/flags/flag_operations.rs
@@ -51,10 +51,11 @@ impl FeatureFlag {
/// Returns true if this flag has experience continuity enabled and is eligible for it.
///
- /// Experience continuity is only supported for person-based flags using distinct_id bucketing.
+ /// Experience continuity is only supported for v1 person-based flags using distinct_id bucketing.
/// Group-based flags and device_id bucketing flags are not eligible.
pub fn has_experience_continuity(&self) -> bool {
- self.ensure_experience_continuity.unwrap_or(false)
+ self.filters.is_v1()
+ && self.ensure_experience_continuity.unwrap_or(false)
&& self.get_group_type_index().is_none()
&& self.get_bucketing_identifier() == BucketingIdentifier::DistinctId
}
@@ -1646,6 +1647,13 @@ mod tests {
}];
// Partial rollout needs consistent bucketing
assert!(flag.needs_hash_key_override());
+ assert!(flag.has_experience_continuity());
+
+ for version in [serde_json::json!(2), serde_json::json!(3)] {
+ flag.filters.extra.insert("version".to_string(), version);
+ assert!(!flag.has_experience_continuity());
+ assert!(!flag.needs_hash_key_override());
+ }
}
#[test]
diff --git a/rust/feature-flags/src/flags/mod.rs b/rust/feature-flags/src/flags/mod.rs
index eb427eba2021..0535a4bfb4dc 100644
--- a/rust/feature-flags/src/flags/mod.rs
+++ b/rust/feature-flags/src/flags/mod.rs
@@ -2,6 +2,7 @@ pub mod cache_builder;
pub mod cache_invalidation;
pub mod cache_shadow;
pub mod cache_writer;
+pub(crate) mod config_format;
pub mod feature_flag_list;
pub mod flag_analytics;
pub mod flag_definitions_cache;
@@ -17,6 +18,7 @@ pub mod flag_property_group;
pub mod flag_request;
pub mod flag_service;
pub mod property_filter;
+pub mod v1_bucketing;
pub mod warm_run_status;
#[cfg(test)]
diff --git a/rust/feature-flags/src/flags/v1_bucketing.rs b/rust/feature-flags/src/flags/v1_bucketing.rs
new file mode 100644
index 000000000000..4bf7a6753e97
--- /dev/null
+++ b/rust/feature-flags/src/flags/v1_bucketing.rs
@@ -0,0 +1,52 @@
+use crate::api::errors::FlagError;
+use crate::flags::flag_models::MultivariateFlagVariant;
+
+/// The hash is a closure because identifier resolution and hashing must stay lazy at 100%:
+/// a flag at full rollout is included even when the identifier cannot be resolved.
+pub fn is_in_rollout(
+ percentage: f64,
+ hash: impl FnOnce() -> Result<f64, FlagError>,
+) -> Result<bool, FlagError> {
+ if percentage == 100.0 {
+ return Ok(true);
+ }
+ Ok(hash()? <= percentage / 100.0)
+}
+
+pub fn select_variant(hash: f64, variants: &[MultivariateFlagVariant]) -> Option<&str> {
+ let mut cumulative_percentage = 0.0;
+ for variant in variants {
+ cumulative_percentage += variant.rollout_percentage / 100.0;
+ if hash < cumulative_percentage {
+ return Some(&variant.key);
+ }
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn full_rollout_bypasses_hash_errors() {
+ let hash_error = || Err(FlagError::HashKeyOverrideError);
+ assert!(is_in_rollout(100.0, hash_error).unwrap());
+ assert!(matches!(
+ is_in_rollout(99.0, hash_error),
+ Err(FlagError::HashKeyOverrideError)
+ ));
+ assert!(is_in_rollout(100.0, || panic!("must not hash")).unwrap());
+ }
+
+ #[test]
+ fn incomplete_variant_weights_leave_the_remainder_unassigned() {
+ let variants = [MultivariateFlagVariant {
+ key: "control".to_string(),
+ rollout_percentage: 40.0,
+ ..Default::default()
+ }];
+ assert_eq!(select_variant(0.4, &variants), None);
+ assert_eq!(select_variant(1.0, &variants), None);
+ }
+}
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 00fad8a67fef..4d978e13ca41 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -699,10 +699,10 @@ pub async fn insert_flag_for_team_in_pg(
let mut conn = client.get_connection().await?;
let row: (i32,) = sqlx::query_as(
r#"INSERT INTO posthog_featureflag
- (team_id, name, key, filters, deleted, active, ensure_experience_continuity, evaluation_runtime, created_at) VALUES
- ($1, $2, $3, $4, $5, $6, $7, $8, '2024-06-17')
+ (team_id, name, key, filters, deleted, active, ensure_experience_continuity, evaluation_runtime, version, created_at) VALUES
+ ($1, $2, $3, $4, $5, $6, $7, $8, $9, '2024-06-17')
RETURNING id"#
- ).bind(team_id).bind(&payload_flag.name).bind(&payload_flag.key).bind(&payload_flag.filters).bind(payload_flag.deleted).bind(payload_flag.active).bind(payload_flag.ensure_experience_continuity).bind(&payload_flag.evaluation_runtime).fetch_one(&mut *conn).await?;
+ ).bind(team_id).bind(&payload_flag.name).bind(&payload_flag.key).bind(&payload_flag.filters).bind(payload_flag.deleted).bind(payload_flag.active).bind(payload_flag.ensure_experience_continuity).bind(&payload_flag.evaluation_runtime).bind(payload_flag.version).fetch_one(&mut *conn).await?;
payload_flag.id = row.0;
diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
index e4149cb16766..2f159f4143f4 100644
--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs
+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
@@ -204,6 +204,31 @@ async fn test_inactive_flag_rejected() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn test_unsupported_config_format_rejected() -> Result<()> {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await?;
+ let server = ServerHandle::for_config(batch_eval_config()).await;
+
+ for version in [json!(2), json!(3), json!("1")] {
+ let key = format!("unsupported-{version}");
+ context
+ .insert_flag(
+ team.id,
+ Some(flag_row(team.id, &key, json!({"version": version}))),
+ )
+ .await?;
+
+ let res =
+ send_batch_request(&server, Some(INTERNAL_TOKEN), &batch_body(team.id, &key, 0)).await;
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
+ let json_response = res.json::<Value>().await?;
+ assert_eq!(json_response["error"], "unsupported_config_format");
+ }
+
+ Ok(())
+}
+
#[tokio::test]
async fn test_group_aggregated_flag_rejected() -> Result<()> {
// The Django caller returns [] for group-aggregated flags without calling us;
diff --git a/rust/feature-flags/tests/test_config_format.rs b/rust/feature-flags/tests/test_config_format.rs
new file mode 100644
index 000000000000..3a5548769148
--- /dev/null
+++ b/rust/feature-flags/tests/test_config_format.rs
@@ -0,0 +1,328 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use anyhow::Result;
+use feature_flags::cohorts::cohort_cache_manager::CohortCacheManager;
+use feature_flags::config::DEFAULT_TEST_CONFIG;
+use feature_flags::flags::cache_builder::build_flags_cache;
+use feature_flags::flags::feature_flag_list::PreparedFlags;
+use feature_flags::flags::flag_matching::FeatureFlagMatcher;
+use feature_flags::flags::flag_models::{
+ EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow,
+};
+use feature_flags::utils::test_utils::{
+ insert_flags_for_team_in_redis, mock_group_type_cache, setup_redis_client,
+ update_team_in_hypercache, TestContext,
+};
+use rstest::rstest;
+use serde_json::{json, Value};
+use uuid::Uuid;
+
+pub mod common;
+
+fn documents() -> Vec<(String, Value, bool, bool)> {
+ let mut cases = Vec::new();
+ for (key, version) in [
+ ("absent", None),
+ ("one", Some(json!(1))),
+ ("one-float", Some(json!(1.0))),
+ ] {
+ let mut filters = json!({"groups": [{"rollout_percentage": 100}], "payloads": {"true": "example-payload"}});
+ if let Some(version) = version {
+ filters["version"] = version;
+ }
+ cases.push((key.to_string(), filters, true, false));
+ }
+ for (index, version) in [
+ json!(2),
+ json!(2.0),
+ json!(3),
+ json!(1.5),
+ json!("1"),
+ json!("2"),
+ json!(true),
+ json!(false),
+ Value::Null,
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ for (shape, groups) in [json!([{"rollout_percentage": 100}]), json!("not v1 groups")]
+ .into_iter()
+ .enumerate()
+ {
+ cases.push((
+ format!("rejected-{index}-{shape}"),
+ json!({"version": version, "groups": groups, "rules": [], "default_value": true}),
+ true,
+ false,
+ ));
+ }
+ }
+ cases.push((
+ "inactive".to_string(),
+ json!({"version": 1, "groups": [{"rollout_percentage": 100}]}),
+ false,
+ false,
+ ));
+ cases.push((
+ "deleted".to_string(),
+ json!({"groups": [{"rollout_percentage": 100}]}),
+ true,
+ true,
+ ));
+ cases.push((
+ "inactive-v2".to_string(),
+ json!({"version": 2, "groups": false}),
+ false,
+ false,
+ ));
+ cases
+}
+
+#[rstest]
+#[case::redis(true)]
+#[case::postgres_fallback(false)]
+#[tokio::test]
+async fn config_dispatch_preserves_siblings_and_wire_errors(#[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?;
+ let docs = documents();
+ let mut flags = Vec::new();
+ for (key, filters, active, deleted) in docs.clone() {
+ if cached {
+ flags.push(
+ json!({"id": flags.len() + 1, "team_id": team.id, "key": key,
+ "active": active, "deleted": deleted, "version": 2, "filters": filters}),
+ );
+ } else {
+ db.insert_flag(
+ team.id,
+ Some(FeatureFlagRow {
+ team_id: team.id,
+ key,
+ name: Some(String::new()),
+ filters,
+ active,
+ deleted,
+ version: Some(2),
+ ..Default::default()
+ }),
+ )
+ .await?;
+ }
+ }
+ if cached {
+ insert_flags_for_team_in_redis(redis, team.id, Some(json!(flags).to_string())).await?;
+ } else {
+ assert!(build_flags_cache(db.non_persons_reader.clone(), team.id)
+ .await
+ .is_err());
+ }
+ 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"});
+
+ 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),
+ ] {
+ let response = client
+ .post(format!(
+ "http://{}/flags?v={version}&config=false",
+ server.addr
+ ))
+ .header("X-Original-Endpoint", endpoint)
+ .json(&payload)
+ .send()
+ .await?;
+ assert_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}");
+ } else {
+ assert!(body.get("errorsWhileComputingFlags").is_none(), "{body}");
+ }
+ match shape {
+ Shape::Detailed => {
+ for key in ["absent", "one", "one-float"] {
+ assert_eq!(body["flags"][key]["enabled"], true, "{body}");
+ assert_eq!(body["flags"][key]["metadata"]["version"], 2, "{body}");
+ }
+ for (key, _, active, deleted) in &docs {
+ if key.starts_with("rejected-") {
+ assert_eq!(body["flags"][key]["failed"], true, "{body}");
+ assert_eq!(
+ body["flags"][key]["reason"]["code"],
+ "flag_data_parsing_error"
+ );
+ assert_eq!(
+ body["flags"][key]["reason"]["description"],
+ "Failed to parse flag data: unsupported feature flag configuration format"
+ );
+ assert!(body["flags"][key]["metadata"]["payload"].is_null());
+ } else if !active || *deleted {
+ assert!(body["flags"].get(key).is_none(), "{body}");
+ }
+ }
+ }
+ 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,
+ vec![json!("absent"), json!("one"), json!("one-float")]
+ );
+ }
+ Shape::Map {
+ keeps_rejected_as_false,
+ } => {
+ let mut expected = json!({"absent": true, "one": true, "one-float": true});
+ if keeps_rejected_as_false {
+ for (key, _, _, _) in &docs {
+ if key.starts_with("rejected-") {
+ expected[key] = json!(false);
+ }
+ }
+ }
+ assert_eq!(body["featureFlags"], expected, "{endpoint} v{version}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[derive(Clone, Copy)]
+enum Shape {
+ Detailed,
+ EnabledKeys,
+ Map { keeps_rejected_as_false: 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(
+ "example-person".to_string(),
+ None,
+ 1,
+ db.create_postgres_router(),
+ cohort_cache,
+ mock_group_type_cache(HashMap::new()),
+ None,
+ );
+ let flag: FeatureFlag = serde_json::from_value(json!({
+ "id": 1, "team_id": 1, "key": "rejected", "active": true,
+ "ensure_experience_continuity": true,
+ "filters": {"version": 2, "groups": [{"properties": [{"type": "cohort", "key": "id", "value": 123}]}], "feature_enrollment": true, "aggregation_group_type_index": 99}
+ })).unwrap();
+ assert!(matcher.get_match(&flag, None, None, None, &None).is_err());
+ let response = matcher
+ .evaluate_all_feature_flags(
+ FeatureFlagList {
+ flags: PreparedFlags::seal(vec![flag]),
+ evaluation_metadata: Arc::new(EvaluationMetadata {
+ dependency_stages: vec![vec![1]],
+ flags_with_missing_deps: vec![1],
+ ..Default::default()
+ }),
+ ..Default::default()
+ },
+ None,
+ None,
+ None,
+ Uuid::new_v4(),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ assert!(response.errors_while_computing_flags);
+ assert!(response.flags["rejected"].failed);
+ assert_eq!(
+ response.flags["rejected"].reason.code,
+ "flag_data_parsing_error"
+ );
+}
+
+#[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 flags: Vec<FeatureFlag> = serde_json::from_value(json!([
+ {"id": 1, "team_id": 1, "key": "blocker", "active": true,
+ "filters": {"version": 2, "groups": [{"rollout_percentage": 100}]}},
+ {"id": 2, "team_id": 1, "key": "dependent", "active": true,
+ "filters": {"groups": [{"rollout_percentage": 100, "properties": [
+ {"type": "flag", "key": "1", "value": false, "operator": "flag_evaluates_to"}]}]}}
+ ]))
+ .unwrap();
+ let response = matcher
+ .evaluate_all_feature_flags(
+ FeatureFlagList {
+ flags: PreparedFlags::seal(flags),
+ evaluation_metadata: Arc::new(EvaluationMetadata {
+ dependency_stages: vec![vec![1], vec![2]],
+ ..Default::default()
+ }),
+ ..Default::default()
+ },
+ None,
+ None,
+ None,
+ Uuid::new_v4(),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ assert!(response.flags["blocker"].failed);
+ assert!(response.flags["dependent"].enabled);
+ assert!(response.errors_while_computing_flags);
+}
diff --git a/rust/feature-flags/tests/test_rules_v2_v1_contract.rs b/rust/feature-flags/tests/test_rules_v2_v1_contract.rs
index e0bf5bb0c5ad..551730c7b5e7 100644
--- a/rust/feature-flags/tests/test_rules_v2_v1_contract.rs
+++ b/rust/feature-flags/tests/test_rules_v2_v1_contract.rs
@@ -22,8 +22,9 @@ use feature_flags::flags::cache_builder::compute_flag_dependencies;
use feature_flags::flags::feature_flag_list::PreparedFlags;
use feature_flags::flags::flag_matching::FeatureFlagMatcher;
use feature_flags::flags::flag_matching_utils::calculate_hash;
-use feature_flags::flags::flag_models::{FeatureFlag, FeatureFlagList};
+use feature_flags::flags::flag_models::{FeatureFlag, FeatureFlagList, MultivariateFlagVariant};
use feature_flags::flags::flag_request::FlagRequest;
+use feature_flags::flags::v1_bucketing::{is_in_rollout, select_variant};
use feature_flags::utils::test_utils::{mock_group_type_cache, TestContext};
use regex::Regex;
use serde_json::{json, Value};
@@ -32,29 +33,6 @@ use uuid::Uuid;
const CORPUS_DIR: &str = "tests/fixtures/rules_v2_contract/1.2.0";
-/// Corpus rows that supply a precomputed `hash01` instead of hash inputs. The evaluator
-/// computes its hash internally and exposes no seam that accepts one, so these rows stay
-/// unsupported until the shared hashing primitives are extracted behind such a seam.
-const UNSUPPORTED_CASE_IDS: &[&str] = &[
- "threshold.equal_is_included",
- "threshold.next_binary64_above_is_excluded",
- "threshold.zero_percent_zero_hash",
- "threshold.zero_percent_smallest_hash",
- "threshold.hundred_percent_short_circuit",
- "threshold.two_decimal_division_equal",
- "threshold.two_decimal_division_excluded",
- "threshold.two_decimal_division_included_below_quotient",
- "variant.zero_hash_first_variant",
- "variant.boundary_is_exclusive",
- "variant.just_below_boundary",
- "variant.accumulated_boundary_left_to_right",
- "variant.accumulated_boundary_third",
- "variant.two_decimal_weights_boundary",
- "variant.hash_one_off_the_end",
- "variant.sum_below_one_off_the_end",
- "parity.final_variant_fallback_divergent",
-];
-
/// A dependency target absent from the fixture definitions maps to an id no fixture flag
/// uses, so the target is missing from the flag list entirely. That is the only way the
/// evaluator reports `missing_dependency`: a deleted target that another flag references
@@ -121,27 +99,12 @@ async fn corpus_matches_production_evaluator_and_projections() {
covered.extend(run_v1_corpus(&db, team_id).await);
covered.extend(run_projection_corpus());
- let unsupported: HashSet<String> = UNSUPPORTED_CASE_IDS.iter().map(|s| s.to_string()).collect();
let declared: HashSet<String> = corpus_artifacts(&manifest)
.flat_map(|artifact| artifact["case_ids"].as_array().unwrap().iter())
.map(|id| id.as_str().unwrap().to_string())
.collect();
- let both: BTreeSet<_> = covered.intersection(&unsupported).collect();
- assert!(
- both.is_empty(),
- "cases both run and listed as unsupported: {both:?}"
- );
- let accounted: HashSet<String> = covered.union(&unsupported).cloned().collect();
- let missing: BTreeSet<_> = declared.difference(&accounted).collect();
- assert!(
- missing.is_empty(),
- "manifest cases neither run nor listed as unsupported: {missing:?}"
- );
- let unknown: BTreeSet<_> = accounted.difference(&declared).collect();
- assert!(
- unknown.is_empty(),
- "cases run or listed that the manifest does not declare: {unknown:?}"
- );
+ assert!(!declared.is_empty(), "the manifest declares no cases");
+ assert_eq!(covered, declared, "every manifest case must execute");
}
async fn run_hash_corpus(db: &TestContext, team_id: i32) -> HashSet<String> {
@@ -258,13 +221,53 @@ async fn run_hash_corpus(db: &TestContext, team_id: i32) -> HashSet<String> {
covered.insert(id.to_string());
}
+ for vector in corpus["threshold_vectors"].as_array().unwrap() {
+ let id = str_field(vector, "id");
+ assert_eq!(
+ json!(
+ is_in_rollout(vector["rollout_percentage"].as_f64().unwrap(), || Ok(
+ prescribed_hash(vector)
+ ),)
+ .unwrap()
+ ),
+ vector["included"],
+ "{id}: rollout inclusion"
+ );
+ covered.insert(id.to_string());
+ }
+ for vector in corpus["variant_vectors"].as_array().unwrap() {
+ let id = str_field(vector, "id");
+ let variants: Vec<MultivariateFlagVariant> =
+ serde_json::from_value(vector["variants"].clone()).unwrap();
+ assert_eq!(
+ json!(select_variant(prescribed_hash(vector), &variants)),
+ vector["selected"],
+ "{id}: v1 variant selection"
+ );
+ covered.insert(id.to_string());
+ }
+
// Parity rows pin that the v1 input and the converted v2 input hash identically.
// `identical_outcome` and `divergence` describe version 2 semantics, which nothing in
// this crate implements yet, so they are not asserted here.
for parity in corpus["seed_parity"].as_array().unwrap() {
let id = str_field(parity, "id");
let Some(v2) = parity.get("v2") else {
- continue; // white-box row, listed in UNSUPPORTED_CASE_IDS
+ // The corpus links this white-box row to its v1 vector only through `note`.
+ assert_eq!(id, "parity.final_variant_fallback_divergent");
+ let linked = corpus["variant_vectors"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|vector| str_field(vector, "id") == "variant.hash_one_off_the_end")
+ .expect("linked v1 variant vector");
+ let variants: Vec<MultivariateFlagVariant> =
+ serde_json::from_value(linked["variants"].clone()).unwrap();
+ let hash = prescribed_hash(parity);
+ assert_eq!(hash, prescribed_hash(linked), "{id}: linked v1 hash");
+ assert_eq!(select_variant(hash, &variants), None, "{id}: v1 selection");
+ covered.insert(id.to_string());
+ continue;
};
let v1_input = str_field(parity, "v1_input");
let v1_hash = hash_of_input(v1_input);
@@ -631,6 +634,10 @@ fn hash_of_input(input: &str) -> f64 {
calculate_hash(input, "", "").unwrap()
}
+fn prescribed_hash(case: &Value) -> f64 {
+ str_field(case, "hash01").parse::<f64>().unwrap()
+}
+
fn assert_hash01(id: &str, actual: f64, expected: &Value) {
let expected: f64 = expected
.as_str()