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): only use cohort_membership for behavioral cohorts (#70554)

Gustavo H. Strassburger2934adf2ccfa
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index dbc276a9e0d8..c43905b20ccf 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -556,6 +556,27 @@ class CohortFiltersField(serializers.JSONField):
pass
+class CohortConditionTypeFlags(BaseModel, extra="forbid"):
+ person_properties: bool = Field(description="The filters include a person property or person_metadata condition.")
+ behavioral: bool = Field(
+ description="The filters include a behavioral condition that is not lifecycle-style "
+ "(e.g. performed_event, performed_event_multiple, performed_event_sequence, or their "
+ "negations)."
+ )
+ lifecycle: bool = Field(
+ description="The filters include a lifecycle-style behavioral condition (first-seen/regularly/"
+ "stopped/restarted performing an event)."
+ )
+ cohorts: bool = Field(description="The filters include a nested reference to another cohort.")
+
+
+@extend_schema_field(CohortConditionTypeFlags) # type: ignore[arg-type]
+class CohortConditionTypeField(serializers.JSONField):
+ """Custom JSONField that exposes proper OpenAPI schema for condition_type flags."""
+
+ pass
+
+
class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
earliest_timestamp_func = earliest_timestamp_func
@@ -567,6 +588,14 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
# Explicit filters field with proper OpenAPI schema
filters = CohortFiltersField(required=False, allow_null=True)
+ # Explicit condition_type field with proper OpenAPI schema
+ condition_type = CohortConditionTypeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Flags describing which kinds of conditions the cohort's filters contain. "
+ "Null when the cohort has no filters to classify.",
+ )
+
# If this cohort is an exposure cohort for an experiment
experiment_set: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField(many=True, read_only=True) # ty: ignore[invalid-assignment]
last_error_message = serializers.SerializerMethodField()
@@ -593,6 +622,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"count",
"is_static",
"cohort_type",
+ "condition_type",
"experiment_set",
"search_match_type",
"_create_in_folder",
@@ -611,6 +641,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"last_error_message",
"count",
"experiment_set",
+ "condition_type",
]
def __init__(self, *args: Any, **kwargs: Any) -> None:
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 07e87d23946b..5799b6978f12 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -6412,6 +6412,15 @@ class TestCohortTypeIntegration(APIBaseTest):
# cohort_type is auto-computed for realtime-capable filters
self.assertEqual(cohort.cohort_type, "realtime")
self.assertEqual(response.data["cohort_type"], "realtime")
+ # condition_type is auto-computed from the filter shape, independent of realtime eligibility
+ expected_condition_type = {
+ "person_properties": True,
+ "behavioral": False,
+ "lifecycle": False,
+ "cohorts": False,
+ }
+ self.assertEqual(cohort.condition_type, expected_condition_type)
+ self.assertEqual(response.data["condition_type"], expected_condition_type)
def test_person_metadata_cohort_not_classified_realtime(self):
"""person_metadata cohorts must route to the non-realtime path: the realtime
@@ -6444,8 +6453,10 @@ class TestCohortTypeIntegration(APIBaseTest):
self.assertNotEqual(cohort.cohort_type, CohortType.REALTIME)
def test_api_response_includes_cohort_type(self):
- """API responses should include the cohort_type field"""
+ """API responses should include the cohort_type and condition_type fields"""
+ # condition_type is intentionally not passed here: it's derived from filters on
+ # save (even for a direct ORM create, not just through the API serializer).
cohort = Cohort.objects.create(
team=self.team,
name="Test Cohort",
@@ -6479,6 +6490,14 @@ class TestCohortTypeIntegration(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertIn("cohort_type", response.data)
self.assertEqual(response.data["cohort_type"], CohortType.BEHAVIORAL)
+ self.assertIn("condition_type", response.data)
+ expected_condition_type = {
+ "person_properties": False,
+ "behavioral": True,
+ "lifecycle": False,
+ "cohorts": False,
+ }
+ self.assertEqual(response.data["condition_type"], expected_condition_type)
# Test LIST request
response = self.client.get(f"/api/projects/{self.team.id}/cohorts/")
@@ -6488,6 +6507,8 @@ class TestCohortTypeIntegration(APIBaseTest):
cohort_data = next(c for c in response.data["results"] if c["id"] == cohort.id)
self.assertIn("cohort_type", cohort_data)
self.assertEqual(cohort_data["cohort_type"], CohortType.BEHAVIORAL)
+ self.assertIn("condition_type", cohort_data)
+ self.assertEqual(cohort_data["condition_type"], expected_condition_type)
def test_explicit_cohort_type_validation_success(self):
"""Should accept valid explicit cohort types"""
diff --git a/posthog/dags/backfill_internal_test_users_cohort.py b/posthog/dags/backfill_internal_test_users_cohort.py
index f56f4737290b..643af28c7843 100644
--- a/posthog/dags/backfill_internal_test_users_cohort.py
+++ b/posthog/dags/backfill_internal_test_users_cohort.py
@@ -53,6 +53,9 @@ def create_internal_test_users_cohorts_op(
# No race condition: the INTERNAL_TEST_USERS kind can only be set by this
# backfill (or get_or_create_internal_test_users_cohort), not by users
# through the UI, so no concurrent creation can happen.
+ # bulk_create bypasses Cohort.save(), so condition_type must be set explicitly here
+ # rather than relying on the save()-time derivation.
+ condition_type = Cohort.compute_condition_type(_INTERNAL_TEST_USERS_FILTERS)
cohorts_to_create = [
Cohort(
team=team,
@@ -61,6 +64,7 @@ def create_internal_test_users_cohorts_op(
is_static=False,
kind=CohortKind.INTERNAL_TEST_USERS,
filters=_INTERNAL_TEST_USERS_FILTERS,
+ condition_type=condition_type,
)
for team in teams_needing_cohort
]
diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.py
index 2983936e1e29..bbcfa7cd9cfc 100644
--- a/posthog/management/commands/resave_cohorts.py
+++ b/posthog/management/commands/resave_cohorts.py
@@ -16,7 +16,7 @@ logger = structlog.get_logger(__name__)
class Command(BaseCommand):
- help = "Regenerate inline bytecode (in filters) and cohort_type for cohorts."
+ help = "Regenerate inline bytecode (in filters), cohort_type, and condition_type for cohorts."
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
@@ -226,12 +226,19 @@ class Command(BaseCommand):
computed_type = None
break
+ computed_condition_type = Cohort.compute_condition_type(clean_filters)
+
# Decide if there is any change worth persisting/reporting
- will_change = clean_filters != cohort.filters or computed_type != cohort.cohort_type
+ will_change = (
+ clean_filters != cohort.filters
+ or computed_type != cohort.cohort_type
+ or computed_condition_type != cohort.condition_type
+ )
# ALWAYS update in-memory for dependency checking
cohort.filters = clean_filters
cohort.cohort_type = computed_type
+ cohort.condition_type = computed_condition_type
# Track summary stats
if computed_type == "realtime":
@@ -243,7 +250,7 @@ class Command(BaseCommand):
# Persist changes to database if needed
if will_change:
- cohort.save(update_fields=["filters", "cohort_type"])
+ cohort.save(update_fields=["filters", "cohort_type", "condition_type"])
changed += 1
except Exception as err:
errors += 1
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 2fb7b3dfa5a4..0bd46a0640d6 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -149,6 +149,7 @@
# name: TestVisitorFieldSnapshots.test_primitive_fields_Cohort
list([
'cohort_type',
+ 'condition_type',
'created_at',
'deleted',
'description',
@@ -490,6 +491,8 @@
'__repr__',
'__static_attributes__',
'__str__',
+ '_filter_leaves',
+ '_filters_contain_type',
'_get_existing_ch_member_uuids',
'_get_uuids_for_emails_batch_ch',
'_has_filter_type',
@@ -506,6 +509,7 @@
'calculate_people_ch',
'cohortcalculationhistory_set',
'cohortpeople_set',
+ 'compute_condition_type',
'count',
'created_by_id',
'enqueue_calculation',
diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.py
index 37a947f99ce8..75b803de8f6d 100644
--- a/posthog/test/test_cohort_model.py
+++ b/posthog/test/test_cohort_model.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
import pytest
from posthog.test.base import BaseTest
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from celery.exceptions import SoftTimeLimitExceeded
from parameterized import parameterized
@@ -15,7 +15,7 @@ from posthog.models import Person, Team
from posthog.models.person.util import get_person_by_id
from posthog.test.persons import add_cohort_members, create_person
-from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.cohort import Cohort, CohortConditionFlags, CohortType
from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID
from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
@@ -666,6 +666,61 @@ _COHORT_REF_FILTERS = {
}
}
+_PERSON_METADATA_FILTERS = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "AND", "values": [{"key": "created_at", "value": "2024-01-01", "type": "person_metadata"}]}
+ ],
+ }
+}
+
+_PERSON_METADATA_AND_BEHAVIORAL_FILTERS = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "AND", "values": [{"key": "created_at", "value": "2024-01-01", "type": "person_metadata"}]},
+ {
+ "type": "AND",
+ "values": [
+ {"type": "behavioral", "value": "performed_event", "event_type": "events", "key": "$pageview"}
+ ],
+ },
+ ],
+ }
+}
+
+_LIFECYCLE_FILTERS = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "value": "performed_event_first_time",
+ "event_type": "events",
+ "key": "$pageview",
+ }
+ ],
+ }
+ ],
+ }
+}
+
+
+def _condition_flags(
+ *, person_properties: bool = False, behavioral: bool = False, lifecycle: bool = False, cohorts: bool = False
+) -> CohortConditionFlags:
+ return {
+ "person_properties": person_properties,
+ "behavioral": behavioral,
+ "lifecycle": lifecycle,
+ "cohorts": cohorts,
+ }
+
+
_FIXED_TS = datetime(2026, 1, 1, tzinfo=UTC)
@@ -705,6 +760,32 @@ class TestCohortIsFlagCompatible(BaseTest):
("realtime_empty_filters_no_ts", CohortType.REALTIME, {}, None, None, False),
("realtime_empty_filters_with_ts", CohortType.REALTIME, {}, _FIXED_TS, _FIXED_TS, False),
("realtime_cohort_ref_with_ts", CohortType.REALTIME, _COHORT_REF_FILTERS, _FIXED_TS, _FIXED_TS, False),
+ # Realtime + person_metadata filters: gate on person timestamp, same as plain person filters
+ ("realtime_person_metadata_no_ts", CohortType.REALTIME, _PERSON_METADATA_FILTERS, None, None, False),
+ (
+ "realtime_person_metadata_only_person_ts",
+ CohortType.REALTIME,
+ _PERSON_METADATA_FILTERS,
+ _FIXED_TS,
+ None,
+ True,
+ ),
+ (
+ "realtime_person_metadata_and_behavioral_only_events_ts",
+ CohortType.REALTIME,
+ _PERSON_METADATA_AND_BEHAVIORAL_FILTERS,
+ None,
+ _FIXED_TS,
+ False,
+ ),
+ (
+ "realtime_person_metadata_and_behavioral_both_ts",
+ CohortType.REALTIME,
+ _PERSON_METADATA_AND_BEHAVIORAL_FILTERS,
+ _FIXED_TS,
+ _FIXED_TS,
+ True,
+ ),
]
)
def test_is_flag_compatible(self, _label, cohort_type, filters, person_ts, events_ts, expected):
@@ -716,3 +797,69 @@ class TestCohortIsFlagCompatible(BaseTest):
last_backfill_events_at=events_ts,
)
self.assertEqual(cohort.is_flag_compatible, expected)
+
+
+class TestCohortComputeConditionType(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("person_only", _PERSON_FILTERS, _condition_flags(person_properties=True)),
+ ("behavioral_only", _BEHAVIORAL_FILTERS, _condition_flags(behavioral=True)),
+ ("mixed", _MIXED_FILTERS, _condition_flags(person_properties=True, behavioral=True)),
+ ("cohort_reference_only", _COHORT_REF_FILTERS, _condition_flags(cohorts=True)),
+ ("empty_filters", {}, None),
+ ("none_filters", None, None),
+ # person_metadata reads a top-level persons-table column rather than the
+ # properties JSON blob, but it's still a property-style (non-behavioral) condition.
+ ("person_metadata_only", _PERSON_METADATA_FILTERS, _condition_flags(person_properties=True)),
+ (
+ "person_metadata_and_behavioral",
+ _PERSON_METADATA_AND_BEHAVIORAL_FILTERS,
+ _condition_flags(person_properties=True, behavioral=True),
+ ),
+ # Lifecycle-style behavioral values (first-seen/regularly/stopped/restarted) are
+ # distinct from plain event-count behavioral filters.
+ ("lifecycle_only", _LIFECYCLE_FILTERS, _condition_flags(lifecycle=True)),
+ ]
+ )
+ def test_compute_condition_type(self, _label, filters, expected):
+ self.assertEqual(Cohort.compute_condition_type(filters), expected)
+
+
+class TestCohortConditionTypeDerivedOnSave(BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ # A cohort created without going through the API serializer (e.g. a management
+ # command or get_or_create_internal_test_users_cohort) must still get classified.
+ def test_direct_orm_create_derives_condition_type(self):
+ cohort = Cohort.objects.create(team=self.team, filters=_PERSON_FILTERS)
+ self.assertEqual(cohort.condition_type, _condition_flags(person_properties=True))
+
+ # Static cohorts skip cohort_type/realtime computation, but condition_type
+ # classifies filter shape independent of that, so it must still be set.
+ def test_static_cohort_with_filters_derives_condition_type(self):
+ cohort = Cohort.objects.create(team=self.team, is_static=True, filters=_BEHAVIORAL_FILTERS)
+ self.assertEqual(cohort.condition_type, _condition_flags(behavioral=True))
+
+ # Saves that don't touch filters (e.g. toggling is_calculating) must not
+ # recompute or drop condition_type.
+ def test_narrow_update_fields_save_does_not_touch_condition_type(self):
+ cohort = Cohort.objects.create(team=self.team, filters=_PERSON_FILTERS)
+ self.assertEqual(cohort.condition_type, _condition_flags(person_properties=True))
+
+ cohort.is_calculating = True
+ cohort.save(update_fields=["is_calculating"])
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.condition_type, _condition_flags(person_properties=True))
+
+ # A save that updates filters must recompute condition_type even when the caller also
+ # (redundantly) lists "condition_type" in update_fields with a stale value — the presence
+ # of "condition_type" in update_fields must not short-circuit recomputation.
+ def test_update_fields_with_both_filters_and_stale_condition_type_still_recomputes(self):
+ cohort = Cohort.objects.create(team=self.team, filters=_PERSON_FILTERS)
+ self.assertEqual(cohort.condition_type, _condition_flags(person_properties=True))
+
+ cohort.filters = _BEHAVIORAL_FILTERS
+ cohort.condition_type = _condition_flags(person_properties=True) # stale value
+ cohort.save(update_fields=["filters", "condition_type"])
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.condition_type, _condition_flags(behavioral=True))
diff --git a/products/cohorts/backend/migrations/0005_cohort_condition_type.py b/products/cohorts/backend/migrations/0005_cohort_condition_type.py
new file mode 100644
index 000000000000..d8058f65ab1a
--- /dev/null
+++ b/products/cohorts/backend/migrations/0005_cohort_condition_type.py
@@ -0,0 +1,31 @@
+"""No backfill: existing rows keep condition_type = NULL until they're next saved (or resaved
+via the resave_cohorts management command), which the Rust realtime-membership gate treats as
+"no behavioral condition" (safe default, falls back to legacy dynamic evaluation). Before
+allowlisting a team in REALTIME_COHORT_EVALUATION_TEAM_IDS, run
+`python manage.py resave_cohorts --team-id <id>` so its already-backfilled behavioral cohorts
+get classified and keep using the realtime cohort_membership path."""
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("cohorts", "0004_cohort_backfill_tables"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="cohort",
+ name="condition_type",
+ field=models.JSONField(
+ blank=True,
+ help_text=(
+ "Flags describing which kinds of conditions the cohort's filters contain: "
+ "person_properties (property or person_metadata), behavioral, lifecycle "
+ "(first-seen/regularly/stopped/restarted performing an event), and cohorts "
+ "(nested cohort references). Null when the cohort has no filters to classify."
+ ),
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
index da7555feff07..e603134fd06f 100644
--- a/products/cohorts/backend/migrations/max_migration.txt
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_cohort_backfill_tables
+0005_cohort_condition_type
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 8e9bf9974440..953bb7f95968 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -3,7 +3,7 @@ import time
from collections.abc import Callable, Iterable
from datetime import datetime
from enum import StrEnum
-from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union, cast
from uuid import UUID
from django.conf import settings
@@ -54,6 +54,30 @@ class CohortType(StrEnum):
ANALYTICAL = "analytical"
+class CohortConditionFlags(TypedDict):
+ """Boolean flags describing which kinds of leaf conditions a cohort's filters contain,
+ independent of `CohortType` (which is about realtime-evaluation eligibility, not filter shape)."""
+
+ person_properties: bool
+ behavioral: bool
+ lifecycle: bool
+ cohorts: bool
+
+
+# Behavioral filter `value`s that represent lifecycle-style conditions (new/returning/dormant/
+# resurrecting), matching the frontend's "Lifecycle" cohort filter section (BehavioralLifecycleType
+# in frontend/src/types.ts) — distinct from plain event-count behavioral filters (performed_event,
+# performed_event_multiple, performed_event_sequence).
+LIFECYCLE_BEHAVIORAL_VALUES = frozenset(
+ {
+ "performed_event_first_time",
+ "performed_event_regularly",
+ "stopped_performing_event",
+ "restarted_performing_event",
+ }
+)
+
+
# The empty string literal helps us determine when the cohort is invalid/deleted, when
# set in cohorts_cache
CohortOrEmpty = Union["Cohort", Literal[""], None]
@@ -226,6 +250,15 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
help_text="Type of cohort based on filter complexity",
)
+ condition_type = models.JSONField(
+ null=True,
+ blank=True,
+ help_text="Flags describing which kinds of conditions the cohort's filters contain: "
+ "person_properties (property or person_metadata), behavioral, lifecycle (first-seen/regularly/"
+ "stopped/restarted performing an event), and cohorts (nested cohort references). Null when the "
+ "cohort has no filters to classify.",
+ )
+
# deprecated in favor of filters
groups = models.JSONField(default=list)
@@ -251,10 +284,20 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
return self.name or "Untitled cohort"
def save(self, *args: Any, **kwargs: Any) -> None:
+ """Keep `condition_type` derived from `filters` on every save, so any creation path
+ (the cohorts API, management commands, or a direct `Cohort.objects.create(...)`)
+ ends up with a consistent classification, not just the API serializer's flow."""
# update_fields can arrive positionally (4th positional, after force_insert/force_update/using)
# or as a keyword. Intercept it so _maintain_behavioral_shape can extend the frozen set.
- positional_update_fields = args[3] if len(args) > 3 else kwargs.get("update_fields")
- maintained_update_fields = self._maintain_behavioral_shape(positional_update_fields)
+ update_fields = args[3] if len(args) > 3 else kwargs.get("update_fields")
+ if update_fields is None:
+ self.condition_type = Cohort.compute_condition_type(self.filters)
+ elif "filters" in update_fields:
+ self.condition_type = Cohort.compute_condition_type(self.filters)
+ if "condition_type" not in update_fields:
+ update_fields = [*update_fields, "condition_type"]
+
+ maintained_update_fields = self._maintain_behavioral_shape(update_fields)
if len(args) > 3:
args = (*args[:3], maintained_update_fields, *args[4:])
else:
@@ -344,30 +387,75 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
should_delete=self.deleted,
)
- def _has_filter_type(self, filter_type: str) -> bool:
- """Check whether the cohort's filter tree contains any leaf node of the given type."""
- if not self.filters:
- return False
- properties = self.filters.get("properties")
+ @staticmethod
+ def _filter_leaves(filters: Optional[dict]) -> list[dict]:
+ """Flatten a cohort filters dict into its leaf filter nodes, expanding AND/OR groups."""
+ if not filters:
+ return []
+ properties = filters.get("properties")
if not properties:
- return False
+ return []
- def _check(node) -> bool:
+ leaves: list[dict] = []
+
+ def _walk(node: Any) -> None:
if not isinstance(node, dict):
- return False
+ return
node_type = node.get("type")
if node_type in ("AND", "OR"):
- return any(_check(child) for child in node.get("values", []))
- return node_type == filter_type
+ for child in node.get("values", []):
+ _walk(child)
+ else:
+ leaves.append(node)
+
+ _walk(properties)
+ return leaves
+
+ @staticmethod
+ def _filters_contain_type(filters: Optional[dict], filter_type: str) -> bool:
+ """Check whether a cohort filters dict contains any leaf node of the given type."""
+ return any(leaf.get("type") == filter_type for leaf in Cohort._filter_leaves(filters))
+
+ def _has_filter_type(self, filter_type: str) -> bool:
+ """Check whether the cohort's filter tree contains any leaf node of the given type."""
+ return Cohort._filters_contain_type(self.filters, filter_type)
+
+ @staticmethod
+ def compute_condition_type(filters: Optional[dict]) -> Optional[CohortConditionFlags]:
+ """Classify a cohort's filters by which kinds of leaf conditions they contain.
- return _check(properties)
+ `person` and `person_metadata` are both property-style conditions (the latter reads
+ top-level persons-table columns instead of the properties JSON blob, but is not
+ behavioral), so either sets the `person_properties` flag. Behavioral filters split into
+ `lifecycle` (first-seen/regularly/stopped/restarted performing an event, matching the
+ frontend's "Lifecycle" cohort filter section) and `behavioral` for everything else
+ (performed_event, performed_event_multiple, performed_event_sequence, and their
+ negations). `cohorts` flags nested cohort references.
+
+ Returns None when the filters have no leaf conditions to classify (e.g. empty filters).
+ """
+ leaves = Cohort._filter_leaves(filters)
+ if not leaves:
+ return None
+
+ return {
+ "person_properties": any(leaf.get("type") in ("person", "person_metadata") for leaf in leaves),
+ "behavioral": any(
+ leaf.get("type") == "behavioral" and leaf.get("value") not in LIFECYCLE_BEHAVIORAL_VALUES
+ for leaf in leaves
+ ),
+ "lifecycle": any(
+ leaf.get("type") == "behavioral" and leaf.get("value") in LIFECYCLE_BEHAVIORAL_VALUES for leaf in leaves
+ ),
+ "cohorts": any(leaf.get("type") == "cohort" for leaf in leaves),
+ }
@property
def is_flag_compatible(self) -> bool:
"""Whether this cohort can be used in feature flag targeting via cohort_membership lookups.
Gates on both person property and event backfills based on which filter types the cohort uses:
- - Cohorts with person property filters require last_backfill_person_properties_at
+ - Cohorts with person property or person_metadata filters require last_backfill_person_properties_at
- Cohorts with behavioral event filters require last_backfill_events_at
- Cohorts with both require both timestamps
- Cohorts with neither recognized filter type (empty filters, cohort-reference-only, etc.)
@@ -377,7 +465,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
if self.cohort_type != CohortType.REALTIME:
return False
- has_person_filters = self._has_filter_type("person")
+ has_person_filters = self._has_filter_type("person") or self._has_filter_type("person_metadata")
has_behavioral_filters = self._has_filter_type("behavioral")
if not (has_person_filters or has_behavioral_filters):
@@ -969,6 +1057,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
"groups": self.groups,
"is_static": self.is_static,
"cohort_type": self.cohort_type,
+ "condition_type": self.condition_type,
"created_by_id": self.created_by_id,
"created_at": self.created_at.isoformat() if self.created_at else None,
"last_error_at": self.last_error_at.isoformat() if self.last_error_at else None,
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 570ede2220ba..cad3d92e573f 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -178,6 +178,17 @@ export const CohortTypeEnumApi = {
Analytical: 'analytical',
} as const
+export interface CohortConditionTypeFlagsApi {
+ /** The filters include a person property or person_metadata condition. */
+ person_properties: boolean
+ /** The filters include a behavioral condition that is not lifecycle-style (e.g. performed_event, performed_event_multiple, performed_event_sequence, or their negations). */
+ behavioral: boolean
+ /** The filters include a lifecycle-style behavioral condition (first-seen/regularly/stopped/restarted performing an event). */
+ lifecycle: boolean
+ /** The filters include a nested reference to another cohort. */
+ cohorts: boolean
+}
+
export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]
export const SearchMatchTypeEnumApi = {
@@ -224,6 +235,8 @@ export interface CohortApi {
* * `realtime` - realtime
* * `analytical` - analytical */
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
+ /** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
+ readonly condition_type: CohortConditionTypeFlagsApi | null
readonly experiment_set: readonly number[]
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnumApi | null
@@ -279,6 +292,8 @@ export interface PatchedCohortApi {
* * `realtime` - realtime
* * `analytical` - analytical */
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
+ /** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
+ readonly condition_type?: CohortConditionTypeFlagsApi | null
readonly experiment_set?: readonly number[]
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnumApi | null
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 7ea5278749f6..780adb48b4f3 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -771,6 +771,7 @@
"posthog_cohort"."is_static",
"posthog_cohort"."kind",
"posthog_cohort"."cohort_type",
+ "posthog_cohort"."condition_type",
"posthog_cohort"."groups"
FROM "posthog_cohort"
INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")
@@ -1143,6 +1144,7 @@
"posthog_cohort"."is_static",
"posthog_cohort"."kind",
"posthog_cohort"."cohort_type",
+ "posthog_cohort"."condition_type",
"posthog_cohort"."groups"
FROM "posthog_cohort"
WHERE "posthog_cohort"."id" = 99999
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index f2c822cace56..04cac3808543 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -230,6 +230,7 @@ def _serialize_cohort(cohort: Cohort) -> dict[str, Any]:
"groups": cohort.groups,
"created_by_id": cohort.created_by_id,
"cohort_type": cohort.cohort_type,
+ "condition_type": cohort.condition_type,
"last_backfill_person_properties_at": (
cohort.last_backfill_person_properties_at.isoformat() if cohort.last_backfill_person_properties_at else None
),
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index b8150c97d720..2b03835a73e4 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -3622,7 +3622,7 @@ class TestSerializeCohort(BaseTest):
)
result = _serialize_cohort(cohort)
- # Hypercache/service cohort schema: these 18 fields must always be present in the serialized payload
+ # Hypercache/service cohort schema: these 19 fields must always be present in the serialized payload
expected_fields = {
"id",
"name",
@@ -3640,6 +3640,7 @@ class TestSerializeCohort(BaseTest):
"groups",
"created_by_id",
"cohort_type",
+ "condition_type",
"last_backfill_person_properties_at",
"last_backfill_events_at",
}
diff --git a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
index 04f84e540fab..ecc40b045a36 100644
--- a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
+++ b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs
@@ -271,6 +271,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
}
}
@@ -767,6 +768,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
cohort_cache.cache.insert(1, vec![test_cohort]).await;
// Moka caches update internal stats lazily - sync ensures stats are current
@@ -1134,6 +1136,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
}])
}
}
diff --git a/rust/feature-flags/src/cohorts/cohort_models.rs b/rust/feature-flags/src/cohorts/cohort_models.rs
index caa044ec573a..0f88ba8ea02a 100644
--- a/rust/feature-flags/src/cohorts/cohort_models.rs
+++ b/rust/feature-flags/src/cohorts/cohort_models.rs
@@ -2,6 +2,7 @@ use crate::properties::property_models::PropertyFilter;
use crate::utils::json_size::estimate_json_size;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
+use serde_json::Value;
use sqlx::FromRow;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
@@ -50,14 +51,24 @@ pub struct Cohort {
pub last_backfill_person_properties_at: Option<DateTime<Utc>>,
#[serde(default)]
pub last_backfill_events_at: Option<DateTime<Utc>>,
+ /// Flags describing which kinds of conditions the cohort's filters contain — see
+ /// `CohortConditionFlags` in products/cohorts/backend/models/cohort.py. Used to gate
+ /// `uses_realtime_membership()` on cohorts with a `behavioral`/`lifecycle` condition,
+ /// not just any Realtime/Behavioral `cohort_type`. `#[serde(default)]` so hypercache
+ /// entries written before this field existed deserialize as `None` (safe default).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub condition_type: Option<Value>,
}
impl Cohort {
/// Returns true if this cohort's membership should be resolved via the
/// realtime cohort_membership table rather than the static cohortpeople table.
- /// Requires both a realtime/behavioral cohort type AND at least one populated
- /// backfill timestamp, which indicates that the membership table has been written to.
- /// Without any timestamp, the cohort falls through to dynamic filter evaluation.
+ /// Requires a realtime/behavioral cohort type, at least one populated backfill
+ /// timestamp (indicating the membership table has been written to), AND at least
+ /// one behavioral/lifecycle leaf condition. Cohorts made up only of person
+ /// properties never use the membership table, even when otherwise eligible —
+ /// there's no realtime signal to gain from it, so they fall through to dynamic
+ /// filter evaluation like any other property-only cohort.
///
/// Note: Python's `Cohort.is_flag_compatible` gates on filter composition (person vs
/// behavioral) and requires the matching timestamp(s) before a flag can reference the
@@ -69,6 +80,29 @@ impl Cohort {
Some(CohortType::Realtime) | Some(CohortType::Behavioral)
) && (self.last_backfill_person_properties_at.is_some()
|| self.last_backfill_events_at.is_some())
+ && self.has_behavioral_condition()
+ }
+
+ /// 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.
+ 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.
@@ -193,6 +227,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
}
}
@@ -321,44 +356,151 @@ mod tests {
#[allow(clippy::type_complexity)]
fn test_uses_realtime_membership() {
let backfill_ts = Some(Utc::now());
-
- // (cohort_type, person_props_ts, events_ts, expected)
+ 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_props_ts, events_ts, condition_type, expected)
let cases: Vec<(
Option<CohortType>,
Option<DateTime<Utc>>,
Option<DateTime<Utc>>,
+ Option<Value>,
bool,
)> = vec![
- (None, None, None, false),
- (None, backfill_ts, None, false),
- (None, None, backfill_ts, false),
- (Some(CohortType::Static), None, None, false),
- (Some(CohortType::Static), backfill_ts, None, false),
- (Some(CohortType::PersonProperty), None, None, false),
- (Some(CohortType::PersonProperty), backfill_ts, None, false),
- (Some(CohortType::Analytical), None, None, false),
- (Some(CohortType::Analytical), backfill_ts, None, false),
- // Realtime: either timestamp enables realtime membership
- (Some(CohortType::Realtime), None, None, false),
- (Some(CohortType::Realtime), backfill_ts, None, true),
- (Some(CohortType::Realtime), None, backfill_ts, true),
- (Some(CohortType::Realtime), backfill_ts, backfill_ts, true),
- // Behavioral: either timestamp enables realtime membership
- (Some(CohortType::Behavioral), None, None, false),
- (Some(CohortType::Behavioral), backfill_ts, None, true),
- (Some(CohortType::Behavioral), None, backfill_ts, true),
- (Some(CohortType::Behavioral), backfill_ts, backfill_ts, true),
+ (None, None, None, None, false),
+ (None, backfill_ts, None, None, false),
+ (None, None, backfill_ts, None, false),
+ (Some(CohortType::Static), None, None, None, false),
+ (
+ Some(CohortType::Static),
+ backfill_ts,
+ None,
+ behavioral.clone(),
+ false,
+ ),
+ (Some(CohortType::PersonProperty), None, None, None, false),
+ (
+ Some(CohortType::PersonProperty),
+ backfill_ts,
+ None,
+ behavioral.clone(),
+ false,
+ ),
+ (Some(CohortType::Analytical), None, None, None, false),
+ (
+ Some(CohortType::Analytical),
+ backfill_ts,
+ None,
+ behavioral.clone(),
+ false,
+ ),
+ // Realtime + behavioral condition: either timestamp enables realtime membership
+ (
+ Some(CohortType::Realtime),
+ None,
+ None,
+ behavioral.clone(),
+ false,
+ ),
+ (
+ Some(CohortType::Realtime),
+ backfill_ts,
+ None,
+ behavioral.clone(),
+ true,
+ ),
+ (
+ Some(CohortType::Realtime),
+ None,
+ backfill_ts,
+ behavioral.clone(),
+ true,
+ ),
+ (
+ Some(CohortType::Realtime),
+ backfill_ts,
+ backfill_ts,
+ behavioral.clone(),
+ true,
+ ),
+ // Behavioral + behavioral condition: either timestamp enables realtime membership
+ (
+ Some(CohortType::Behavioral),
+ None,
+ None,
+ behavioral.clone(),
+ false,
+ ),
+ (
+ Some(CohortType::Behavioral),
+ backfill_ts,
+ None,
+ behavioral.clone(),
+ true,
+ ),
+ (
+ Some(CohortType::Behavioral),
+ None,
+ backfill_ts,
+ behavioral.clone(),
+ true,
+ ),
+ (
+ Some(CohortType::Behavioral),
+ backfill_ts,
+ backfill_ts,
+ behavioral.clone(),
+ true,
+ ),
+ // Person-properties-only cohorts never use realtime membership, regardless of
+ // cohort_type or backfill timestamps — there's no behavioral/lifecycle
+ // condition to gain a realtime signal from.
+ (
+ Some(CohortType::Realtime),
+ backfill_ts,
+ None,
+ person_properties_only.clone(),
+ false,
+ ),
+ (
+ Some(CohortType::Realtime),
+ None,
+ backfill_ts,
+ person_properties_only.clone(),
+ false,
+ ),
+ (
+ Some(CohortType::Realtime),
+ backfill_ts,
+ backfill_ts,
+ person_properties_only.clone(),
+ false,
+ ),
+ // Missing condition_type (e.g. a hypercache entry written before this field
+ // existed) defaults to false — the safe choice.
+ (
+ Some(CohortType::Realtime),
+ backfill_ts,
+ backfill_ts,
+ None,
+ false,
+ ),
];
- for (cohort_type, pp_ts, events_ts, expected) in cases {
+ for (cohort_type, pp_ts, events_ts, condition_type, expected) in cases {
let mut cohort = create_test_cohort(None, None, serde_json::json!({}));
cohort.cohort_type = cohort_type;
cohort.last_backfill_person_properties_at = pp_ts;
cohort.last_backfill_events_at = events_ts;
+ cohort.condition_type = condition_type.clone();
assert_eq!(
cohort.uses_realtime_membership(),
expected,
- "cohort_type={cohort_type:?}, pp_ts={}, events_ts={} should return {expected}",
+ "cohort_type={cohort_type:?}, pp_ts={}, events_ts={}, condition_type={condition_type:?} should return {expected}",
pp_ts.is_some(),
events_ts.is_some()
);
@@ -368,27 +510,65 @@ mod tests {
#[test]
fn test_realtime_cohort_filtering_mirrors_flag_matching() {
// Verifies that filtering cohorts by `uses_realtime_membership()` correctly
- // selects only Realtime/Behavioral cohorts with a backfill timestamp, which
- // is the same filter applied in flag_matching::prepare_flag_evaluation_data.
+ // selects only Realtime/Behavioral cohorts with a backfill timestamp AND a
+ // behavioral/lifecycle condition, which is the same filter applied in
+ // flag_matching::prepare_flag_evaluation_data.
let backfill_ts = Some(Utc::now());
-
- let make_cohort = |id: i32, cohort_type: Option<CohortType>, ts: Option<DateTime<Utc>>| {
+ 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),
- make_cohort(2, Some(CohortType::PersonProperty), backfill_ts),
- make_cohort(3, Some(CohortType::Realtime), None), // no backfill
- make_cohort(4, Some(CohortType::Realtime), backfill_ts), // should be selected
- make_cohort(5, Some(CohortType::Behavioral), None), // no backfill
- make_cohort(6, Some(CohortType::Behavioral), backfill_ts), // should be selected
- make_cohort(7, Some(CohortType::Analytical), backfill_ts),
- make_cohort(8, None, backfill_ts),
+ 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
@@ -467,6 +647,7 @@ mod skip_serializing_if_tests {
"created_by_id",
"cohort_type",
"last_backfill_person_properties_at",
+ "condition_type",
] {
assert_absent(&output, key);
}
@@ -487,6 +668,9 @@ mod skip_serializing_if_tests {
created_by_id: Some(9),
cohort_type: Some(CohortType::Behavioral),
last_backfill_person_properties_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()
};
@@ -501,5 +685,6 @@ mod skip_serializing_if_tests {
assert_eq!(output["created_by_id"], 9);
assert_eq!(output["cohort_type"], "behavioral");
assert!(output["last_backfill_person_properties_at"].is_string());
+ assert_eq!(output["condition_type"]["behavioral"], true);
}
}
diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rs
index 072598045bb7..9bc4aa6c3c72 100644
--- a/rust/feature-flags/src/cohorts/cohort_operations.rs
+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs
@@ -28,7 +28,8 @@ const COHORT_COLUMNS: &str = r#"
c.id, c.name, c.description, c.team_id, c.deleted, c.filters,
c.query, c.version, c.pending_version, c.count, c.is_calculating,
c.is_static, c.errors_calculating, c.groups, c.created_by_id,
- c.cohort_type, c.last_backfill_person_properties_at, c.last_backfill_events_at
+ c.cohort_type, c.last_backfill_person_properties_at, c.last_backfill_events_at,
+ c.condition_type
"#;
impl Cohort {
@@ -615,6 +616,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
// This should not fail even though the filters are malformed
@@ -643,6 +645,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
let dependencies = static_cohort_empty_filters.extract_dependencies().unwrap();
@@ -668,6 +671,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
// This should fail because it's dynamic and the filters are malformed
@@ -714,6 +718,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
}
}
@@ -762,6 +767,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
// Create a dynamic cohort (cohort 20) that depends on the static cohort
@@ -797,6 +803,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
let cohorts = vec![static_cohort, dynamic_cohort];
@@ -892,6 +899,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
let cohorts = vec![cohort];
@@ -965,6 +973,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
let cohorts = vec![cohort_with_negation];
@@ -1057,6 +1066,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
}
}
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 24b88c569810..faefcaeceb11 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -392,6 +392,12 @@ pub struct Config {
// if the behavioral cohorts DB is configured and cohorts with CohortType::Realtime
// exist. Set to "all", specific team IDs, or ranges to enable realtime cohort
// membership lookups on the hot path for those teams.
+ //
+ // `Cohort::uses_realtime_membership()` also requires `condition_type` to flag a
+ // behavioral/lifecycle condition. `condition_type` wasn't backfilled when it was added, so
+ // any cohort that hasn't been saved since must be resaved (`python manage.py resave_cohorts
+ // --team-id <id>`) before allowlisting a team here, or its behavioral cohorts will read as
+ // condition_type = NULL and fall back to legacy dynamic evaluation.
#[envconfig(from = "REALTIME_COHORT_EVALUATION_TEAM_IDS", default = "none")]
pub realtime_cohort_evaluation_team_ids: TeamIdCollection,
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index 47ca724ce3da..25135f647037 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -3506,6 +3506,15 @@ mod tests {
}
}
+ /// `condition_type` flags for a cohort with a behavioral condition — required for
+ /// `Cohort::uses_realtime_membership()` to route through the `cohort_membership`
+ /// provider rather than falling back to dynamic filter evaluation.
+ fn behavioral_condition_type() -> serde_json::Value {
+ json!({
+ "person_properties": false, "behavioral": true, "lifecycle": false, "cohorts": false
+ })
+ }
+
/// Cohort filters requiring person property plan == `plan`, used so tests can
/// tell provider-driven results apart from dynamic filter evaluation.
fn plan_cohort_filters(plan: &str) -> serde_json::Value {
@@ -3568,11 +3577,16 @@ mod tests {
));
let team = context.insert_new_team(None).await.unwrap();
- // Realtime cohort with a backfill timestamp, so membership comes from the
- // provider. Its filters require plan=enterprise, which the person does NOT
- // satisfy — a match can only come from the provider.
+ // Realtime cohort with a backfill timestamp and a behavioral condition_type, so
+ // membership comes from the provider (uses_realtime_membership() requires all
+ // three). Its filters require plan=enterprise, which the person does NOT
+ // satisfy — a match can only come from the provider. The filters themselves are
+ // person-property (not actually behavioral) purely so this test can tell a
+ // provider-driven result apart from dynamic filter evaluation; condition_type is
+ // set directly since this test is exercising the matcher's provider routing, not
+ // condition_type derivation (covered separately in cohort_models.rs tests).
let cohort = context
- .insert_cohort_with_type(
+ .insert_cohort_with_type_and_condition_type(
team.id,
Some("Realtime Cohort".to_string()),
plan_cohort_filters("enterprise"),
@@ -3580,6 +3594,7 @@ mod tests {
Some(CohortType::Realtime),
Some(Utc::now()),
None,
+ Some(behavioral_condition_type()),
)
.await
.unwrap();
@@ -3634,8 +3649,10 @@ mod tests {
// The person DOES satisfy the cohort's filters (plan=enterprise), so if a
// provider failure wrongly fell through to dynamic evaluation the flag
// would match. Graceful degradation must treat the person as a non-member.
+ // condition_type is set directly (see comment in the sibling test above) so this
+ // cohort qualifies for uses_realtime_membership() and routes through the provider.
let cohort = context
- .insert_cohort_with_type(
+ .insert_cohort_with_type_and_condition_type(
team.id,
Some("Realtime Cohort Degraded".to_string()),
plan_cohort_filters("enterprise"),
@@ -3643,6 +3660,7 @@ mod tests {
Some(CohortType::Realtime),
Some(Utc::now()),
None,
+ Some(behavioral_condition_type()),
)
.await
.unwrap();
diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rs
index 44436cfbe83b..51485360f2c2 100644
--- a/rust/feature-flags/src/utils/mock.rs
+++ b/rust/feature-flags/src/utils/mock.rs
@@ -417,6 +417,7 @@ mod tests {
cohort_type: None,
last_backfill_person_properties_at: None,
last_backfill_events_at: None,
+ condition_type: None,
};
let mock_cohort = mock!(Cohort,
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index b58b94c254f7..211d136dfa20 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -820,6 +820,7 @@ pub async fn insert_cohort_for_team_in_pg(
cohort_type: Option<CohortType>,
last_backfill_person_properties_at: Option<DateTime<Utc>>,
last_backfill_events_at: Option<DateTime<Utc>>,
+ condition_type: Option<serde_json::Value>,
) -> Result<Cohort, Error> {
let cohort = Cohort {
id: 0, // Placeholder, will be updated after insertion
@@ -840,13 +841,14 @@ pub async fn insert_cohort_for_team_in_pg(
cohort_type,
last_backfill_person_properties_at,
last_backfill_events_at,
+ condition_type,
};
let mut conn = client.get_connection().await?;
let row: (i32,) = sqlx::query_as(
r#"INSERT INTO posthog_cohort
- (name, description, team_id, deleted, filters, query, version, pending_version, count, is_calculating, is_static, errors_calculating, groups, created_by_id, cohort_type, last_backfill_person_properties_at, last_backfill_events_at) VALUES
- ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
+ (name, description, team_id, deleted, filters, query, version, pending_version, count, is_calculating, is_static, errors_calculating, groups, created_by_id, cohort_type, last_backfill_person_properties_at, last_backfill_events_at, condition_type) VALUES
+ ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
RETURNING id"#,
)
.bind(&cohort.name)
@@ -866,6 +868,7 @@ pub async fn insert_cohort_for_team_in_pg(
.bind(cohort.cohort_type)
.bind(cohort.last_backfill_person_properties_at)
.bind(cohort.last_backfill_events_at)
+ .bind(&cohort.condition_type)
.fetch_one(&mut *conn)
.await?;
@@ -1284,6 +1287,7 @@ impl TestContext {
None,
None,
None,
+ None,
)
.await
}
@@ -1308,6 +1312,37 @@ impl TestContext {
cohort_type,
last_backfill_person_properties_at,
last_backfill_events_at,
+ None,
+ )
+ .await
+ }
+
+ /// Like `insert_cohort_with_type`, but also sets `condition_type` — needed by tests that
+ /// exercise the realtime `cohort_membership` provider path, since
+ /// `Cohort::uses_realtime_membership()` requires a behavioral/lifecycle condition in
+ /// addition to `cohort_type` and a backfill timestamp.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn insert_cohort_with_type_and_condition_type(
+ &self,
+ team_id: i32,
+ name: Option<String>,
+ filters: serde_json::Value,
+ is_static: bool,
+ cohort_type: Option<CohortType>,
+ last_backfill_person_properties_at: Option<DateTime<Utc>>,
+ last_backfill_events_at: Option<DateTime<Utc>>,
+ condition_type: Option<serde_json::Value>,
+ ) -> Result<Cohort, Error> {
+ insert_cohort_for_team_in_pg(
+ self.non_persons_writer.clone(),
+ team_id,
+ name,
+ filters,
+ is_static,
+ cohort_type,
+ last_backfill_person_properties_at,
+ last_backfill_events_at,
+ condition_type,
)
.await
}
diff --git a/rust/feature-flags/tests/fixtures/hypercache_contract.json b/rust/feature-flags/tests/fixtures/hypercache_contract.json
index 95fe26117c8e..3934be21a6d4 100644
--- a/rust/feature-flags/tests/fixtures/hypercache_contract.json
+++ b/rust/feature-flags/tests/fixtures/hypercache_contract.json
@@ -213,6 +213,12 @@
"groups": [],
"created_by_id": 1,
"cohort_type": null,
+ "condition_type": {
+ "person_properties": true,
+ "behavioral": false,
+ "lifecycle": false,
+ "cohorts": false
+ },
"last_backfill_person_properties_at": "2024-01-15T12:00:00+00:00",
"last_backfill_events_at": "2024-01-15T12:00:00+00:00"
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8a02f8f8ba18..835468dc8dfc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13983,6 +13983,17 @@ export namespace Schemas {
Analytical: 'analytical',
} as const;
+ export interface CohortConditionTypeFlags {
+ /** The filters include a person property or person_metadata condition. */
+ person_properties: boolean;
+ /** The filters include a behavioral condition that is not lifecycle-style (e.g. performed_event, performed_event_multiple, performed_event_sequence, or their negations). */
+ behavioral: boolean;
+ /** The filters include a lifecycle-style behavioral condition (first-seen/regularly/stopped/restarted performing an event). */
+ lifecycle: boolean;
+ /** The filters include a nested reference to another cohort. */
+ cohorts: boolean;
+ }
+
export interface Cohort {
readonly id: number;
/**
@@ -14022,6 +14033,8 @@ export namespace Schemas {
* * `realtime` - realtime
* * `analytical` - analytical */
cohort_type?: CohortTypeEnum | BlankEnum | null;
+ /** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
+ readonly condition_type: CohortConditionTypeFlags | null;
readonly experiment_set: readonly number[];
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnum | null;
@@ -41112,6 +41125,8 @@ export namespace Schemas {
* * `realtime` - realtime
* * `analytical` - analytical */
cohort_type?: CohortTypeEnum | BlankEnum | null;
+ /** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
+ readonly condition_type?: CohortConditionTypeFlags | null;
readonly experiment_set?: readonly number[];
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnum | null;