: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): measure requests whose geoip values differ from lookup (#80995)
Phil Haackc8cfa052a498
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex e9215ba67bf6..669cabbda47c 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -170,6 +170,22 @@ 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.++Before changing that, the affected population is being measured:++- `flags_geoip_properties_differ_from_lookup_total` counts requests that supplied a `$geoip_*` value disagreeing with the lookup.+- 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.+### `FlagsResponse` (v2 response)```rustdiff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rsindex 9f93799c9cb3..9eca4660fa60 100644--- a/rust/feature-flags/src/handler/canonical_log.rs+++ b/rust/feature-flags/src/handler/canonical_log.rs@@ -199,6 +199,10 @@ pub struct FlagsCanonicalLogLine {pub flags_experience_continuity: usize,pub flags_disabled: bool,pub quota_limited: bool,+ /// Set when the request supplied a `$geoip_*` value disagreeing with the MaxMind lookup.+ /// Attributable counterpart to `flags_geoip_properties_differ_from_lookup_total`, which has+ /// no labels.+ pub geoip_properties_differ_from_lookup: bool,/// Flag keys that were overridden with custom definitions (for testing/historical evaluation)pub flags_overridden: Option<Vec<String>>,/// Source of the flags data: "Redis", "S3", or "Fallback" (PostgreSQL).@@ -329,6 +333,7 @@ impl Default for FlagsCanonicalLogLine {flags_experience_continuity: 0,flags_disabled: false,quota_limited: false,+ geoip_properties_differ_from_lookup: false,flags_overridden: None,flags_cache_source: None,eval: EvalCounters::default(),@@ -398,6 +403,7 @@ impl FlagsCanonicalLogLine {flags_device_id_bucketing = self.eval.flags_device_id_bucketing,flags_disabled = self.flags_disabled,quota_limited = self.quota_limited,+ geoip_properties_differ_from_lookup = self.geoip_properties_differ_from_lookup,flags_overridden = ?self.flags_overridden,flags_cache_source = self.flags_cache_source,db_property_fetches = self.db_property_fetches,diff --git a/rust/feature-flags/src/handler/properties.rs b/rust/feature-flags/src/handler/properties.rsindex 9a5275a7c9ce..f59c8321853b 100644--- a/rust/feature-flags/src/handler/properties.rs+++ b/rust/feature-flags/src/handler/properties.rs@@ -1,8 +1,13 @@-use crate::{api::errors::FlagError, flags::flag_request::FlagRequest};+use crate::{+ api::errors::FlagError, flags::flag_request::FlagRequest,+ metrics::consts::GEOIP_PROPERTIES_DIFFER_FROM_LOOKUP_COUNTER,+};use common_geoip::GeoIpClient;+use common_metrics::inc;use serde_json::Value;use std::{collections::HashMap, net::IpAddr};+use super::canonical_log::with_canonical_log;use super::types::{RequestContext, RequestPropertyOverrides};pub fn prepare_overrides(@@ -41,6 +46,27 @@ 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.+fn record_geoip_divergence(+ person_properties: &HashMap<String, Value>,+ geoip_props: &HashMap<String, String>,+) {+ let diverged = geoip_props.iter().any(|(key, resolved)| {+ person_properties.get(key).is_some_and(|supplied| {+ !supplied.is_null() && supplied.as_str() != Some(resolved.as_str())+ })+ });+ if diverged {+ inc(GEOIP_PROPERTIES_DIFFER_FROM_LOOKUP_COUNTER, &[], 1);+ with_canonical_log(|log| log.geoip_properties_differ_from_lookup = true);+ }+}+pub fn get_person_property_overrides(geoip_disabled: bool,person_properties: Option<HashMap<String, Value>>,@@ -50,6 +76,7 @@ pub fn get_person_property_overrides(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))));}Some(props)diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rsindex 0c116c47e964..79dce71dceca 100644--- a/rust/feature-flags/src/handler/tests.rs+++ b/rust/feature-flags/src/handler/tests.rs@@ -24,8 +24,12 @@ use crate::{flag_service::FlagService,},handler::{- apply_minimal_flag_called_events, decoding, evaluation::evaluate_feature_flags,- flags::fetch_and_filter, properties, FeatureFlagEvaluationContext,+ apply_minimal_flag_called_events,+ canonical_log::{run_with_canonical_log, FlagsCanonicalLogLine},+ decoding,+ evaluation::evaluate_feature_flags,+ flags::fetch_and_filter,+ properties, FeatureFlagEvaluationContext,},mock,properties::property_models::PropertyType,@@ -177,6 +181,65 @@ fn test_geoip_person_property_overrides(}}+/// `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)]+#[tokio::test]+async fn test_canonical_log_records_geoip_divergence(+ #[case] geoip_disabled: bool,+ #[case] supplied: Option<Value>,+ #[case] expected: bool,+) {+ let geoip_service = create_test_geoip_service();+ let ip = IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8));++ // The `matches_lookup` case is only meaningful if the lookup really resolves this value.+ assert_eq!(+ geoip_service+ .get_geoip_properties(&ip.to_string())+ .unwrap_or_default()+ .get("$geoip_country_code")+ .map(String::as_str),+ Some("US")+ );++ let person_properties = supplied+ .map(|value| HashMap::from([("$geoip_country_code".to_string(), value)]))+ .or_else(|| {+ Some(HashMap::from([(+ "name".to_string(),+ Value::String("John".to_string()),+ )]))+ });++ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), ip.to_string());+ let (result, final_log) = run_with_canonical_log(log, async {+ properties::get_person_property_overrides(+ geoip_disabled,+ person_properties,+ &ip,+ &geoip_service,+ )+ })+ .await;++ assert_eq!(final_log.geoip_properties_differ_from_lookup, expected);++ // 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()))+ );+ }+}+#[tokio::test]async fn test_evaluate_feature_flags() {let reader: Arc<dyn Client + Send + Sync> = setup_pg_reader_client(None);diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 65da8c5149fd..019b5921070d 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -74,6 +74,12 @@ pub const DB_PERSON_AND_GROUP_PROPERTIES_READS_COUNTER: &str ="flags_db_person_and_group_properties_reads_total";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.+pub const GEOIP_PROPERTIES_DIFFER_FROM_LOOKUP_COUNTER: &str =+ "flags_geoip_properties_differ_from_lookup_total";// Internal batch flag evaluation endpoint (static cohort generation). Dedicated// `flags_batch_eval_*` names keep batch traffic separable from live `/flags` metrics.