: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): don't let geoip overwrite supplied person properties (#74397)
posthog[bot]9cd198107842
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.mdindex 5fed604942ab..3824452efc8d 100644--- a/docs/internal/feature-flags/flag-evaluation-engine.md+++ b/docs/internal/feature-flags/flag-evaluation-engine.md@@ -455,6 +455,8 @@ pub struct FlagEvaluationState {```Property overrides from the request body are merged on top of DB-fetched properties. Request overrides take precedence.+GeoIP-derived `$geoip_*` properties follow the same rule. They are added to the request overrides before evaluation, but only fill keys the request didn't supply.+See [GeoIP enrichment of `person_properties`](rust-service-overview.md#geoip-enrichment-of-person_properties).## Data fetching strategydiff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex 669cabbda47c..6fb4dd960b72 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -173,18 +173,17 @@ pub struct FlagRequest {#### GeoIP enrichment of `person_properties`Unless `geoip_disable: true` is set in the body, `handler::properties::get_person_property_overrides` looks up the request IP in MaxMind and merges the resulting `$geoip_*` properties into `person_properties` before evaluation.-The lookup wins: a `$geoip_*` value in the request body is overwritten.-That precedence is likely wrong for server-side evaluation, because the IP we geolocate is whoever the request appears to come from.-A backend that doesn't forward the end user's IP resolves its own server's location, so a caller that resolved geo itself (from `CF-IPCountry`, `X-Forwarded-For`, or similar) loses values it is better placed to know.+GeoIP only fills gaps. A `$geoip_*` key present in the request body is left alone, and a JSON null counts as absent, since callers clear a property with `$unset`, so a null is a gap to fill.+This matters for server-side evaluation: the IP we geolocate is whoever made the HTTP request, so a call from a backend or an SSR render resolves the server's own location, not the end user's.+A caller that resolved geo itself (from `CF-IPCountry`, `X-Forwarded-For`, or similar) is the authority for those keys.-Before changing that, the affected population is being measured:+Two signals size how often that precedence matters:-- `flags_geoip_properties_differ_from_lookup_total` counts requests that supplied a `$geoip_*` value disagreeing with the lookup.+- `flags_geoip_properties_differ_from_lookup_total` counts requests that supplied a `$geoip_*` value disagreeing with the lookup, i.e. requests that would evaluate differently if the lookup won.- The canonical log line carries the same fact as `geoip_properties_differ_from_lookup`. The counter has no labels, so query the log line in Loki to attribute a spike to a team or SDK.-Both only measure. Nothing about evaluation changes until the precedence flip ships, and both are removable once it has settled.-A JSON null in the request counts as absent for this purpose, since it carries no value to compare against the lookup.+Both are removable once the precedence change has settled.### `FlagsResponse` (v2 response)diff --git a/rust/feature-flags/src/flags/flag_request.rs b/rust/feature-flags/src/flags/flag_request.rsindex 07be85aec7d5..0faafa11b7e2 100644--- a/rust/feature-flags/src/flags/flag_request.rs+++ b/rust/feature-flags/src/flags/flag_request.rs@@ -65,6 +65,11 @@ pub struct FlagRequest {pub distinct_id: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub sent_at: Option<DateTime<Utc>>,+ /// Skips the MaxMind lookup that adds `$geoip_*` properties to `person_properties`.+ /// Only affects keys the request didn't send, since request-supplied `$geoip_*` values take+ /// precedence over the lookup either way. With the lookup skipped, a flag targeting+ /// `$geoip_*` falls back to the person's stored properties rather than matching on nothing.+ /// See `docs/internal/feature-flags/rust-service-overview.md`.pub geoip_disable: Option<bool>,// Web and mobile clients can configure this parameter to disable flags for a request.// It's mostly used for folks who want to save money on flag evaluations while still usingdiff --git a/rust/feature-flags/src/handler/properties.rs b/rust/feature-flags/src/handler/properties.rsindex f59c8321853b..eb11e5475f74 100644--- a/rust/feature-flags/src/handler/properties.rs+++ b/rust/feature-flags/src/handler/properties.rs@@ -5,7 +5,10 @@ use crate::{use common_geoip::GeoIpClient;use common_metrics::inc;use serde_json::Value;-use std::{collections::HashMap, net::IpAddr};+use std::{+ collections::{hash_map::Entry, HashMap},+ net::IpAddr,+};use super::canonical_log::with_canonical_log;use super::types::{RequestContext, RequestPropertyOverrides};@@ -46,12 +49,11 @@ pub fn prepare_overrides(})}-/// Flags requests whose own `$geoip_*` values disagree with the lookup, without changing what-/// wins. The lookup still overwrites them.-///-/// Sizes the population that letting request values win would affect, so that change can be-/// measured before it ships rather than after. A JSON null counts as absent: it carries no-/// value to compare against the lookup, so it can't be a divergence.+/// Flags requests that supplied a `$geoip_*` value disagreeing with the lookup. These are the+/// requests where keeping supplied values produces a different evaluation input than letting the+/// lookup win, so the counter sizes the behavior difference between the two precedences.+/// A JSON null counts as absent: it carries no value to compare against the lookup, so it can't+/// be a divergence.fn record_geoip_divergence(person_properties: &HashMap<String, Value>,geoip_props: &HashMap<String, String>,@@ -67,39 +69,47 @@ fn record_geoip_divergence(}}+/// Builds the person property overrides for a request, filling in GeoIP-derived properties+/// unless GeoIP is disabled.+///+/// GeoIP only fills gaps: a `$geoip_*` key the caller sent explicitly is kept as-is, because the+/// IP we geolocate is whoever the request appears to come from. For a server-side caller that+/// doesn't forward the end user's IP, that's its own server, so a caller that resolved geo itself+/// is the authority for those keys.pub fn get_person_property_overrides(geoip_disabled: bool,person_properties: Option<HashMap<String, Value>>,ip: &IpAddr,geoip_service: &GeoIpClient,) -> Option<HashMap<String, Value>> {- match (!geoip_disabled, person_properties) {- (true, Some(mut props)) => {- if let Some(geoip_props) = geoip_service.get_geoip_properties(&ip.to_string()) {- record_geoip_divergence(&props, &geoip_props);- props.extend(geoip_props.into_iter().map(|(k, v)| (k, Value::String(v))));+ if geoip_disabled {+ return person_properties;+ }++ let geoip_props = geoip_service+ .get_geoip_properties(&ip.to_string())+ .unwrap_or_default();+ if geoip_props.is_empty() {+ return person_properties;+ }++ let mut props = person_properties.unwrap_or_default();+ record_geoip_divergence(&props, &geoip_props);+ for (key, value) in geoip_props {+ match props.entry(key) {+ Entry::Vacant(slot) => {+ slot.insert(Value::String(value));}- Some(props)- }- (true, None) => {- if let Some(geoip_props) = geoip_service.get_geoip_properties(&ip.to_string()) {- if !geoip_props.is_empty() {- Some(- geoip_props- .into_iter()- .map(|(k, v)| (k, Value::String(v)))- .collect(),- )- } else {- None- }- } else {- None+ // A JSON null means the caller had no value rather than that it supplied one.+ // Callers clear a property with `$unset`, so a null here is a gap to fill.+ Entry::Occupied(mut slot) if slot.get().is_null() => {+ slot.insert(Value::String(value));}+ Entry::Occupied(_) => {}}- (false, Some(props)) => Some(props),- (false, None) => None,}++ Some(props)}pub fn get_group_property_overrides(diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rsindex 79dce71dceca..db9bb73c40a1 100644--- a/rust/feature-flags/src/handler/tests.rs+++ b/rust/feature-flags/src/handler/tests.rs@@ -142,6 +142,13 @@ enum GeoipExpected {IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),GeoipExpected::None)]+// GeoIP on, loopback IP, with person props → supplied props survive an unresolvable IP+#[case(+ false,+ true,+ IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),+ GeoipExpected::NameOnly+)]fn test_geoip_person_property_overrides(#[case] geoip_disabled: bool,#[case] with_name: bool,@@ -181,19 +188,49 @@ fn test_geoip_person_property_overrides(}}+#[test]+// A supplied null survives only when the IP resolves nothing: the fill loop at+// properties.rs only visits keys MaxMind returns. That leftover null reads as+// "supplied" to `requires_db_property`, so it suppresses the person fetch; treat+// this as a presence test for the residual null, not a verdict that the DB+// suppression is correct.+fn test_supplied_geoip_null_survives_unresolvable_ip() {+ let geoip_service = create_test_geoip_service();+ let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));+ let name = Value::String("John".to_string());++ let person_properties = HashMap::from([+ ("name".to_string(), name.clone()),+ ("$geoip_country_code".to_string(), Value::Null),+ ]);++ let result = properties::get_person_property_overrides(+ false,+ Some(person_properties),+ &ip,+ &geoip_service,+ );++ let result = result.expect("expected property overrides");+ assert_eq!(result.len(), 2);+ assert_eq!(result.get("name"), Some(&name));+ assert_eq!(result.get("$geoip_country_code"), Some(&Value::Null));+}+/// `supplied` is the value the request sends for `$geoip_country_code`, or `None` for a request/// that sends person properties without that key at all (the `unrelated_key_only` case).#[rstest]-#[case::differs(false, Some(Value::String("DE".to_string())), true)]-#[case::matches_lookup(false, Some(Value::String("US".to_string())), false)]-#[case::null_counts_as_absent(false, Some(Value::Null), false)]-#[case::unrelated_key_only(false, None, false)]-#[case::geoip_disabled(true, Some(Value::String("DE".to_string())), false)]+#[case::differs(false, Some(Value::String("DE".to_string())), true, "DE")]+#[case::matches_lookup(false, Some(Value::String("US".to_string())), false, "US")]+#[case::null_counts_as_absent(false, Some(Value::Null), false, "US")]+#[case::unrelated_key_only(false, None, false, "US")]+#[case::geoip_disabled(true, Some(Value::String("DE".to_string())), false, "DE")]#[tokio::test]async fn test_canonical_log_records_geoip_divergence(#[case] geoip_disabled: bool,#[case] supplied: Option<Value>,- #[case] expected: bool,+ #[case] expected_divergence: bool,+ #[case] expected_country: &str,) {let geoip_service = create_test_geoip_service();let ip = IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8));@@ -228,16 +265,22 @@ async fn test_canonical_log_records_geoip_divergence(}).await;- assert_eq!(final_log.geoip_properties_differ_from_lookup, expected);+ assert_eq!(+ final_log.geoip_properties_differ_from_lookup,+ expected_divergence+ );- // Measuring only: the lookup still overwrites whatever the request sent.- if !geoip_disabled {- let result = result.expect("expected property overrides");- assert_eq!(- result.get("$geoip_country_code"),- Some(&Value::String("US".to_string()))- );- }+ // Supplied values win; the lookup only fills keys the request left absent or null.+ let result = result.expect("expected property overrides");+ assert_eq!(+ result.get("$geoip_country_code"),+ Some(&Value::String(expected_country.to_string()))+ );+ assert_eq!(+ result.contains_key("$geoip_country_name"),+ !geoip_disabled,+ "the lookup should fill the geoip keys the request didn't send, unless disabled"+ );}#[tokio::test]diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 019b5921070d..0fd9ec90ad98 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -75,9 +75,10 @@ pub const DB_PERSON_AND_GROUP_PROPERTIES_READS_COUNTER: &str =pub const FLAG_REQUESTS_COUNTER: &str = "flags_requests_total";pub const FLAG_REQUESTS_LATENCY: &str = "flags_requests_duration_ms";// Incremented once per request that supplied a `$geoip_*` value disagreeing with the MaxMind-// lookup. The lookup currently wins, so this only sizes the population that a pending change to-// let request values win would affect. Removable once that change has shipped and settled.-// Per-team and per-SDK attribution lives in the canonical log line via Loki.+// lookup. Supplied values win over the lookup, so this counts the requests that evaluate+// differently than they would under lookup-wins precedence. Removable once the precedence+// change has shipped and settled. Per-team and per-SDK attribution lives in the canonical log+// line via Loki.pub const GEOIP_PROPERTIES_DIFFER_FROM_LOOKUP_COUNTER: &str ="flags_geoip_properties_differ_from_lookup_total";