: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): count the flags dropped for unparseable filters (#92163)
James Gill203badc45eff
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rsindex e28d717737ad..4acf4c852fce 100644--- a/rust/feature-flags/src/flags/feature_flag_list.rs+++ b/rust/feature-flags/src/flags/feature_flag_list.rs@@ -5,7 +5,9 @@ use crate::flags::flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, FlagPropertyGroup,HypercacheFlagsWrapper,};-use crate::metrics::consts::TOMBSTONE_COUNTER;+use crate::metrics::consts::{+ FLAG_MALFORMED_FILTER_COUNTER, FLAG_MALFORMED_FILTER_READ_COUNTER, TOMBSTONE_COUNTER,+};use common_database::PostgresReader;use common_types::TeamId;use metrics::counter;@@ -192,6 +194,7 @@ impl FeatureFlagList {FlagError::internal(anyhow::Error::new(e).context(message))})?;+ let mut malformed_filter_flags: u64 = 0;let flags: Vec<FeatureFlag> = flags_row.into_iter().filter_map(|row| {@@ -212,14 +215,21 @@ impl FeatureFlagList {has_experiment: row.has_experiment,}),Err(e) => {- // This is highly unlikely to happen, but if it does, we skip the flag.+ // Serde fails the whole `filters` struct when a required field is+ // absent, so one bad property filter costs the entire flag. A property+ // filter with no `"type"` key does that, because+ // PropertyFilter::prop_type has no default. Python does not parse these+ // filters, so it keeps such a flag when the flag is active or referenced,+ // and those drops are real builder divergences. An inactive, unreferenced+ // flag is dropped by both builders, so the counters below over-count it.+ // Skip the flag rather than fail the read, so the team keeps the rest.+ malformed_filter_flags += 1;tracing::warn!("Failed to deserialize filters for flag {} in team {}: {}",row.key,row.team_id,e);- // Also track as a tombstone - invalid data in postgres should never happen// Details (team_id, flag_key) are logged above to avoid high-cardinality labelscounter!(TOMBSTONE_COUNTER,@@ -229,12 +239,17 @@ impl FeatureFlagList {).increment(1);- None // Skip this flag, continue with others+ None}}}).collect();+ if malformed_filter_flags > 0 {+ counter!(FLAG_MALFORMED_FILTER_COUNTER).increment(malformed_filter_flags);+ counter!(FLAG_MALFORMED_FILTER_READ_COUNTER).increment(1);+ }+tracing::debug!("Successfully fetched {} flags from database for team {}",flags.len(),@@ -479,6 +494,91 @@ mod tests {}}+ #[tokio::test]+ async fn test_flag_with_malformed_filters_is_dropped_and_counted() {+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};++ // `set_default_local_recorder` returns a thread-local guard; safe across+ // `.await` because `#[tokio::test]` defaults to a current-thread runtime.+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let context = TestContext::new(None).await;+ let team = context+ .insert_new_team(None)+ .await+ .expect("Failed to insert team");++ let good_flag = FeatureFlagRow {+ id: 0,+ team_id: team.id,+ name: Some("Good flag".to_string()),+ key: "good_flag".to_string(),+ filters: serde_json::json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),+ deleted: false,+ active: true,+ ensure_experience_continuity: Some(false),+ version: Some(1),+ evaluation_runtime: Some("all".to_string()),+ evaluation_tags: None,+ bucketing_identifier: None,+ has_experiment: false,+ };++ // `groups` holds a string where FlagFilters wants a list, so this blob stays+ // unparseable whatever PropertyFilter later does with a missing `"type"`.+ let malformed_flag = FeatureFlagRow {+ id: 0,+ team_id: team.id,+ name: Some("Malformed flag".to_string()),+ key: "malformed_flag".to_string(),+ filters: serde_json::json!({"groups": "not-a-list"}),+ deleted: false,+ active: true,+ ensure_experience_continuity: Some(false),+ version: Some(1),+ evaluation_runtime: Some("all".to_string()),+ evaluation_tags: None,+ bucketing_identifier: None,+ has_experiment: false,+ };++ context+ .insert_flag(team.id, Some(good_flag))+ .await+ .expect("Failed to insert good flag");+ context+ .insert_flag(team.id, Some(malformed_flag))+ .await+ .expect("Failed to insert malformed flag");++ let flags = FeatureFlagList::from_pg(context.non_persons_reader.clone(), team.id)+ .await+ .expect("A malformed flag must not fail the whole read");++ let keys: Vec<&str> = flags.iter().map(|f| f.key.as_str()).collect();+ assert_eq!(keys, vec!["good_flag"]);++ let counter_value = |name: &str| {+ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .find(|(ckey, _, _, _)| ckey.key().name() == name)+ .map(|(_, _, _, value)| value)+ };++ assert_eq!(+ counter_value(FLAG_MALFORMED_FILTER_COUNTER),+ Some(DebugValue::Counter(1))+ );+ assert_eq!(+ counter_value(FLAG_MALFORMED_FILTER_READ_COUNTER),+ Some(DebugValue::Counter(1))+ );+ }+#[tokio::test]async fn test_fetch_flags_with_evaluation_tags_from_pg() {let context = TestContext::new(None).await;diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex ee7822cc3e94..b08eb6b974de 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -417,6 +417,21 @@ pub const FLAG_QUOTA_LIMITED_COUNTER: &str = "flags_quota_limited_total";// Labels: reason (missing_device_id, missing_group_type)pub const FLAG_CONDITION_SKIPPED_COUNTER: &str = "flags_condition_skipped_total";+// Incremented once per flag left out of a team's payload because its `filters` JSON+// does not deserialize into FlagFilters. A property filter with no `"type"` key is+// one such blob, because PropertyFilter requires prop_type, and serde fails the+// whole outer struct. This counts every dropped flag, which is a superset of the+// flags the two builders disagree about: Python keeps an active or referenced flag+// that this drops, but an inactive, unreferenced flag is dropped by both builders.+// Team id and flag key are in the companion warn log, not in metric labels (cardinality).+pub const FLAG_MALFORMED_FILTER_COUNTER: &str = "flags_flag_malformed_filter_total";+// Incremented once per team read that left out at least one flag for the reason+// above. FLAG_MALFORMED_FILTER_COUNTER divided by this gives the mean flags+// dropped per affected read. It does not measure how many teams are affected,+// because neither counter carries a team label and one team read many times+// inflates this denominator. Read the warn log for team identity and breadth.+pub const FLAG_MALFORMED_FILTER_READ_COUNTER: &str = "flags_flag_malformed_filter_reads_total";+// Tombstone metric for tracking "impossible" failures that should never happen in production// Different failure types are tracked via the "failure_type" labelpub const TOMBSTONE_COUNTER: &str = "posthog_tombstone_total";