Skip to content

: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.

fix(flags): tolerate behavioral cohort filters instead of failing eval (#72076)

Phil Haack38bb34ff9232
diff --git a/rust/feature-flags/src/cohorts/cohort_models.rs b/rust/feature-flags/src/cohorts/cohort_models.rs
index 0f88ba8ea02a..231b1532160f 100644
--- a/rust/feature-flags/src/cohorts/cohort_models.rs
+++ b/rust/feature-flags/src/cohorts/cohort_models.rs
@@ -1,6 +1,7 @@
-use crate::properties::property_models::PropertyFilter;
+use crate::properties::property_models::{PropertyFilter, PropertyType};
use crate::utils::json_size::estimate_json_size;
use chrono::{DateTime, Utc};
+use serde::de::IgnoredAny;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::FromRow;
@@ -143,19 +144,19 @@ pub enum CohortPropertyType {
OR,
}
-#[derive(Debug, Clone, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize)]
pub struct CohortProperty {
pub properties: InnerCohortProperty,
}
-#[derive(Debug, Clone, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize)]
pub struct InnerCohortProperty {
#[serde(rename = "type")]
pub prop_type: CohortPropertyType,
pub values: Vec<CohortValuesItem>,
}
-#[derive(Debug, Clone, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize)]
pub struct CohortValues {
#[serde(rename = "type")]
pub prop_type: String,
@@ -171,11 +172,43 @@ pub struct CohortValues {
/// `PropertyFilter` requires `key`, so a group (no `key`) falls through to `Group`,
/// while an ambiguous object carrying both `key` and `values` is kept as the filter
/// it most likely is rather than silently dropping its `key`/`value`/`operator`.
-#[derive(Debug, Clone, Deserialize, Serialize)]
+///
+/// `MalformedKnownType` catches a leaf whose `type` names one of the supported
+/// `PropertyType`s (so it isn't genuinely unsupported) but is otherwise malformed for
+/// that type, e.g. a `cohort` filter missing the required `key` — a shape that could
+/// exist in storage from before cohort filters were validated on write. It's tried
+/// after `Filter`/`Group` (a well-formed leaf of a known type already matched one of
+/// those) and before `Unsupported`, so a malformed-but-known-type leaf still surfaces
+/// as a parsing error instead of silently degrading like a genuinely unrecognized type
+/// does.
+///
+/// `Unsupported` is the catch-all last variant: a leaf whose `type` this evaluator
+/// can't resolve from person/group properties — most commonly a `behavioral` filter,
+/// which needs event history over time. An unsupported leaf contributes no cohort
+/// dependency and is a non-match during evaluation, so the cohort's evaluable leaves
+/// still decide membership. The payload is discarded via `IgnoredAny` rather than kept
+/// as `serde_json::Value` since nothing reads it, avoiding materializing every
+/// unsupported leaf on each cohort parse. Because it deserializes any JSON, it must
+/// stay last so real filters and groups are tried first; this also means the whole
+/// type tree can no longer derive `Serialize` (`IgnoredAny` doesn't implement it) —
+/// nothing in the codebase serializes cohort filters back out, only the raw JSON on
+/// `Cohort::filters`.
+#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum CohortValuesItem {
Filter(PropertyFilter),
Group(CohortValues),
+ MalformedKnownType(KnownTypeMarker),
+ Unsupported(IgnoredAny),
+}
+
+/// Matches only the `type` field of a leaf, so it succeeds whenever `type` names a
+/// supported `PropertyType` even if the rest of the leaf is malformed for that type.
+/// See `CohortValuesItem::MalformedKnownType`.
+#[derive(Debug, Clone, Deserialize)]
+pub struct KnownTypeMarker {
+ #[serde(rename = "type")]
+ pub prop_type: PropertyType,
}
#[cfg(test)]
@@ -602,6 +635,30 @@ mod tests {
"Large JSON should have significant estimated size"
);
}
+
+ #[test]
+ fn test_cohort_values_item_untagged_variant_ordering() {
+ // The untagged variant order must keep real filters and groups ahead of the
+ // catch-all: a leaf property filter stays a `Filter`, a group stays a `Group`,
+ // and only a leaf whose `type` we can't parse (e.g. `behavioral`) falls through
+ // to `Unsupported` instead of aborting the whole cohort parse.
+ let filter: CohortValuesItem = serde_json::from_value(serde_json::json!(
+ {"key": "email", "type": "person", "value": "@posthog.com", "operator": "icontains"}
+ ))
+ .unwrap();
+ assert!(matches!(filter, CohortValuesItem::Filter(_)));
+
+ let group: CohortValuesItem =
+ serde_json::from_value(serde_json::json!({"type": "AND", "values": []})).unwrap();
+ assert!(matches!(group, CohortValuesItem::Group(_)));
+
+ let behavioral: CohortValuesItem = serde_json::from_value(serde_json::json!(
+ {"key": "$pageview", "type": "behavioral", "value": "performed_event",
+ "negation": false, "event_type": "events", "time_value": "30", "time_interval": "day"}
+ ))
+ .unwrap();
+ assert!(matches!(behavioral, CohortValuesItem::Unsupported(_)));
+ }
}
#[cfg(test)]
diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rs
index 9bc4aa6c3c72..a604958558aa 100644
--- a/rust/feature-flags/src/cohorts/cohort_operations.rs
+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs
@@ -10,6 +10,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::properties::property_matching::match_property;
use crate::properties::property_models::OperatorType;
use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};
@@ -213,6 +214,16 @@ impl Cohort {
}
}
}
+ // A known filter type (e.g. `cohort`) that's otherwise malformed, such as a
+ // cohort reference missing `key`. Fail loud rather than silently dropping
+ // what may be a real dependency.
+ CohortValuesItem::MalformedKnownType(_) => {
+ return Err(FlagError::CohortFiltersParsingError);
+ }
+ // No cohort dependency to contribute; count it and continue.
+ CohortValuesItem::Unsupported(_) => {
+ common_metrics::inc(COHORT_UNSUPPORTED_FILTER_COUNTER, &[], 1);
+ }
}
Ok(())
}
@@ -284,6 +295,11 @@ fn evaluate_cohort_item(
CohortValuesItem::Filter(filter) => {
evaluate_cohort_filter(filter, target_properties, cohort_matches, team_timezone)
}
+ // A known filter type that's otherwise malformed; fail loud rather than
+ // silently resolving to non-match (see `traverse_item`).
+ CohortValuesItem::MalformedKnownType(_) => Err(FlagError::CohortFiltersParsingError),
+ // Non-match, so sibling leaves decide membership via their AND/OR combination.
+ CohortValuesItem::Unsupported(_) => Ok(false),
}
}
@@ -1373,4 +1389,173 @@ mod tests {
Err(FlagError::CohortFiltersParsingError)
));
}
+
+ /// A `behavioral` filter leaf — unresolvable from person/group properties, so it
+ /// always parses to `CohortValuesItem::Unsupported`.
+ fn behavioral_leaf_json() -> serde_json::Value {
+ json!({"key": "$pageview", "type": "behavioral", "value": "performed_event",
+ "negation": false, "event_type": "events", "time_value": "30", "time_interval": "day"})
+ }
+
+ #[test]
+ fn test_extract_dependencies_tolerates_behavioral_leaf() {
+ // A `behavioral` leaf can't be resolved from person properties here, but it
+ // must not abort dependency extraction — the sibling cohort reference should
+ // still be discovered. Before the fix this returned CohortFiltersParsingError.
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "OR",
+ "values": [
+ behavioral_leaf_json(),
+ {"key": "id", "type": "cohort", "value": 7, "negation": false}
+ ]
+ }]
+ }
+ }),
+ );
+
+ let dependencies = cohort
+ .extract_dependencies()
+ .expect("a behavioral leaf must not fail cohort dependency extraction");
+ assert_eq!(dependencies, [7].into_iter().collect());
+ }
+
+ #[test]
+ fn test_evaluate_dynamic_cohorts_with_behavioral_leaf_in_or_group() {
+ // In an OR group, an unresolvable behavioral leaf is a non-match, so an
+ // evaluable person-property sibling still decides membership.
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "OR",
+ "values": [
+ behavioral_leaf_json(),
+ {"key": "plan", "type": "person", "value": "pro", "operator": "exact"}
+ ]
+ }]
+ }
+ }),
+ );
+
+ let cohorts = vec![cohort];
+ let static_cohort_matches = HashMap::new();
+
+ let test_cases = [
+ (json!("pro"), true), // person-property sibling matches -> cohort matches
+ (json!("free"), false), // sibling misses, behavioral leaf non-matches -> no match
+ ];
+ for (plan, expected) in test_cases {
+ let target_properties = HashMap::from([("plan".to_string(), plan.clone())]);
+ let result = evaluate_dynamic_cohorts(
+ 1,
+ &target_properties,
+ &cohorts,
+ &static_cohort_matches,
+ Tz::UTC,
+ )
+ .unwrap();
+ assert_eq!(
+ result, expected,
+ "plan={plan} should evaluate to {expected}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_evaluate_dynamic_cohorts_with_behavioral_leaf_in_and_group_never_matches() {
+ // In an AND group, the unresolvable behavioral leaf (treated as a non-match)
+ // prevents the group from matching even when the person-property leaf is satisfied.
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "AND",
+ "values": [
+ {"key": "plan", "type": "person", "value": "pro", "operator": "exact"},
+ behavioral_leaf_json()
+ ]
+ }]
+ }
+ }),
+ );
+
+ let cohorts = vec![cohort];
+ let target_properties = HashMap::from([("plan".to_string(), json!("pro"))]);
+ assert!(matches!(
+ evaluate_dynamic_cohorts(1, &target_properties, &cohorts, &HashMap::new(), Tz::UTC),
+ Ok(false)
+ ));
+ }
+
+ #[test]
+ fn test_purely_behavioral_cohort_resolves_to_non_match_with_no_dependencies() {
+ // A cohort whose only criterion is behavioral has no evaluable leaves at all:
+ // dependency extraction finds nothing, and evaluation resolves to non-match
+ // instead of aborting the whole cohort parse.
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "OR",
+ "values": [behavioral_leaf_json()]
+ }]
+ }
+ }),
+ );
+
+ let dependencies = cohort
+ .extract_dependencies()
+ .expect("a purely behavioral cohort must not fail dependency extraction");
+ assert!(dependencies.is_empty());
+
+ let cohorts = vec![cohort];
+ assert!(matches!(
+ evaluate_dynamic_cohorts(1, &HashMap::new(), &cohorts, &HashMap::new(), Tz::UTC),
+ Ok(false)
+ ));
+ }
+
+ #[test]
+ fn test_cohort_filter_of_known_type_missing_required_field_still_errors() {
+ // A `type: "cohort"` leaf missing the required `key` matches neither `Filter`
+ // (no `key`) nor `Group` (no `values`). Its `type` is still a recognized
+ // `PropertyType`, though, so this must surface as a parsing error rather than
+ // silently falling through to `Unsupported` like a genuinely unrecognized type
+ // (e.g. `behavioral`) does — losing a real cohort dependency edge silently
+ // would be worse than the loud failure this replaces.
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "OR",
+ "values": [{"type": "cohort", "value": 7, "negation": false}]
+ }]
+ }
+ }),
+ );
+
+ assert!(matches!(
+ cohort.extract_dependencies(),
+ Err(FlagError::CohortFiltersParsingError)
+ ));
+
+ let cohorts = vec![cohort];
+ assert!(matches!(
+ evaluate_dynamic_cohorts(1, &HashMap::new(), &cohorts, &HashMap::new(), Tz::UTC),
+ Err(FlagError::CohortFiltersParsingError)
+ ));
+ }
}
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index b5a8666978f2..7c4f58182558 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -20,6 +20,9 @@ pub const COHORT_CACHE_HIT_COUNTER: &str = "flags_cohort_cache_hit_total";
pub const COHORT_CACHE_MISS_COUNTER: &str = "flags_cohort_cache_miss_total";
pub const COHORT_CACHE_SIZE_BYTES_GAUGE: &str = "flags_cohort_cache_size_bytes";
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";
// 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 was