: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): mirror $os and $os_name at flag match time (#64439)
Phil Haack629552af72a7
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex b5332daf891f..2ba34e603bd4 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2313,7 +2313,7 @@"label": "OS distro"},"$os_name": {- "description": "The Operating System name",+ "description": "The Operating System name.","examples": ["iOS","Android"@@ -6114,6 +6114,14 @@],"label": "Initial OS"},+ "$initial_os_name": {+ "description": "The Operating System name. Data from the first time this user was seen.",+ "examples": [+ "iOS",+ "Android"+ ],+ "label": "Initial OS name"+ },"$initial_os_version": {"description": "The Operating System version. Data from the first time this user was seen.","examples": [@@ -6661,12 +6669,12 @@"label": "OS distro"},"$os_name": {- "description": "The Operating System name",+ "description": "The Operating System name. Data from the last time this user was seen.","examples": ["iOS","Android"],- "label": "OS name"+ "label": "Latest OS name"},"$os_version": {"description": "The Operating System version. Data from the last time this user was seen.",diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 53985ae4d6dd..00a2fb5152df 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -62,6 +62,7 @@ PERSON_PROPERTIES_ADAPTED_FROM_EVENT: set[str] = {"$current_url","$pathname","$os",+ "$os_name","$os_version","$referring_domain","$referrer",@@ -1300,7 +1301,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {},"$os_name": {"label": "OS name",- "description": "The Operating System name",+ "description": "The Operating System name.","examples": ["iOS", "Android"],},"$os_version": {diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 94ed6271873c..7ed5d23d0bf0 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -12,7 +12,7 @@ use crate::flags::flag_match_reason::FeatureFlagMatchReason;use crate::flags::flag_matching_utils::{calculate_hash, fetch_and_locally_cache_all_relevant_properties,get_feature_flag_hash_key_overrides, match_flag_value_to_flag_filter,- populate_missing_initial_properties, set_feature_flag_hash_key_overrides,+ populate_missing_initial_properties, populate_os_aliases, set_feature_flag_hash_key_overrides,should_write_hash_key_override,};use crate::flags::flag_models::{@@ -1696,6 +1696,11 @@ impl FeatureFlagMatcher {merged_properties.extend(overrides.iter_owned());}+ // Mirror $os <-> $os_name so a condition keyed on either matches when the+ // person row carries only one of them (web reports $os, mobile $os_name).+ // Runs before initial-property population so an aliased $os can backfill $initial_os.+ populate_os_aliases(&mut merged_properties);+// Populate missing $initial_ properties from their non-initial counterparts.// DB $initial_ values are preserved; this only fills in missing ones from// the merged properties (which may come from DB or request overrides).diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rsindex 5889bab802a2..5a282cb31903 100644--- a/rust/feature-flags/src/flags/flag_matching_utils.rs+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs@@ -148,6 +148,33 @@ pub fn populate_missing_initial_properties(properties: &mut HashMap<String, Valu}}+/// Mirrors `$os` and `$os_name` so a flag condition keyed on either property+/// matches when the person row carries only one of them.+///+/// Web SDKs (posthog-js) report the OS as `$os`; mobile SDKs report it as+/// `$os_name`. Ingestion normalizes `$os_name` -> `$os` at write time+/// (`personInitialAndUTMProperties` in nodejs/src/utils/db/utils.ts), but that+/// only covers newly-written rows — historical and un-normalized person rows can+/// carry only one of the two keys. Flag matching does exact-key lookups, so+/// without this a mobile person whose row has only `$os_name` never matches an+/// `$os` filter (and vice versa). The mirror is bidirectional so either filter+/// key works regardless of which key the person row happens to carry.+///+/// Only the missing key is filled — an already-present value is never+/// overwritten, so request overrides keep precedence over their own key.+pub fn populate_os_aliases(properties: &mut HashMap<String, Value>) {+ match (properties.get("$os"), properties.get("$os_name")) {+ (Some(os), None) => {+ properties.insert("$os_name".to_string(), os.clone());+ }+ (None, Some(os_name)) => {+ properties.insert("$os".to_string(), os_name.clone());+ }+ // Both present or both absent: nothing to mirror.+ _ => {}+ }+}+/// Result from the person + static cohort query branch.struct PersonCohortResult {person: Option<Person>,@@ -2458,6 +2485,64 @@ mod tests {assert_eq!(properties.get("$browser"), Some(&json!("Firefox")));}+ #[test]+ fn test_populate_os_aliases_fills_os_from_os_name() {+ let mut properties = HashMap::from([("$os_name".to_string(), json!("Android"))]);++ populate_os_aliases(&mut properties);++ assert_eq!(properties.get("$os"), Some(&json!("Android")));+ assert_eq!(properties.get("$os_name"), Some(&json!("Android")));+ }++ #[test]+ fn test_populate_os_aliases_fills_os_name_from_os() {+ let mut properties = HashMap::from([("$os".to_string(), json!("iOS"))]);++ populate_os_aliases(&mut properties);++ assert_eq!(properties.get("$os_name"), Some(&json!("iOS")));+ assert_eq!(properties.get("$os"), Some(&json!("iOS")));+ }++ #[test]+ fn test_populate_os_aliases_preserves_both_when_present() {+ let mut properties = HashMap::from([+ ("$os".to_string(), json!("iOS")),+ ("$os_name".to_string(), json!("iPadOS")),+ ]);++ populate_os_aliases(&mut properties);++ // Neither value is overwritten when both keys already exist.+ assert_eq!(properties.get("$os"), Some(&json!("iOS")));+ assert_eq!(properties.get("$os_name"), Some(&json!("iPadOS")));+ }++ #[test]+ fn test_populate_os_aliases_noop_when_neither_present() {+ let mut properties = HashMap::from([("$browser".to_string(), json!("Chrome"))]);++ populate_os_aliases(&mut properties);++ assert!(!properties.contains_key("$os"));+ assert!(!properties.contains_key("$os_name"));+ assert_eq!(properties.len(), 1);+ }++ #[test]+ fn test_populate_os_aliases_then_initial_backfills_initial_os() {+ // Mobile person row carries only $os_name; the alias should let $initial_os+ // get backfilled by populate_missing_initial_properties.+ let mut properties = HashMap::from([("$os_name".to_string(), json!("Android"))]);++ populate_os_aliases(&mut properties);+ populate_missing_initial_properties(&mut properties);++ assert_eq!(properties.get("$os"), Some(&json!("Android")));+ assert_eq!(properties.get("$initial_os"), Some(&json!("Android")));+ }+#[test]fn test_populate_missing_initial_properties_handles_campaign_properties() {let mut properties = HashMap::from([diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex 9c9b92ae6594..a6fd2cbb39c4 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -5600,6 +5600,127 @@ async fn test_initial_property_population_respects_db_values(Ok(())}+/// Tests that `$os` and `$os_name` are mirrored at match time, so a flag condition+/// keyed on either property matches a person row that carries only one of them.+///+/// Web SDKs report the OS as `$os`; mobile SDKs report it as `$os_name`, and+/// ingestion stores only one of the two on the person. Matching does exact-key+/// lookups, so without the mirror a mobile person (DB has only `$os_name`) would+/// fall through on a `$os` filter, and vice versa.+///+/// Each case runs with experience continuity off and on. The on cases pin the+/// scenario reported in https://github.com/PostHog/posthog/issues/55532, where+/// matching reads properties from the persisted person row — exactly where a+/// legacy `$os_name`-only mobile row used to miss a `$os` filter.+#[rstest]+// Person row has only $os_name (mobile); flag filters on $os -> should match.+#[case::os_name_in_db_matches_os_filter(json!({"$os_name": "Android"}), "$os", "Android", false, true)]+// Person row has only $os (web); flag filters on $os_name -> should match.+#[case::os_in_db_matches_os_name_filter(json!({"$os": "iOS"}), "$os_name", "iOS", false, true)]+// Person row has only $os_name; flag filters on $os for a different value -> no match.+#[case::os_name_in_db_wrong_value_no_match(json!({"$os_name": "Android"}), "$os", "iOS", false, false)]+// Same three under experience continuity (the #55532 path: matches the persisted person row).+#[case::eec_os_name_in_db_matches_os_filter(json!({"$os_name": "Android"}), "$os", "Android", true, true)]+#[case::eec_os_in_db_matches_os_name_filter(json!({"$os": "iOS"}), "$os_name", "iOS", true, true)]+#[case::eec_os_name_in_db_wrong_value_no_match(json!({"$os_name": "Android"}), "$os", "iOS", true, false)]+#[tokio::test]+async fn test_os_name_aliases_os_at_match_time(+ #[case] db_properties: Value,+ #[case] filter_key: &str,+ #[case] filter_value: &str,+ #[case] ensure_experience_continuity: bool,+ #[case] flag_should_match: bool,+) -> Result<()> {+ let config = DEFAULT_TEST_CONFIG.clone();+ let distinct_id = format!("test_os_alias_{}", rand::thread_rng().gen::<u32>());++ let client = setup_redis_client(Some(config.redis_url.clone())).await;+ let team = insert_new_team_in_redis(client.clone()).await.unwrap();+ let token = team.api_token.clone();++ let context = TestContext::new(None).await;+ context.insert_new_team(Some(team.id)).await.unwrap();++ context+ .insert_person(team.id, distinct_id.clone(), Some(db_properties))+ .await+ .unwrap();++ let flag_json = json!([+ {+ "id": 1,+ "key": "os-flag",+ "name": "Flag checking OS",+ "active": true,+ "deleted": false,+ "team_id": team.id,+ "ensure_experience_continuity": ensure_experience_continuity,+ "filters": {+ "groups": [+ {+ "properties": [+ {+ "key": filter_key,+ "value": filter_value,+ "operator": "exact",+ "type": "person"+ }+ ],+ "rollout_percentage": 100+ }+ ],+ },+ }+ ]);++ insert_flags_for_team_in_redis(client, team.id, Some(flag_json.to_string())).await?;++ let server = ServerHandle::for_config(config).await;++ // No person_properties override: properties come purely from the DB person row,+ // which is the experience-continuity path this bug affects.+ let payload = json!({+ "token": token,+ "distinct_id": distinct_id,+ });++ let res = server+ .send_flags_request(payload.to_string(), Some("2"), None)+ .await;++ if res.status() != StatusCode::OK {+ let status = res.status();+ let text = res.text().await?;+ panic!("Non-200 response: {status}\nBody: {text}");+ }++ let json_data = res.json::<Value>().await?;++ let expected_reason = if flag_should_match {+ "condition_match"+ } else {+ "no_condition_match"+ };++ assert_json_include!(+ actual: json_data,+ expected: json!({+ "errorsWhileComputingFlags": false,+ "flags": {+ "os-flag": {+ "key": "os-flag",+ "enabled": flag_should_match,+ "reason": {+ "code": expected_reason+ }+ }+ }+ })+ );++ Ok(())+}+#[rstest]#[case(true)]#[case(false)]