: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): support between/not_between operators in cohort filters (#73399)
Phil Haack0fc450a18fd0
diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rsindex a604958558aa..edc502d76b97 100644--- a/rust/feature-flags/src/cohorts/cohort_operations.rs+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs@@ -1,7 +1,9 @@+use once_cell::sync::Lazy;use serde_json::Value;use std::borrow::Borrow;use std::collections::HashMap;use std::collections::HashSet;+use std::sync::Mutex;use super::cohort_models::CohortPropertyType;use super::cohort_models::CohortValues;@@ -10,7 +12,7 @@ use crate::cohorts::cohort_models::{Cohort, CohortId, CohortProperty, CohortValuesItem, InnerCohortProperty,};use crate::database::get_connection_with_metrics;-use crate::metrics::consts::COHORT_UNSUPPORTED_FILTER_COUNTER;+use crate::metrics::consts::{COHORT_MALFORMED_FILTER_COUNTER, COHORT_UNSUPPORTED_FILTER_COUNTER};use crate::properties::property_matching::match_property;use crate::properties::property_models::OperatorType;use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};@@ -24,6 +26,32 @@ use common_types::TeamId;/// `/flags` path against stack overflow from an adversarially deep filter tree.const MAX_COHORT_FILTER_DEPTH: usize = 64;+/// Cohorts already warned about by `record_malformed_cohort_filter`, so a persistently+/// malformed cohort on the hot `/flags` path logs its identifying context once per+/// process lifetime instead of flooding logs on every request.+static WARNED_MALFORMED_COHORTS: Lazy<Mutex<HashSet<(TeamId, CohortId)>>> =+ Lazy::new(|| Mutex::new(HashSet::new()));++/// Logs and counts a cohort whose filters failed dependency extraction or evaluation+/// with `CohortFiltersParsingError` (malformed leaf, excessive nesting, or other+/// structural error surfaced by `traverse_filters`/`InnerCohortProperty::evaluate`).+///+/// The counter is unlabeled (cardinality), so this log is the only place the cohort+/// and team ids are recorded; it's deduped per cohort so it stays visible at `warn`+/// without flooding logs when the same cohort keeps failing.+fn record_malformed_cohort_filter(cohort_id: CohortId, team_id: TeamId, phase: &str) {+ common_metrics::inc(COHORT_MALFORMED_FILTER_COUNTER, &[], 1);++ let mut warned = WARNED_MALFORMED_COHORTS.lock().unwrap();+ if warned.insert((team_id, cohort_id)) {+ tracing::warn!(+ cohort_id,+ team_id,+ "Cohort filters contain a malformed or unparsable leaf; failing {phase}"+ );+ }+}+/// Column list for `posthog_cohort` queries. Must match the fields in `Cohort` (sqlx::FromRow).const COHORT_COLUMNS: &str = r#"c.id, c.name, c.description, c.team_id, c.deleted, c.filters,@@ -147,7 +175,9 @@ impl Cohort {})?;let mut dependencies = HashSet::new();- Self::traverse_filters(&cohort_property.properties, &mut dependencies)?;+ Self::traverse_filters(&cohort_property.properties, &mut dependencies).inspect_err(+ |_| record_malformed_cohort_filter(self.id, self.team_id, "dependency extraction"),+ )?;Ok(dependencies)}@@ -415,6 +445,7 @@ fn evaluate_single_cohort(cohort_property.properties.evaluate(target_properties, evaluation_results, team_timezone)+ .inspect_err(|_| record_malformed_cohort_filter(cohort.id, cohort.team_id, "evaluation"))}pub fn evaluate_dynamic_cohorts(@@ -1558,4 +1589,114 @@ mod tests {Err(FlagError::CohortFiltersParsingError)));}++ #[test]+ fn test_cohort_with_between_leaf_parses_and_evaluates() {+ // A person-property leaf with the `between` operator (valid in the cohort UI+ // and HogQL, but previously unknown to this evaluator) must parse as a real+ // filter and evaluate with inclusive bounds — not fall through to+ // MalformedKnownType and fail the whole cohort with CohortFiltersParsingError.+ let cohort = create_dynamic_cohort_with_filters(+ 1,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{"key": "tenant_id", "type": "person", "value": [70000, 80000],+ "operator": "between", "negation": false}]+ }]+ }+ }),+ );++ let dependencies = cohort+ .extract_dependencies()+ .expect("a between leaf must not fail cohort dependency extraction");+ assert!(dependencies.is_empty());++ let cohorts = vec![cohort];+ let test_cases = [+ (Some(json!(70000)), true), // inclusive lower bound+ (Some(json!(80000)), true), // inclusive upper bound+ (Some(json!(75000)), true), // inside range+ (Some(json!("75000")), true), // string number coerces+ (Some(json!(90000)), false), // outside range+ (None, false), // missing property+ ];+ for (tenant_id, expected) in test_cases {+ let target_properties = match &tenant_id {+ Some(value) => HashMap::from([("tenant_id".to_string(), value.clone())]),+ None => HashMap::new(),+ };+ let result =+ evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &HashMap::new(), Tz::UTC)+ .unwrap();+ assert_eq!(+ result, expected,+ "tenant_id={tenant_id:?} should evaluate to {expected}"+ );+ }+ }++ #[test]+ fn test_cohort_with_malformed_between_value_is_non_match_not_parse_error() {+ // A between leaf with a malformed value (not a two-element array) deserializes+ // as a regular filter and resolves to a non-match during evaluation, rather+ // than failing the whole cohort parse.+ let cohort = create_dynamic_cohort_with_filters(+ 1,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{"key": "tenant_id", "type": "person", "value": [1, 2, 3],+ "operator": "between", "negation": false}]+ }]+ }+ }),+ );++ assert!(cohort.extract_dependencies().unwrap().is_empty());++ let cohorts = vec![cohort];+ let target_properties = HashMap::from([("tenant_id".to_string(), json!(2))]);+ assert!(matches!(+ evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &HashMap::new(), Tz::UTC),+ Ok(false)+ ));+ }++ #[test]+ fn test_cohort_with_min_operator_alias_evaluates_as_gte() {+ // Legacy `min`/`max` operator aliases are only normalized to gte/lte on the+ // flag write path; cohort filters can still carry them and must evaluate.+ let cohort = create_dynamic_cohort_with_filters(+ 1,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{"key": "seats", "type": "person", "value": "30",+ "operator": "min", "negation": false}]+ }]+ }+ }),+ );++ let cohorts = vec![cohort];+ let test_cases = [(json!(40), true), (json!(30), true), (json!(20), false)];+ for (seats, expected) in test_cases {+ let target_properties = HashMap::from([("seats".to_string(), seats.clone())]);+ let result =+ evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &HashMap::new(), Tz::UTC)+ .unwrap();+ assert_eq!(+ result, expected,+ "seats={seats} should evaluate to {expected}"+ );+ }+ }}diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 70f5b50eba39..ca97099537a0 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -23,6 +23,12 @@ pub const COHORT_CACHE_ENTRIES_GAUGE: &str = "flags_cohort_cache_entries";// Incremented once per unsupported cohort filter leaf (e.g. a `behavioral` filter)// skipped during dependency extraction, instead of failing the whole cohort parse.pub const COHORT_UNSUPPORTED_FILTER_COUNTER: &str = "flags_cohort_unsupported_filter_total";+// Incremented once per cohort whose filters fail dependency extraction or evaluation+// with CohortFiltersParsingError — most commonly a malformed leaf of a known type+// (CohortValuesItem::MalformedKnownType), but also excessive nesting depth or other+// structural errors. Cohort and team ids are in the companion debug log, not metric+// labels (cardinality).+pub const COHORT_MALFORMED_FILTER_COUNTER: &str = "flags_cohort_malformed_filter_total";// Realtime cohort membership cache (CachedCohortMembershipProvider, keyed on// (team_id, person_uuid)). hit = lookup fully served from cache; miss = a// behavioral cohorts DB query was issued (no cache entry, or the entry wasdiff --git a/rust/feature-flags/src/properties/property_matching.rs b/rust/feature-flags/src/properties/property_matching.rsindex 1338422595c1..d293ed5f7f7a 100644--- a/rust/feature-flags/src/properties/property_matching.rs+++ b/rust/feature-flags/src/properties/property_matching.rs@@ -68,6 +68,27 @@ pub fn to_f64_representation(value: &Value) -> Option<f64> {to_string_representation(value).parse::<f64>().ok()}+/// Parses the property value being matched as f64, for the numeric comparison operators+/// (Gt/Gte/Lt/Lte, Between/NotBetween). A missing or non-numeric value is a validation+/// error here, distinct from `match_value.is_none()` short-circuiting to `Ok(false)`+/// earlier in each operator's match arm.+fn parse_numeric_match_value(+ match_value: Option<&Value>,+ key: &str,+ operator: OperatorType,+) -> Result<f64, FlagMatchingError> {+ let match_value = match_value.unwrap_or(&Value::Null);+ to_f64_representation(match_value).ok_or_else(|| {+ tracing::debug!(+ "Failed to parse property value '{}' for key '{}' as number for operator {:?}",+ match_value,+ key,+ operator+ );+ FlagMatchingError::ValidationError("value is not a number".to_string())+ })+}+/// Strip 'v' prefix if present (e.g., "v1.2.3" -> "1.2.3")fn normalize_version_string(version: &str) -> &str {version.strip_prefix('v').unwrap_or(version).trim()@@ -329,22 +350,7 @@ pub fn match_property(}};- let parsed_value = match to_f64_representation(- match_value.unwrap_or(&serde_json::Value::Null),- ) {- Some(parsed_value) => parsed_value,- None => {- tracing::debug!(- "Failed to parse property value '{}' for key '{}' as number for operator {:?}",- match_value.unwrap_or(&serde_json::Value::Null),- key,- operator- );- return Err(FlagMatchingError::ValidationError(- "value is not a number".to_string(),- ));- }- };+ let parsed_value = parse_numeric_match_value(match_value, key, operator)?;if let Some(filter_value) = to_f64_representation(value) {Ok(compare(parsed_value, filter_value, operator))@@ -360,6 +366,67 @@ pub fn match_property())}}+ OperatorType::Between | OperatorType::NotBetween => {+ if match_value.is_none() {+ // When value doesn't exist:+ // - for Between/NotBetween: it's not a match (false)+ return Ok(false);+ }++ // Mirrors HogQL semantics (posthog/hogql/property.py): between is inclusive+ // on both ends, not_between is its complement, and the filter value must be+ // a two-element numeric array with min <= max.+ let bounds = match value.as_array() {+ Some(bounds) if bounds.len() == 2 => bounds,+ _ => {+ tracing::debug!(+ "Invalid filter value '{}' for key '{}' for operator {:?}",+ value,+ key,+ operator+ );+ return Err(FlagMatchingError::ValidationError(+ "between/not_between operator requires a two-element array [min, max]"+ .to_string(),+ ));+ }+ };++ let (low, high) = match (+ to_f64_representation(&bounds[0]),+ to_f64_representation(&bounds[1]),+ ) {+ (Some(low), Some(high)) if !low.is_nan() && !high.is_nan() => (low, high),+ _ => {+ return Err(FlagMatchingError::ValidationError(+ "between/not_between operator requires numeric values".to_string(),+ ));+ }+ };+ if low > high {+ return Err(FlagMatchingError::ValidationError(+ "between/not_between operator requires min value to be less than or equal to max value"+ .to_string(),+ ));+ }++ let parsed_value = parse_numeric_match_value(match_value, key, operator)?;+ if parsed_value.is_nan() {+ // "NaN" parses successfully as f64::NAN rather than failing, but a NaN+ // property value is malformed input, not a real number: it must be a+ // non-match for both operators, not just the ones where NaN comparisons+ // happen to fall out as false (Between would; NotBetween would flip it+ // to true via `!in_range`).+ return Ok(false);+ }++ let in_range = parsed_value >= low && parsed_value <= high;+ if operator == OperatorType::Between {+ Ok(in_range)+ } else {+ Ok(!in_range)+ }+ }OperatorType::SemverGt| OperatorType::SemverGte| OperatorType::SemverLt@@ -1543,6 +1610,126 @@ mod test_match_properties {// );}+ #[test_case(json!(70000), true; "at lower bound is inclusive")]+ #[test_case(json!(80000), true; "at upper bound is inclusive")]+ #[test_case(json!(75000), true; "inside range")]+ #[test_case(json!("75000"), true; "string number property value coerces")]+ #[test_case(json!(69999), false; "below range")]+ #[test_case(json!(80001), false; "above range")]+ fn test_match_properties_between_operator(property_value: Value, expected: bool) {+ let between = PropertyFilter {+ key: "key".to_string(),+ value: Some(json!([70000, 80000])),+ operator: Some(OperatorType::Between),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ };+ let not_between = PropertyFilter {+ operator: Some(OperatorType::NotBetween),+ ..between.clone()+ };+ let props = HashMap::from([("key".to_string(), property_value)]);++ assert_eq!(+ match_property(&between, &props, true).expect("expected match to exist"),+ expected+ );+ // not_between is the exact complement+ assert_eq!(+ match_property(¬_between, &props, true).expect("expected match to exist"),+ !expected+ );+ }++ #[test]+ fn test_match_properties_between_operator_edge_cases() {+ let between = PropertyFilter {+ key: "key".to_string(),+ // String bounds coerce to numbers like the Gt/Lt operators do+ value: Some(json!(["70000", "80000"])),+ operator: Some(OperatorType::Between),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ };++ assert!(match_property(+ &between,+ &HashMap::from([("key".to_string(), json!(75000))]),+ true+ )+ .expect("expected match to exist"));++ // Missing person property is not a match, for both between and not_between+ assert!(!match_property(&between, &HashMap::new(), false).expect("expected match to exist"));+ let not_between = PropertyFilter {+ operator: Some(OperatorType::NotBetween),+ ..between.clone()+ };+ assert!(+ !match_property(¬_between, &HashMap::new(), false).expect("expected match to exist")+ );++ // Non-numeric person property value is a validation error (like Gt/Lt), which+ // cohort evaluation resolves to a non-match+ assert!(matches!(+ match_property(+ &between,+ &HashMap::from([("key".to_string(), json!("abc"))]),+ true+ ),+ Err(FlagMatchingError::ValidationError(_))+ ));++ // A filter with no value is not a match+ let no_value = PropertyFilter {+ value: None,+ ..between.clone()+ };+ assert!(!match_property(+ &no_value,+ &HashMap::from([("key".to_string(), json!(75000))]),+ true+ )+ .expect("expected match to exist"));+ }++ #[test_case(json!(75000); "not an array")]+ #[test_case(json!([70000]); "one element")]+ #[test_case(json!([70000, 75000, 80000]); "three elements")]+ #[test_case(json!(["a", "b"]); "non-numeric bounds")]+ #[test_case(json!([80000, 70000]); "min greater than max")]+ #[test_case(json!(["NaN", 80000]); "NaN lower bound")]+ #[test_case(json!([70000, "NaN"]); "NaN upper bound")]+ fn test_match_properties_between_operator_malformed_filter_value(filter_value: Value) {+ for operator in [OperatorType::Between, OperatorType::NotBetween] {+ let property = PropertyFilter {+ key: "key".to_string(),+ value: Some(filter_value.clone()),+ operator: Some(operator),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ };++ assert!(matches!(+ match_property(+ &property,+ &HashMap::from([("key".to_string(), json!(75000))]),+ true+ ),+ Err(FlagMatchingError::ValidationError(_))+ ));+ }+ }+#[test]fn test_none_property_value_with_all_operators() {let property_a = PropertyFilter {diff --git a/rust/feature-flags/src/properties/property_models.rs b/rust/feature-flags/src/properties/property_models.rsindex 52d0a994a22f..4ab8e0cddd92 100644--- a/rust/feature-flags/src/properties/property_models.rs+++ b/rust/feature-flags/src/properties/property_models.rs@@ -2,7 +2,10 @@ use serde::{Deserialize, Serialize};// Keep in sync with FEATURE_FLAG_SUPPORTED_OPERATORS in// products/feature_flags/backend/api/feature_flag.py (mirrored by the filters serializer in-// products/feature_flags/backend/api/filters_schema.py — issue #50084)+// products/feature_flags/backend/api/filters_schema.py — issue #50084). This enum is+// deliberately a superset: cohort filters don't go through flag-level operator validation,+// so operators the cohort UI allows (between/not_between, and the min/max aliases mirroring+// FEATURE_FLAG_OPERATOR_ALIASES) must deserialize here even though the flag API rejects them.#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]#[serde(rename_all = "snake_case")]pub enum OperatorType {@@ -16,8 +19,12 @@ pub enum OperatorType {NotRegex,Gt,Lt,+ #[serde(alias = "min")]Gte,+ #[serde(alias = "max")]Lte,+ Between,+ NotBetween,SemverGt,SemverGte,SemverLt,@@ -183,4 +190,44 @@ mod tests {assert_eq!(filter.key, "email");}++ #[test]+ fn deserializes_between_operators_and_min_max_aliases() {+ // Cohort filters can carry operators the flag API rejects (between/not_between)+ // and the legacy min/max aliases that only the flag write path normalizes to+ // gte/lte — all of them must deserialize instead of failing the whole cohort.+ let cases = [+ ("between", OperatorType::Between),+ ("not_between", OperatorType::NotBetween),+ ("min", OperatorType::Gte),+ ("max", OperatorType::Lte),+ ];+ for (wire_name, expected) in cases {+ let operator: OperatorType = serde_json::from_value(serde_json::json!(wire_name))+ .unwrap_or_else(|_| panic!("operator '{wire_name}' should deserialize"));+ assert_eq!(operator, expected, "operator '{wire_name}'");+ }++ // The aliases must not change serialization: a Gte/Lte parsed from "min"/"max"+ // still round-trips as "gte"/"lte" (guards the hypercache verifier contract).+ assert_eq!(+ serde_json::to_value(OperatorType::Gte).unwrap(),+ serde_json::json!("gte")+ );+ assert_eq!(+ serde_json::to_value(OperatorType::Lte).unwrap(),+ serde_json::json!("lte")+ );++ // Between/NotBetween must also round-trip to their own canonical wire names+ // (guards the same hypercache verifier contract for the operators this PR adds).+ assert_eq!(+ serde_json::to_value(OperatorType::Between).unwrap(),+ serde_json::json!("between")+ );+ assert_eq!(+ serde_json::to_value(OperatorType::NotBetween).unwrap(),+ serde_json::json!("not_between")+ );+ }}