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.

35.8 KB
Raw Blame
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;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[serde(rename_all = "snake_case")]
#[sqlx(type_name = "varchar", rename_all = "snake_case")]
pub enum CohortType {
    Static,
    PersonProperty,
    Behavioral,
    Realtime,
    Analytical,
}

/// HYPERCACHE CONTRACT: These fields are deserialized from JSON written by Python's
/// `_serialize_cohort()` in products/feature_flags/backend/flags_cache.py. Field changes
/// must follow the expand-and-contract pattern. Golden fixture contract test:
///   cargo test -p feature-flags test_hypercache_contract
#[derive(Debug, Clone, Default, Serialize, Deserialize, FromRow)]
pub struct Cohort {
    pub id: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub team_id: i32,
    pub deleted: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pending_version: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i32>,
    pub is_calculating: bool,
    pub is_static: bool,
    pub errors_calculating: i32,
    pub groups: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by_id: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cohort_type: Option<CohortType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_backfill_person_properties_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub last_backfill_events_at: Option<DateTime<Utc>>,
    /// Which kinds of conditions the cohort's filters contain, written by
    /// `CohortConditionFlags` in products/cohorts/backend/models/cohort.py.
    /// `#[serde(default)]` so hypercache entries written before this field existed
    /// deserialize as `None`, which routes the cohort to dynamic evaluation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition_type: Option<Value>,
    /// When the legacy realtime workflow last computed this cohort's membership into the PG
    /// `cohort_membership` table. Nothing schedules that workflow, so this only stays true of
    /// the cohort's current definition while Django nulls it on edit, which it does for
    /// allowlisted teams' undeleted, non-static, `realtime`-typed cohorts and nothing else.
    /// `#[serde(default)]` so hypercache entries written before this field existed
    /// deserialize as `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_realtime_cohort_calculation_at: Option<DateTime<Utc>>,
}

/// Which cohort stamps count as proof that the PG `cohort_membership` table has been
/// populated for a cohort. Selected by `REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MembershipStampPolicy {
    /// Accept either backfill stamp. `last_backfill_person_properties_at` is overloaded: on
    /// cohorts the legacy realtime workflow stamped it means "computed into
    /// cohort_membership", but the current writer means only "person seed state exists".
    #[default]
    AnyBackfillStamp,
    /// Accept only stamps that prove table population: `last_backfill_events_at` (behavioral
    /// backfill completed and reconciled) or `last_realtime_cohort_calculation_at` (legacy
    /// workflow computed this cohort).
    EventsOrCalculationStamp,
}

impl MembershipStampPolicy {
    /// Whether to resolve this cohort's membership through the realtime `cohort_membership`
    /// table rather than dynamic filter evaluation. A person-property-only cohort never
    /// qualifies: there is no realtime signal to gain from the table.
    pub fn uses_realtime_membership(self, cohort: &Cohort) -> bool {
        matches!(
            cohort.cohort_type,
            Some(CohortType::Realtime) | Some(CohortType::Behavioral)
        ) && self.membership_table_populated(cohort)
            && cohort.has_behavioral_condition()
    }

    fn membership_table_populated(self, cohort: &Cohort) -> bool {
        match self {
            Self::AnyBackfillStamp => {
                cohort.last_backfill_person_properties_at.is_some()
                    || cohort.last_backfill_events_at.is_some()
            }
            Self::EventsOrCalculationStamp => {
                cohort.last_backfill_events_at.is_some()
                    // The legacy workflow only computed `realtime` cohorts and Django only
                    // invalidates the stamp on that type, so on any other type the stamp
                    // vouches for a definition the cohort has since left.
                    || (cohort.last_realtime_cohort_calculation_at.is_some()
                        && cohort.cohort_type == Some(CohortType::Realtime))
            }
        }
    }

    /// `active_policy` label value on `flags_cohort_stamp_policy_divergence_total`.
    pub fn as_label(self) -> &'static str {
        match self {
            Self::AnyBackfillStamp => "any_backfill_stamp",
            Self::EventsOrCalculationStamp => "events_or_calculation_stamp",
        }
    }

    pub fn divergence(cohort: &Cohort) -> Option<StampPolicyDivergence> {
        match (
            Self::AnyBackfillStamp.uses_realtime_membership(cohort),
            Self::EventsOrCalculationStamp.uses_realtime_membership(cohort),
        ) {
            (true, false) => Some(StampPolicyDivergence::WouldLose),
            (false, true) => Some(StampPolicyDivergence::WouldGain),
            (true, true) | (false, false) => None,
        }
    }
}

impl FromStr for MembershipStampPolicy {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "any_backfill_stamp" | "any-backfill-stamp" => Ok(Self::AnyBackfillStamp),
            "events_or_calculation_stamp" | "events-or-calculation-stamp" => {
                Ok(Self::EventsOrCalculationStamp)
            }
            _ => Err(format!(
                "Invalid REALTIME_COHORT_MEMBERSHIP_STAMP_POLICY: '{s}'. Expected 'any_backfill_stamp' or 'events_or_calculation_stamp'"
            )),
        }
    }
}

/// Which way a cohort's routing moves when `AnyBackfillStamp` gives way to
/// `EventsOrCalculationStamp`: `WouldLose` drops to dynamic evaluation, `WouldGain` picks
/// up the realtime membership table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StampPolicyDivergence {
    WouldLose,
    WouldGain,
}

impl StampPolicyDivergence {
    /// `direction` label value on `flags_cohort_stamp_policy_divergence_total`.
    pub fn as_label(self) -> &'static str {
        match self {
            Self::WouldLose => "would_lose",
            Self::WouldGain => "would_gain",
        }
    }
}

/// A cohort membership resolved for condition analysis, and whether it can be stated as fact.
///
/// The dynamic path scores a behavioral or lifecycle leaf as a non-match whatever the cohort's
/// member list holds, so the matcher refuses to trust a non-match on such a cohort. Condition
/// analysis keeps the same distinction, so its explanation never asserts a membership that
/// nothing resolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CohortMembership {
    Member,
    NonMember,
    /// Resolved as a non-member, on a cohort whose behavioral or lifecycle leaf the dynamic path
    /// cannot evaluate.
    UnverifiedNonMember,
}

impl CohortMembership {
    pub fn is_member(self) -> bool {
        matches!(self, Self::Member)
    }
}

impl Cohort {
    /// Returns true if `condition_type` flags a `behavioral` or `lifecycle` leaf condition.
    /// Missing or malformed `condition_type` (e.g. a hypercache entry written before this
    /// field existed, or a cohort with no filters) defaults to `false` — the safe choice,
    /// since it routes the cohort through legacy dynamic filter evaluation instead of the
    /// realtime `cohort_membership` table.
    pub(crate) fn has_behavioral_condition(&self) -> bool {
        self.condition_type
            .as_ref()
            .and_then(|value| value.as_object())
            .map(|flags| {
                flags
                    .get("behavioral")
                    .and_then(Value::as_bool)
                    .unwrap_or(false)
                    || flags
                        .get("lifecycle")
                        .and_then(Value::as_bool)
                        .unwrap_or(false)
            })
            .unwrap_or(false)
    }

    /// Estimates the memory size of this cohort in bytes.
    ///
    /// This approximation accounts for the variable-size JSON fields (`filters`, `query`, `groups`)
    /// which can be arbitrarily large depending on cohort complexity. The estimate is used by the
    /// cache weigher to enforce memory-based eviction rather than count-based eviction.
    ///
    /// **Accuracy note**: This measures serialized JSON size, not actual heap allocations.
    /// `serde_json::Value` stores JSON in a tree structure with per-node overhead not counted here.
    /// Deeply nested structures may use 2-3x more memory than estimated. This is acceptable because:
    /// 1. The estimate is consistent and proportional to actual usage
    /// 2. It correctly identifies large cohorts as heavier than small ones
    /// 3. Operators can tune the cache limit based on observed memory usage
    pub fn estimated_size_bytes(&self) -> usize {
        // Base struct size (fixed-size fields like i32, bool, Option overhead)
        let base_size = std::mem::size_of::<Self>();

        // Variable-size string fields
        let name_size = self.name.as_ref().map_or(0, |s| s.len());
        let desc_size = self.description.as_ref().map_or(0, |s| s.len());

        // JSON fields - estimate size by traversing the structure without allocation
        let filters_size = self.filters.as_ref().map_or(0, estimate_json_size);
        let query_size = self.query.as_ref().map_or(0, estimate_json_size);
        let groups_size = estimate_json_size(&self.groups);

        base_size + name_size + desc_size + filters_size + query_size + groups_size
    }
}

pub type CohortId = i32;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CohortPropertyType {
    AND,
    OR,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CohortProperty {
    pub properties: InnerCohortProperty,
}

#[derive(Debug, Clone, Deserialize)]
pub struct InnerCohortProperty {
    #[serde(rename = "type")]
    pub prop_type: CohortPropertyType,
    pub values: Vec<CohortValuesItem>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CohortValues {
    #[serde(rename = "type")]
    pub prop_type: String,
    pub values: Vec<CohortValuesItem>,
}

/// A single entry inside a cohort property group: either a nested group or a leaf
/// property filter. Mirrors `FilterOrGroup` in posthog/api/cohort.py — the cohort UI
/// always wraps filters in an inner group, but the API contract allows filters
/// directly in a group and arbitrarily deep nesting, so evaluation must accept both.
///
/// `Filter` is listed first because `#[serde(untagged)]` tries variants in order:
/// `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`.
///
/// `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)]
#[allow(clippy::needless_update)]
mod mock_impls {
    use super::*;
    use crate::utils::mock::Mock;

    impl Mock for Cohort {
        fn mock() -> Self {
            Cohort {
                id: 1,
                name: Some("Test Cohort".to_string()),
                description: Some("Test cohort description".to_string()),
                team_id: 1,
                version: Some(1),
                groups: serde_json::json!({}),
                ..Default::default()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_cohort(
        filters: Option<serde_json::Value>,
        query: Option<serde_json::Value>,
        groups: serde_json::Value,
    ) -> Cohort {
        Cohort {
            id: 1,
            name: Some("Test Cohort".to_string()),
            description: Some("A test cohort".to_string()),
            team_id: 1,
            deleted: false,
            filters,
            query,
            version: Some(1),
            pending_version: None,
            count: Some(100),
            is_calculating: false,
            is_static: false,
            errors_calculating: 0,
            groups,
            created_by_id: Some(1),
            cohort_type: None,
            last_backfill_person_properties_at: None,
            last_backfill_events_at: None,
            condition_type: None,
            last_realtime_cohort_calculation_at: None,
        }
    }

    #[test]
    fn test_estimated_size_bytes_minimal_cohort() {
        let cohort = create_test_cohort(None, None, serde_json::json!({}));

        let size = cohort.estimated_size_bytes();

        // Should include at least the base struct size
        assert!(
            size >= std::mem::size_of::<Cohort>(),
            "Size should be at least the base struct size"
        );
    }

    #[test]
    fn test_estimated_size_bytes_with_large_filters() {
        let small_cohort = create_test_cohort(
            Some(serde_json::json!({"type": "AND", "values": []})),
            None,
            serde_json::json!({}),
        );

        let large_filters = serde_json::json!({
            "properties": {
                "type": "OR",
                "values": [
                    {"type": "OR", "values": [
                        {"key": "property_1", "type": "person", "value": ["value1", "value2", "value3", "value4", "value5"], "negation": false, "operator": "exact"},
                        {"key": "property_2", "type": "person", "value": ["value6", "value7", "value8", "value9", "value10"], "negation": false, "operator": "exact"}
                    ]},
                    {"type": "AND", "values": [
                        {"key": "property_3", "type": "person", "value": ["value11", "value12"], "negation": true, "operator": "is_not"}
                    ]}
                ]
            }
        });
        let large_cohort = create_test_cohort(Some(large_filters), None, serde_json::json!({}));

        let small_size = small_cohort.estimated_size_bytes();
        let large_size = large_cohort.estimated_size_bytes();

        assert!(
            large_size > small_size,
            "Large filter cohort ({large_size} bytes) should be larger than small filter cohort ({small_size} bytes)"
        );
    }

    #[test]
    fn test_estimated_size_bytes_includes_all_json_fields() {
        let base_cohort = create_test_cohort(None, None, serde_json::json!({}));

        let with_filters = create_test_cohort(
            Some(serde_json::json!({"key": "value", "nested": {"deep": "data"}})),
            None,
            serde_json::json!({}),
        );

        let with_query = create_test_cohort(
            None,
            Some(serde_json::json!({"query": "SELECT * FROM events WHERE large_query_here"})),
            serde_json::json!({}),
        );

        let with_groups = create_test_cohort(
            None,
            None,
            serde_json::json!({"group1": "value1", "group2": "value2", "group3": "value3"}),
        );

        let base_size = base_cohort.estimated_size_bytes();
        let filters_size = with_filters.estimated_size_bytes();
        let query_size = with_query.estimated_size_bytes();
        let groups_size = with_groups.estimated_size_bytes();

        // Each field should contribute to the size
        assert!(
            filters_size > base_size,
            "Adding filters should increase size"
        );
        assert!(query_size > base_size, "Adding query should increase size");
        assert!(
            groups_size > base_size,
            "Adding groups should increase size"
        );
    }

    #[test]
    fn test_estimate_json_size_accuracy() {
        // Test that estimate_json_size produces reasonable approximations
        // compared to actual serialization
        let test_cases = vec![
            serde_json::json!(null),
            serde_json::json!(true),
            serde_json::json!(false),
            serde_json::json!(42),
            serde_json::json!(-123),
            serde_json::json!(1.5),
            serde_json::json!("hello"),
            serde_json::json!([1, 2, 3]),
            serde_json::json!({"key": "value"}),
            serde_json::json!({
                "nested": {
                    "array": [1, 2, {"deep": true}],
                    "string": "test"
                }
            }),
        ];

        for value in test_cases {
            let estimated = estimate_json_size(&value);
            let actual = value.to_string().len();

            // Allow up to 20% deviation - the estimate doesn't need to be exact,
            // just proportional and reasonable
            let deviation = (estimated as f64 - actual as f64).abs() / actual as f64;
            assert!(
                deviation < 0.20,
                "Estimate {estimated} deviates too much from actual {actual} for {value}"
            );
        }
    }

    #[test]
    #[allow(clippy::type_complexity)]
    fn test_uses_realtime_membership() {
        let ts = Some(Utc::now());
        let behavioral = Some(serde_json::json!({
            "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
        }));
        let person_properties_only = Some(serde_json::json!({
            "person_properties": true, "behavioral": false, "lifecycle": false, "cohorts": false
        }));

        // (cohort_type, person_ts, events_ts, calc_ts, condition_type,
        //  expected under AnyBackfillStamp, expected under EventsOrCalculationStamp)
        let cases: Vec<(
            Option<CohortType>,
            Option<DateTime<Utc>>,
            Option<DateTime<Utc>>,
            Option<DateTime<Utc>>,
            Option<Value>,
            bool,
            bool,
        )> = vec![
            (None, ts, ts, ts, behavioral.clone(), false, false),
            (
                Some(CohortType::Static),
                ts,
                ts,
                ts,
                behavioral.clone(),
                false,
                false,
            ),
            (
                Some(CohortType::PersonProperty),
                ts,
                ts,
                ts,
                behavioral.clone(),
                false,
                false,
            ),
            (
                Some(CohortType::Analytical),
                ts,
                ts,
                ts,
                behavioral.clone(),
                false,
                false,
            ),
            (
                Some(CohortType::Realtime),
                None,
                None,
                None,
                behavioral.clone(),
                false,
                false,
            ),
            (
                Some(CohortType::Realtime),
                ts,
                None,
                None,
                behavioral.clone(),
                true,
                false,
            ),
            (
                Some(CohortType::Behavioral),
                ts,
                None,
                None,
                behavioral.clone(),
                true,
                false,
            ),
            (
                Some(CohortType::Realtime),
                None,
                ts,
                None,
                behavioral.clone(),
                true,
                true,
            ),
            (
                Some(CohortType::Realtime),
                None,
                None,
                ts,
                behavioral.clone(),
                false,
                true,
            ),
            (
                Some(CohortType::Behavioral),
                None,
                None,
                ts,
                behavioral.clone(),
                false,
                false,
            ),
            // The events stamp carries a `behavioral`-typed cohort that the calculation
            // stamp above cannot.
            (
                Some(CohortType::Behavioral),
                None,
                ts,
                ts,
                behavioral.clone(),
                true,
                true,
            ),
            (
                Some(CohortType::Realtime),
                ts,
                ts,
                ts,
                behavioral.clone(),
                true,
                true,
            ),
            (
                Some(CohortType::Realtime),
                ts,
                ts,
                ts,
                person_properties_only.clone(),
                false,
                false,
            ),
            (Some(CohortType::Realtime), ts, ts, ts, None, false, false),
        ];

        for (
            cohort_type,
            person_ts,
            events_ts,
            calc_ts,
            condition_type,
            expected_any,
            expected_disambiguated,
        ) in cases
        {
            let mut cohort = create_test_cohort(None, None, serde_json::json!({}));
            cohort.cohort_type = cohort_type;
            cohort.last_backfill_person_properties_at = person_ts;
            cohort.last_backfill_events_at = events_ts;
            cohort.last_realtime_cohort_calculation_at = calc_ts;
            cohort.condition_type = condition_type.clone();
            for (policy, expected) in [
                (MembershipStampPolicy::AnyBackfillStamp, expected_any),
                (
                    MembershipStampPolicy::EventsOrCalculationStamp,
                    expected_disambiguated,
                ),
            ] {
                assert_eq!(
                    policy.uses_realtime_membership(&cohort),
                    expected,
                    "policy={policy:?}, cohort_type={cohort_type:?}, person_ts={}, events_ts={}, calc_ts={}, condition_type={condition_type:?} should return {expected}",
                    person_ts.is_some(),
                    events_ts.is_some(),
                    calc_ts.is_some()
                );
            }
        }
    }

    #[test]
    fn test_stamp_policy_divergence() {
        let ts = Some(Utc::now());
        let behavioral = Some(serde_json::json!({
            "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
        }));

        let make_cohort = |person_ts, events_ts, calc_ts, condition_type: &Option<Value>| {
            let mut cohort = create_test_cohort(None, None, serde_json::json!({}));
            cohort.cohort_type = Some(CohortType::Realtime);
            cohort.condition_type = condition_type.clone();
            cohort.last_backfill_person_properties_at = person_ts;
            cohort.last_backfill_events_at = events_ts;
            cohort.last_realtime_cohort_calculation_at = calc_ts;
            cohort
        };

        // (person_ts, events_ts, calc_ts, expected)
        let cases = [
            (ts, None, None, Some(StampPolicyDivergence::WouldLose)),
            (None, None, ts, Some(StampPolicyDivergence::WouldGain)),
            // A stamp both policies accept masks the person stamp.
            (ts, ts, None, None),
            (ts, None, ts, None),
            (None, None, None, None),
        ];
        for (person_ts, events_ts, calc_ts, expected) in cases {
            let cohort = make_cohort(person_ts, events_ts, calc_ts, &behavioral);
            assert_eq!(
                MembershipStampPolicy::divergence(&cohort),
                expected,
                "person_ts={}, events_ts={}, calc_ts={}",
                person_ts.is_some(),
                events_ts.is_some(),
                calc_ts.is_some()
            );
        }

        // A cohort neither policy routes cannot diverge, whatever its stamps say.
        let unrouted = make_cohort(ts, None, None, &None);
        assert_eq!(MembershipStampPolicy::divergence(&unrouted), None);

        assert_eq!(StampPolicyDivergence::WouldLose.as_label(), "would_lose");
        assert_eq!(StampPolicyDivergence::WouldGain.as_label(), "would_gain");
    }

    #[test]
    fn test_membership_stamp_policy_from_str() {
        let valid = [
            (
                "any_backfill_stamp",
                MembershipStampPolicy::AnyBackfillStamp,
            ),
            (
                "any-backfill-stamp",
                MembershipStampPolicy::AnyBackfillStamp,
            ),
            (
                " Any_Backfill_Stamp ",
                MembershipStampPolicy::AnyBackfillStamp,
            ),
            (
                "events_or_calculation_stamp",
                MembershipStampPolicy::EventsOrCalculationStamp,
            ),
            (
                "events-or-calculation-stamp",
                MembershipStampPolicy::EventsOrCalculationStamp,
            ),
        ];
        for (input, expected) in valid {
            assert_eq!(
                input.parse::<MembershipStampPolicy>().unwrap(),
                expected,
                "{input}"
            );
        }

        let err = "person_stamp".parse::<MembershipStampPolicy>().unwrap_err();
        assert!(
            err.contains("any_backfill_stamp") && err.contains("events_or_calculation_stamp"),
            "error must name the valid values: {err}"
        );

        // The metric label reuses the env spellings, so a dashboard query written against
        // one reads the other.
        for policy in [
            MembershipStampPolicy::AnyBackfillStamp,
            MembershipStampPolicy::EventsOrCalculationStamp,
        ] {
            assert_eq!(
                policy.as_label().parse::<MembershipStampPolicy>().unwrap(),
                policy
            );
        }
    }

    #[test]
    fn test_realtime_cohort_filtering_mirrors_flag_matching() {
        // Mirrors the filter flag_matching::prepare_flag_evaluation_state applies.
        let backfill_ts = Some(Utc::now());
        let behavioral = Some(serde_json::json!({
            "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
        }));
        let person_properties_only = Some(serde_json::json!({
            "person_properties": true, "behavioral": false, "lifecycle": false, "cohorts": false
        }));

        let make_cohort = |id: i32,
                           cohort_type: Option<CohortType>,
                           ts: Option<DateTime<Utc>>,
                           condition_type: Option<Value>| {
            let mut c = create_test_cohort(None, None, serde_json::json!({}));
            c.id = id;
            c.cohort_type = cohort_type;
            c.last_backfill_person_properties_at = ts;
            c.condition_type = condition_type;
            c
        };

        let cohorts = [
            make_cohort(1, Some(CohortType::Static), None, None),
            make_cohort(
                2,
                Some(CohortType::PersonProperty),
                backfill_ts,
                person_properties_only.clone(),
            ),
            make_cohort(3, Some(CohortType::Realtime), None, behavioral.clone()), // no backfill
            make_cohort(
                4,
                Some(CohortType::Realtime),
                backfill_ts,
                behavioral.clone(),
            ), // should be selected
            make_cohort(5, Some(CohortType::Behavioral), None, behavioral.clone()), // no backfill
            make_cohort(
                6,
                Some(CohortType::Behavioral),
                backfill_ts,
                behavioral.clone(),
            ), // should be selected
            make_cohort(
                7,
                Some(CohortType::Analytical),
                backfill_ts,
                behavioral.clone(),
            ),
            make_cohort(8, None, backfill_ts, behavioral.clone()),
            // Realtime + backfilled but person-properties-only: never selected
            make_cohort(
                9,
                Some(CohortType::Realtime),
                backfill_ts,
                person_properties_only.clone(),
            ),
        ];

        let realtime_ids: Vec<i32> = cohorts
            .iter()
            .filter(|c| MembershipStampPolicy::default().uses_realtime_membership(c))
            .map(|c| c.id)
            .collect();

        assert_eq!(realtime_ids, vec![4, 6]);
    }

    #[test]
    fn test_estimate_json_size_minimal_allocation() {
        // This test verifies the function works correctly. The "minimal allocation" property
        // is structural (only numbers allocate via to_string()) rather than something we can directly test.
        let large_value = serde_json::json!({
            "properties": {
                "type": "OR",
                "values": (0..100).map(|i| {
                    serde_json::json!({
                        "key": format!("property_{}", i),
                        "value": format!("value_{}", i)
                    })
                }).collect::<Vec<_>>()
            }
        });

        let size = estimate_json_size(&large_value);
        assert!(
            size > 1000,
            "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)]
mod skip_serializing_if_tests {
    //! Verify the `skip_serializing_if = "Option::is_none"` sweep on `Cohort`.
    //! For every swept `Option<T>` field, absent input must round-trip as absent
    //! (no fabricated `null` key on cache-write serialize), and a real value must
    //! round-trip unchanged. See
    //! plans/rust-flag-models-skip-serializing-if-sweep.md.
    use super::*;

    fn assert_absent(value: &serde_json::Value, key: &str) {
        let map = value
            .as_object()
            .expect("serialized cohort should be an object");
        assert!(
            !map.contains_key(key),
            "absent field `{key}` must not be promoted to a null key on serialize"
        );
    }

    /// Minimal cohort with every swept Option field at `None`.
    fn minimal_cohort() -> Cohort {
        Cohort {
            id: 1,
            team_id: 1,
            groups: serde_json::json!({}),
            ..Default::default()
        }
    }

    #[test]
    fn cohort_absent_options_stay_absent() {
        let output = serde_json::to_value(minimal_cohort()).unwrap();
        for key in [
            "name",
            "description",
            "filters",
            "query",
            "version",
            "pending_version",
            "count",
            "created_by_id",
            "cohort_type",
            "last_backfill_person_properties_at",
            "condition_type",
            "last_realtime_cohort_calculation_at",
        ] {
            assert_absent(&output, key);
        }
    }

    #[test]
    fn cohort_values_round_trip() {
        let cohort = Cohort {
            id: 1,
            name: Some("QA".to_string()),
            description: Some("desc".to_string()),
            team_id: 1,
            filters: Some(serde_json::json!({"k": "v"})),
            query: Some(serde_json::json!({"q": 1})),
            version: Some(2),
            pending_version: Some(3),
            count: Some(7),
            created_by_id: Some(9),
            cohort_type: Some(CohortType::Behavioral),
            last_backfill_person_properties_at: Some(Utc::now()),
            last_realtime_cohort_calculation_at: Some(Utc::now()),
            condition_type: Some(serde_json::json!({
                "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
            })),
            groups: serde_json::json!({}),
            ..Default::default()
        };
        let output = serde_json::to_value(&cohort).unwrap();
        assert_eq!(output["name"], "QA");
        assert_eq!(output["description"], "desc");
        assert_eq!(output["filters"]["k"], "v");
        assert_eq!(output["query"]["q"], 1);
        assert_eq!(output["version"], 2);
        assert_eq!(output["pending_version"], 3);
        assert_eq!(output["count"], 7);
        assert_eq!(output["created_by_id"], 9);
        assert_eq!(output["cohort_type"], "behavioral");
        assert!(output["last_backfill_person_properties_at"].is_string());
        assert!(output["last_realtime_cohort_calculation_at"].is_string());
        assert_eq!(output["condition_type"]["behavioral"], true);
    }
}