: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
fix(flags): report errors when the postgres fallback omits a flag (#121667)
Phil Haack6ebaba1f1d4c
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex ebddf2d3b593..e21e8bb19593 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -132,8 +132,11 @@ The service's PostgreSQL fallback runs the same classification, so a Redis missBoth 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.When the Rust service reads a Python-written entry that holds such a row, it skips that one flag, counts it in `flags_flag_malformed_filter_total`, and marks every flag that depends on it as missing a dependency, so the team's other flags still evaluate.+That response sets `errorsWhileComputingFlags`, and so does a PostgreSQL fallback response that omits such a row, so an SDK keeps its stored value for the missing flag.+An entry the Rust builder wrote already lacks the row, so a response served from it does not report the missing flag.`verify_team_flags` reports and repairs such a team, attributed to the writer that produced it.-An entry written before this rule can hold an inactive non-v1 row already blanked to `{"groups": []}`; its cached bytes cannot recover the original format, so the entry is rebuilt from the database rows by the next invalidation, refresh sweep, or verifier repair rather than reclassified in place.+Python rejects a v1 row as well when its `groups`, or a group's `properties`, is neither falsy nor a list of objects, so neither builder publishes that row and no response reports it.+An entry written before the builders omitted unsupported non-v1 rows can hold an inactive non-v1 row already blanked to `{"groups": []}`; its cached bytes cannot recover the original format, so the entry is rebuilt from the database rows by the next invalidation, refresh sweep, or verifier repair rather than reclassified in place.Until then an unreferenced blanked row is inert for the matcher, and an active dependent of one reports as `STALE_IN_CACHE` and triggers the repair.Parity is per team, not per byte: each team has one primary writer (teams whose invalidation routes to Kafka via `KAFKA_ROUTING_FLAG` get the Rust builder, every other team Python), the Python verifier remains a repair writer for every team, and the two serializers order keys differently — so what must match is the flag set, fields, and metadata, not the bytes or etag.Verifier fixes on the flags cache carry a `writer` label (`posthog_hypercache_verify_fixes_total{cache_type="flags", writer="rust"|"python"|"unknown"}`), attributed by evaluating the same routing flag (`get_team_primary_flags_writer` in `flags_cache.py`): a fix on a rust-routed team is the parity signal that the Rust builder diverged, which the unattributed counter blends into Python's baseline repair noise. `unknown` means the routing flag couldn't be evaluated at fix time, so an attribution outage can't masquerade as a clean Rust ramp.diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rsindex 6524d6858d4b..ca94c9e89679 100644--- a/rust/feature-flags/src/api/remote_config.rs+++ b/rust/feature-flags/src/api/remote_config.rs@@ -38,6 +38,7 @@ use crate::{metrics::consts::{REMOTE_CONFIG_AUTH_COUNTER, REMOTE_CONFIG_ETAG_COUNTER},router::State as AppState,team::team_models::Team,+ utils::python_truthiness::is_falsy,};use axum::{debug_handler,@@ -219,7 +220,7 @@ pub async fn remote_config(// Django applies `or None` to the final value and renders None as an empty body, not// the JSON literal `null`. Apply the falsy check after decryption so an empty decrypted- // string nulls out too.+ // string nulls out too. In practice the payload is always a JSON-encoded string.let payload = payload.filter(|v| !is_falsy(v));// `Value::to_string` produces the same compact JSON `Json(v)` would serialize, so the@@ -336,20 +337,6 @@ fn empty_ok_no_content_type(etag: &str) -> Response {(StatusCode::OK, revalidation_headers(etag)).into_response()}-/// Mirrors Python truthiness for `payloads.get("true") or None`. In practice the payload-/// is always a JSON-encoded string, but cover every falsy JSON value so the behaviour-/// matches Python exactly: null, false, zero, and empty string/array/object.-fn is_falsy(v: &Value) -> bool {- match v {- Value::Null => true,- Value::Bool(b) => !b,- Value::Number(n) => n.as_f64() == Some(0.0),- Value::String(s) => s.is_empty(),- Value::Array(a) => a.is_empty(),- Value::Object(o) => o.is_empty(),- }-}-/// Authenticates and resolves the decrypt gate against the already-resolved scope team,/// mirroring Django.///@@ -550,27 +537,3 @@ async fn load_remote_config_flag(FlagError::DatabaseUnavailable})}--#[cfg(test)]-mod tests {- use super::is_falsy;- use serde_json::json;-- #[test]- fn is_falsy_matches_python_truthiness() {- // Django's `payloads["true"] or None` nulls out every falsy JSON value.- assert!(is_falsy(&json!(null)));- assert!(is_falsy(&json!(false)));- assert!(is_falsy(&json!(0)));- assert!(is_falsy(&json!(0.0)));- assert!(is_falsy(&json!("")));- assert!(is_falsy(&json!([])));- assert!(is_falsy(&json!({})));- // Truthy values pass through.- assert!(!is_falsy(&json!(true)));- assert!(!is_falsy(&json!(1)));- assert!(!is_falsy(&json!("x")));- assert!(!is_falsy(&json!([1])));- assert!(!is_falsy(&json!({"k": "v"})));- }-}diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rsindex 9e0d3cc74e00..515847cd8b7e 100644--- a/rust/feature-flags/src/flags/cache_builder.rs+++ b/rust/feature-flags/src/flags/cache_builder.rs@@ -75,8 +75,8 @@ 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(+/// The team's rows minus those this cache cannot carry.+async fn load_supported_flags(pg_reader: PostgresReader,team_id: TeamId,) -> Result<Vec<FeatureFlag>, FlagError> {@@ -86,15 +86,41 @@ pub(crate) async fn load_supported_flags(Ok(flags)}+/// The flags the service evaluates when the hypercache has no entry for the team. It omits+/// the same rows as the cache. Its metadata sets `has_unparseable_flags` when it omitted a row+/// that Python's builder publishes, so the response sets `errorsWhileComputingFlags` and an+/// SDK keeps that flag's stored value.+pub(crate) async fn build_fallback_wrapper(+ pg_reader: PostgresReader,+ team_id: TeamId,+) -> Result<HypercacheFlagsWrapper, FlagError> {+ let (mut flags, undecodable) =+ FeatureFlagList::from_pg_keeping_undecodable(pg_reader, team_id).await?;+ let has_unparseable_flags = omit_unsupported_flags(team_id, &mut flags, &undecodable);+ let evaluation_metadata = EvaluationMetadata {+ has_unparseable_flags,+ ..compute_flag_dependencies_or_single_stage(team_id, &flags)+ };+ Ok(HypercacheFlagsWrapper {+ flags,+ cohorts: None,+ evaluation_metadata,+ })+}+/// Drop the stored rows this cache cannot carry, and their dependents transitively:/// 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`.+///+/// Returns true when it omitted an evaluable `UnreadableV1Object` row. Python's builder+/// publishes such a row unless the row depends on a row that Python also rejects. When it+/// returns false, Python's builder omits the same rows as this function.fn omit_unsupported_flags(team_id: TeamId,flags: &mut Vec<FeatureFlag>,undecodable: &UndecodableFlags,-) {+) -> bool {let unsupported: HashSet<FeatureFlagId> = flags.iter().filter(|flag| {@@ -103,14 +129,17 @@ fn omit_unsupported_flags(}match undecodable.get(&flag.id) {Some(UndecodableDocument::NotAnObject) => true,- Some(UndecodableDocument::UnreadableV1Object) => is_evaluable(flag),+ Some(+ UndecodableDocument::MalformedV1Groups+ | UndecodableDocument::UnreadableV1Object,+ ) => is_evaluable(flag),None => false,}}).map(|flag| flag.id).collect();if unsupported.is_empty() {- return;+ return false;}let mut dependents: HashMap<FeatureFlagId, Vec<FeatureFlagId>> = HashMap::new();for flag in flags.iter() {@@ -138,6 +167,9 @@ fn omit_unsupported_flags("Omitted flags the service cache cannot carry");flags.retain(|flag| !excluded.contains(&flag.id));+ unsupported+ .iter()+ .any(|id| undecodable.get(id) == Some(&UndecodableDocument::UnreadableV1Object))}/// Keep the flags worth caching: evaluable ones, plus unevaluable ones that another@@ -923,6 +955,29 @@ mod tests {);}+ // -------------------------------------------------------------------------+ // omit_unsupported_flags tests+ // -------------------------------------------------------------------------++ #[test_case(true, true ; "active unreadable row is omitted and reported")]+ #[test_case(false, false ; "inactive unreadable row is kept and not reported")]+ fn test_omit_reports_an_omitted_row_python_publishes(active: bool, expect_reported: bool) {+ let mut flags = vec![+ make_flag(1, "unreadable", active, vec![]),+ make_flag(2, "healthy", true, vec![group_with_properties(vec![])]),+ make_flag(3, "not-an-object", true, vec![]),+ ];+ let undecodable = UndecodableFlags::from([+ (1, UndecodableDocument::UnreadableV1Object),+ (3, UndecodableDocument::NotAnObject),+ ]);++ let reported = omit_unsupported_flags(1, &mut flags, &undecodable);++ assert_eq!(reported, expect_reported);+ assert_eq!(flags.iter().any(|f| f.id == 1), !expect_reported);+ }+// -------------------------------------------------------------------------// retain_evaluable_and_referenced_flags tests// -------------------------------------------------------------------------@@ -1201,6 +1256,10 @@ mod tests {let wrapper = build_flags_cache(context.non_persons_reader.clone(), team.id).await.expect("Failed to build flags cache");+ let fallback = build_fallback_wrapper(context.non_persons_reader.clone(), team.id)+ .await+ .expect("Failed to load flags");+ assert!(!fallback.evaluation_metadata.has_unparseable_flags);let rows = fixture["flags"].as_array().unwrap();let published: HashMap<i32, &FeatureFlag> =diff --git a/rust/feature-flags/src/flags/config_format.rs b/rust/feature-flags/src/flags/config_format.rsindex 6674d91138ce..3aa8e4299f22 100644--- a/rust/feature-flags/src/flags/config_format.rs+++ b/rust/feature-flags/src/flags/config_format.rs@@ -8,6 +8,7 @@ use crate::flags::config_v2;use crate::flags::feature_flag_list::UndecodableDocument;use crate::flags::flag_models::FlagFilters;use crate::metrics::consts::FLAG_V2_PARSE_COUNTER;+use crate::utils::python_truthiness::is_falsy;#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum ConfigFormat {@@ -145,7 +146,7 @@ pub(crate) fn decode_raw_filters(raw: Box<RawValue>) -> Result<FlagFilters, Filt.and_then(|document| serde_json::from_value(Value::Object(document))).map_err(|error| FilterDecodeError {error,- document: UndecodableDocument::UnreadableV1Object,+ document: classify_undecodable_v1(&raw),})} else {let parsed_v2 = (format == ConfigFormat::V2).then(|| {@@ -172,6 +173,47 @@ pub(crate) fn decode_raw_filters(raw: Box<RawValue>) -> Result<FlagFilters, Filt}}+fn classify_undecodable_v1(raw: &RawValue) -> UndecodableDocument {+ // This read fails on a number that serde cannot represent, or on nesting deeper than+ // serde's recursion limit. Python's JSON reader accepts both, so the document counts+ // as one that Python's builder can read.+ let Ok(document) = serde_json::from_str::<Value>(raw.get()) else {+ return UndecodableDocument::UnreadableV1Object;+ };+ if python_reads_conditions(&document) {+ UndecodableDocument::UnreadableV1Object+ } else {+ UndecodableDocument::MalformedV1Groups+ }+}++/// Python's builder reads only the conditions of a v1 document, as `references()` in+/// `products/feature_flags/backend/facade/references.py` does. It iterates `groups or []`+/// and each group's `properties or []`, and calls `.get` on every element. Returns false+/// where that read raises.+fn python_reads_conditions(document: &Value) -> bool {+ let Some(groups) = python_list(document.get("groups")) else {+ return false;+ };+ groups.iter().all(|group| {+ group+ .as_object()+ .and_then(|group| python_list(group.get("properties")))+ .is_some_and(|properties| properties.iter().all(Value::is_object))+ })+}++/// The elements Python iterates in `value or []`. Returns `None` for a truthy value that is+/// not an array, because Python either cannot iterate it or yields elements that are not+/// objects.+fn python_list(value: Option<&Value>) -> Option<&[Value]> {+ match value {+ Some(Value::Array(items)) => Some(items),+ Some(value) if !is_falsy(value) => None,+ _ => Some(&[]),+ }+}+pub(crate) fn deserialize_filters<'de, D>(deserializer: D) -> Result<FlagFilters, D::Error>whereD: Deserializer<'de>,diff --git a/rust/feature-flags/src/flags/config_format/tests.rs b/rust/feature-flags/src/flags/config_format/tests.rsindex 71cdc9bbe6fe..857fa478174b 100644--- a/rust/feature-flags/src/flags/config_format/tests.rs+++ b/rust/feature-flags/src/flags/config_format/tests.rs@@ -78,20 +78,48 @@ fn non_v1_cache_documents_remain_opaque_and_keep_healthy_siblings() {#[test]fn invalid_v1_filter_documents_keep_ingress_errors() {- for filters in [- Value::Null,- json!(false),- json!(1),- json!("filters"),- json!([]),- json!([2]),- json!([1]),- json!({"groups": null}),- json!({"groups": [{"properties": [{"key": "missing-type"}]}]}),+ use UndecodableDocument::{MalformedV1Groups, NotAnObject, UnreadableV1Object};+ for (filters, document) in [+ (Value::Null, NotAnObject),+ (json!(false), NotAnObject),+ (json!(1), NotAnObject),+ (json!("filters"), NotAnObject),+ (json!([]), NotAnObject),+ (json!([2]), NotAnObject),+ (json!([1]), NotAnObject),+ (json!({"groups": null}), UnreadableV1Object),+ (json!({"groups": ""}), UnreadableV1Object),+ (json!({"groups": 0}), UnreadableV1Object),+ (json!({"groups": {}}), UnreadableV1Object),+ (+ json!({"groups": [{"properties": false}]}),+ UnreadableV1Object,+ ),+ (+ json!({"groups": [{"properties": [{"key": "missing-type"}]}]}),+ UnreadableV1Object,+ ),+ (json!({"groups": "not a list"}), MalformedV1Groups),+ (json!({"groups": {"key": "value"}}), MalformedV1Groups),+ (json!({"groups": [1]}), MalformedV1Groups),+ (json!({"groups": [{"properties": "x"}]}), MalformedV1Groups),+ (json!({"groups": [{"properties": [[]]}]}), MalformedV1Groups),] {assert!(serde_json::from_value::<FeatureFlag>(flag(filters.clone())).is_err());- assert!(decode_filters(filters).is_err());+ assert_eq!(+ decode_filters(filters.clone()).unwrap_err().document,+ document,+ "{filters}"+ );}+ // A number serde cannot represent hides the malformed `groups` from the classifier.+ let unrepresentable = format!(r#"{{"groups": "not a list", "x": 1{}}}"#, "0".repeat(400));+ assert_eq!(+ decode_raw_filters(RawValue::from_string(unrepresentable).unwrap())+ .unwrap_err()+ .document,+ UnreadableV1Object+ );let mut missing = flag(json!({}));missing.as_object_mut().unwrap().remove("filters");assert!(serde_json::from_value::<FeatureFlag>(missing).is_err());diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rsindex c473f59fcb05..92bfb898ac0c 100644--- a/rust/feature-flags/src/flags/feature_flag_list.rs+++ b/rust/feature-flags/src/flags/feature_flag_list.rs@@ -24,6 +24,12 @@ type HypercacheParseResult = (Vec<FeatureFlag>, EvaluationMetadata, Option<Vec<C#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum UndecodableDocument {NotAnObject,+ /// A v1 object whose `groups`, or a group's `properties`, is neither falsy nor a list of+ /// objects.+ /// Python's builder cannot read it either.+ MalformedV1Groups,+ /// A v1 object that Python's builder reads but the typed decoder rejects, such as one+ /// with a property filter that has no `type` key.UnreadableV1Object,}@@ -333,10 +339,11 @@ impl FeatureFlagList {// Serde fails the whole `filters` struct when a required field is// absent, so one bad property filter costs the entire flag. A property// filter with no `"type"` key does that, because- // PropertyFilter::prop_type has no default. Python does not parse these- // filters, so it keeps such a flag when the flag is active, and those- // drops are real builder divergences. Either way the team keeps the- // rest of its flags, rather than failing the read.+ // PropertyFilter::prop_type has no default. Python reads only the cohort+ // and flag references. It reads a property's `type` with `.get`, so it+ // keeps such a flag when the flag is active. Those drops are real+ // builder divergences, which `UnreadableV1Object` marks. Either way the+ // team keeps the rest of its flags, rather than failing the read.tracing::warn!("Failed to deserialize filters for flag {} in team {}: {}",row.key,diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex 60ab3d917eb4..509f80e26a34 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -80,7 +80,8 @@ pub struct EvaluationMetadata {serialize_with = "serialize_string_keyed_i32_map")]pub transitive_deps: HashMap<i32, HashSet<i32>>,- /// True when the serving read skipped a cached flag that it could not parse.+ /// True when the serving read skipped a cached flag that it could not parse, or the+ /// PostgreSQL fallback omitted a flag that Python's builder can read./// The response then sets `errorsWhileComputingFlags`, so an SDK merges the/// response into its stored flags and keeps the skipped flag's last value.#[serde(skip)]diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rsindex 0e80d2a721d9..03e05182c9b1 100644--- a/rust/feature-flags/src/flags/flag_service.rs+++ b/rust/feature-flags/src/flags/flag_service.rs@@ -284,20 +284,11 @@ impl FlagService {1,);- let flags = crate::flags::cache_builder::load_supported_flags(+ let wrapper = crate::flags::cache_builder::build_fallback_wrapper(self.pg_client.clone(),team_id,).await?;- let evaluation_metadata =- crate::flags::cache_builder::compute_flag_dependencies_or_single_stage(- team_id, &flags,- );- let wrapper = HypercacheFlagsWrapper {- flags,- cohorts: None,- evaluation_metadata,- };Ok((Some(wrapper), CacheSource::Fallback))}}diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rsindex 8d964ff26601..3138227a67d4 100644--- a/rust/feature-flags/src/handler/flags.rs+++ b/rust/feature-flags/src/handler/flags.rs@@ -410,8 +410,9 @@ pub async fn evaluate_for_request(evaluation::evaluate_feature_flags(ctx, request_id).await?};- // A response for a team whose cached payload had a flag skipped reports an error, so that- // an SDK merges it into its stored flags and keeps the skipped flag's last value.+ // A response that lacks a flag Python's builder publishes reports an error, because the+ // serving read skipped it or the PostgreSQL fallback omitted it. An SDK then merges the+ // response into its stored flags and keeps the missing flag's last value.response.errors_while_computing_flags |= has_unparseable_flags;Ok(response)}diff --git a/rust/feature-flags/src/utils/mod.rs b/rust/feature-flags/src/utils/mod.rsindex 9988dd992e1f..6a6bc081e27e 100644--- a/rust/feature-flags/src/utils/mod.rs+++ b/rust/feature-flags/src/utils/mod.rs@@ -4,6 +4,7 @@ pub mod graph_utils;pub mod json_size;#[cfg(test)]pub mod mock;+pub mod python_truthiness;pub mod test_utils;pub mod user_agent;diff --git a/rust/feature-flags/src/utils/python_truthiness.rs b/rust/feature-flags/src/utils/python_truthiness.rsnew file mode 100644index 000000000000..9595dda9a8a8--- /dev/null+++ b/rust/feature-flags/src/utils/python_truthiness.rs@@ -0,0 +1,37 @@+use serde_json::Value;++/// Mirrors Python truthiness for a JSON value, for code that matches a Python `x or default`+/// read: null, false, zero, and an empty string, array or object are falsy.+pub fn is_falsy(v: &Value) -> bool {+ match v {+ Value::Null => true,+ Value::Bool(b) => !b,+ Value::Number(n) => n.as_f64() == Some(0.0),+ Value::String(s) => s.is_empty(),+ Value::Array(a) => a.is_empty(),+ Value::Object(o) => o.is_empty(),+ }+}++#[cfg(test)]+mod tests {+ use super::is_falsy;+ use serde_json::json;++ #[test]+ fn is_falsy_matches_python_truthiness() {+ assert!(is_falsy(&json!(null)));+ assert!(is_falsy(&json!(false)));+ assert!(is_falsy(&json!(0)));+ assert!(is_falsy(&json!(0.0)));+ assert!(is_falsy(&json!("")));+ assert!(is_falsy(&json!([])));+ assert!(is_falsy(&json!({})));+ // Truthy values pass through.+ assert!(!is_falsy(&json!(true)));+ assert!(!is_falsy(&json!(1)));+ assert!(!is_falsy(&json!("x")));+ assert!(!is_falsy(&json!([1])));+ assert!(!is_falsy(&json!({"k": "v"})));+ }+}diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex 517502696784..7c486bf4a33c 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -106,8 +106,16 @@ pub async fn insert_new_team_in_redis(Ok(team)}-/// A cached flag that the serving read cannot deserialize. Its property filter has no-/// `"type"` key, and `PropertyFilter` requires one.+/// v1 filters that the typed decoder rejects and Python's builder reads. The property filter+/// has no `"type"` key. `PropertyFilter` requires one.+pub fn unparseable_v1_filters() -> Value {+ json!({"groups": [{+ "properties": [{"key": "email", "value": "[email protected]"}],+ "rollout_percentage": 100+ }]})+}++/// A cached flag that the serving read cannot deserialize, because of its filters.pub fn unparseable_flag_json(id: i32, key: &str, team_id: i32) -> Value {json!({"id": id,@@ -115,10 +123,7 @@ pub fn unparseable_flag_json(id: i32, key: &str, team_id: i32) -> Value {"team_id": team_id,"active": true,"deleted": false,- "filters": {"groups": [{- "properties": [{"key": "email", "value": "[email protected]"}],- "rollout_percentage": 100- }]}+ "filters": unparseable_v1_filters()})}@@ -332,17 +337,30 @@ pub fn dummy_s3_client() -> Arc<dyn common_hypercache::S3Client + Send + Sync> {}pub async fn insert_v1_v2_and_unsupported_flags(context: &TestContext, team_id: i32) {- for (key, filters) in [- (- "v1-flag",- json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),- ),- (- "v2-flag",- json!({"version": 2, "return_type": "boolean", "default_value": false, "rules": []}),- ),- ("v3-flag", json!({"version": 3})),- ] {+ insert_active_flags(+ context,+ team_id,+ [+ (+ "v1-flag",+ json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),+ ),+ (+ "v2-flag",+ json!({"version": 2, "return_type": "boolean", "default_value": false, "rules": []}),+ ),+ ("v3-flag", json!({"version": 3})),+ ],+ )+ .await;+}++pub async fn insert_active_flags(+ context: &TestContext,+ team_id: i32,+ flags: impl IntoIterator<Item = (&str, Value)>,+) {+ for (key, filters) in flags {context.insert_flag(team_id,diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex b8a5007fe208..4d8ddb19f41d 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -15,9 +15,10 @@ use crate::common::*;use feature_flags::cohorts::cohort_models::CohortType;use feature_flags::config::DEFAULT_TEST_CONFIG;use feature_flags::utils::test_utils::{- insert_config_in_hypercache, insert_flags_for_team_in_redis,+ insert_active_flags, insert_config_in_hypercache, insert_flags_for_team_in_redis,insert_flags_with_metadata_for_team_in_redis, insert_new_team_in_redis, setup_pg_reader_client,- setup_redis_client, unparseable_flag_json, update_team_in_hypercache, TestContext,+ setup_redis_client, unparseable_flag_json, unparseable_v1_filters, update_team_in_hypercache,+ TestContext,};pub mod common;@@ -6448,3 +6449,40 @@ async fn it_reports_errors_when_the_serving_read_skips_a_flag(Ok(())}++#[tokio::test]+async fn it_reports_errors_when_the_postgres_fallback_omits_a_flag_python_publishes() -> Result<()>+{+ let config = DEFAULT_TEST_CONFIG.clone();++ let client = setup_redis_client(Some(config.redis_url.clone())).await;+ let team = insert_new_team_in_redis(client).await.unwrap();+ let context = TestContext::new(None).await;+ context.insert_new_team(Some(team.id)).await.unwrap();++ insert_active_flags(+ &context,+ team.id,+ [+ ("omitted-flag", unparseable_v1_filters()),+ (+ "healthy-flag",+ json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),+ ),+ ],+ )+ .await;++ let server = ServerHandle::for_config(config).await;+ let payload = json!({"token": team.api_token, "distinct_id": "user_distinct_id"}).to_string();+ let res = server.send_flags_request(payload, Some("2"), None).await;++ assert_eq!(res.status(), StatusCode::OK);+ let body = res.json::<FlagsResponse>().await?;+ assert!(body.errors_while_computing_flags);+ let keys: Vec<&str> = body.flags.keys().map(String::as_str).collect();+ assert_eq!(keys, ["healthy-flag"]);+ assert!(body.flags["healthy-flag"].enabled);++ Ok(())+}