:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): add last_backfill_events_at field and integrate with flag compatibility (#54124)
Dylan Martin505ccb5debb7
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 0b7d58f11260..cfba120dd7cf 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -1838,6 +1838,7 @@ [email protected],filters={"properties": {"type": "OR", "values": values}},cohort_type=CohortType.REALTIME if realtime_backfilled else None,last_backfill_person_properties_at=timezone.now() if realtime_backfilled else None,+ last_backfill_events_at=timezone.now() if realtime_backfilled else None,)cohorts = {@@ -2064,6 +2065,7 @@ [email protected],},cohort_type=cohort_type,last_backfill_person_properties_at=datetime.now() if is_backfilled else None,+ last_backfill_events_at=datetime.now() if is_backfilled else None,)regular_cohort = Cohort.objects.create(@@ -2119,6 +2121,7 @@ [email protected],},cohort_type=CohortType.REALTIME,last_backfill_person_properties_at=datetime.now(),+ last_backfill_events_at=datetime.now(),)# Parent: non-behavioral cohort that references the leafdiff --git a/posthog/models/filters/test/__snapshots__/test_filter.ambr b/posthog/models/filters/test/__snapshots__/test_filter.ambrindex 89a654449c4d..c294bc32c7b2 100644--- a/posthog/models/filters/test/__snapshots__/test_filter.ambr+++ b/posthog/models/filters/test/__snapshots__/test_filter.ambr@@ -44,6 +44,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -103,6 +104,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -237,6 +239,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -271,6 +274,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -305,6 +309,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -339,6 +344,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",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.ambrindex 979eca9dda5b..51eaafcdaa82 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@@ -151,6 +151,7 @@'filters','is_static','kind',+ 'last_backfill_events_at','last_backfill_person_properties_at','last_calculation_duration_ms','last_realtime_cohort_calculation_at',@@ -489,6 +490,7 @@'__str__','_get_existing_ch_member_uuids','_get_uuids_for_emails_batch_ch',+ '_has_filter_type','_insert_batch_via_personhog','_insert_users_list_with_batching','_meta',diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.pyindex ac9bd34601a5..84b916a54920 100644--- a/posthog/test/test_cohort_model.py+++ b/posthog/test/test_cohort_model.py@@ -1,4 +1,5 @@import uuid+from datetime import UTC, datetimeimport pytestfrom posthog.test.base import BaseTest@@ -14,7 +15,7 @@ from posthog.models import Person, Teamfrom posthog.models.person.util import get_person_by_idfrom posthog.test.persons import add_cohort_members, create_person-from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_IDfrom products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_idsfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -603,3 +604,98 @@ class TestCohort(BaseTest):cohort.refresh_from_db()self.assertEqual(cohort.version, 1)self.assertEqual(cohort.count, 42)+++_PERSON_FILTERS = {+ "properties": {+ "type": "AND",+ "values": [{"type": "AND", "values": [{"key": "email", "value": "[email protected]", "type": "person"}]}],+ }+}++_BEHAVIORAL_FILTERS = {+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {"type": "behavioral", "value": "performed_event", "event_type": "events", "key": "$pageview"}+ ],+ }+ ],+ }+}++_MIXED_FILTERS = {+ "properties": {+ "type": "AND",+ "values": [+ {"type": "AND", "values": [{"key": "email", "value": "[email protected]", "type": "person"}]},+ {+ "type": "AND",+ "values": [+ {"type": "behavioral", "value": "performed_event", "event_type": "events", "key": "$pageview"}+ ],+ },+ ],+ }+}++_COHORT_REF_FILTERS = {+ "properties": {+ "type": "AND",+ "values": [{"type": "AND", "values": [{"key": "id", "value": 1, "type": "cohort"}]}],+ }+}++_FIXED_TS = datetime(2026, 1, 1, tzinfo=UTC)+++class TestCohortIsFlagCompatible(BaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ @parameterized.expand(+ [+ # (label, cohort_type, filters, person_ts, events_ts, expected)+ # Non-realtime cohort types are never flag-compatible+ ("static_never_compatible", CohortType.STATIC, _PERSON_FILTERS, _FIXED_TS, _FIXED_TS, False),+ ("behavioral_type_never_compatible", CohortType.BEHAVIORAL, _PERSON_FILTERS, _FIXED_TS, _FIXED_TS, False),+ (+ "person_property_type_never_compatible",+ CohortType.PERSON_PROPERTY,+ _PERSON_FILTERS,+ _FIXED_TS,+ None,+ False,+ ),+ # Realtime + person filters: gate on person timestamp+ ("realtime_person_no_ts", CohortType.REALTIME, _PERSON_FILTERS, None, None, False),+ ("realtime_person_only_person_ts", CohortType.REALTIME, _PERSON_FILTERS, _FIXED_TS, None, True),+ ("realtime_person_only_events_ts", CohortType.REALTIME, _PERSON_FILTERS, None, _FIXED_TS, False),+ ("realtime_person_both_ts", CohortType.REALTIME, _PERSON_FILTERS, _FIXED_TS, _FIXED_TS, True),+ # Realtime + behavioral filters: gate on events timestamp+ ("realtime_behavioral_no_ts", CohortType.REALTIME, _BEHAVIORAL_FILTERS, None, None, False),+ ("realtime_behavioral_only_person_ts", CohortType.REALTIME, _BEHAVIORAL_FILTERS, _FIXED_TS, None, False),+ ("realtime_behavioral_only_events_ts", CohortType.REALTIME, _BEHAVIORAL_FILTERS, None, _FIXED_TS, True),+ ("realtime_behavioral_both_ts", CohortType.REALTIME, _BEHAVIORAL_FILTERS, _FIXED_TS, _FIXED_TS, True),+ # Realtime + mixed filters: require both timestamps+ ("realtime_mixed_no_ts", CohortType.REALTIME, _MIXED_FILTERS, None, None, False),+ ("realtime_mixed_only_person_ts", CohortType.REALTIME, _MIXED_FILTERS, _FIXED_TS, None, False),+ ("realtime_mixed_only_events_ts", CohortType.REALTIME, _MIXED_FILTERS, None, _FIXED_TS, False),+ ("realtime_mixed_both_ts", CohortType.REALTIME, _MIXED_FILTERS, _FIXED_TS, _FIXED_TS, True),+ # Realtime + no recognized filter types: never compatible, regardless of timestamps+ ("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),+ ]+ )+ def test_is_flag_compatible(self, _label, cohort_type, filters, person_ts, events_ts, expected):+ cohort = Cohort.objects.create(+ team=self.team,+ filters=filters,+ cohort_type=cohort_type,+ last_backfill_person_properties_at=person_ts,+ last_backfill_events_at=events_ts,+ )+ self.assertEqual(cohort.is_flag_compatible, expected)diff --git a/products/cohorts/backend/migrations/0002_cohort_last_backfill_events_at.py b/products/cohorts/backend/migrations/0002_cohort_last_backfill_events_at.pynew file mode 100644index 000000000000..cdfb0706144e--- /dev/null+++ b/products/cohorts/backend/migrations/0002_cohort_last_backfill_events_at.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0001_migrate_cohorts_models"),+ ]++ operations = [+ migrations.AddField(+ model_name="cohort",+ name="last_backfill_events_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txtindex 6c080bdd9533..95693715736a 100644--- a/products/cohorts/backend/migrations/max_migration.txt+++ b/products/cohorts/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_migrate_cohorts_models+0002_cohort_last_backfill_events_atdiff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 6b58e249c19c..8de2a0c60978 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -199,6 +199,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):errors_calculating = models.IntegerField(default=0)last_error_at = models.DateTimeField(blank=True, null=True)last_backfill_person_properties_at = models.DateTimeField(blank=True, null=True)+ last_backfill_events_at = models.DateTimeField(blank=True, null=True)last_realtime_cohort_calculation_at = models.DateTimeField(blank=True, null=True)is_static = models.BooleanField(default=False)@@ -261,10 +262,51 @@ 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")+ if not properties:+ return False++ def _check(node) -> bool:+ if not isinstance(node, dict):+ return False+ 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++ return _check(properties)+@propertydef is_flag_compatible(self) -> bool:- """Whether this cohort can be used in feature flag targeting via cohort_membership lookups."""- return self.cohort_type == CohortType.REALTIME and self.last_backfill_person_properties_at is not None+ """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 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.)+ are not flag-compatible, even if stale timestamps are set, because HogQLRealtimeCohortQuery+ cannot evaluate them.+ """+ if self.cohort_type != CohortType.REALTIME:+ return False++ has_person_filters = self._has_filter_type("person")+ has_behavioral_filters = self._has_filter_type("behavioral")++ if not (has_person_filters or has_behavioral_filters):+ return False++ if has_person_filters and self.last_backfill_person_properties_at is None:+ return False+ if has_behavioral_filters and self.last_backfill_events_at is None:+ return False++ return True@propertydef properties(self) -> PropertyGroup:diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.pyindex c135263ff212..67e8f5d25f12 100644--- a/products/cohorts/backend/models/dependencies.py+++ b/products/cohorts/backend/models/dependencies.py@@ -143,7 +143,14 @@ def _compute_flag_excluded_behavioral_cohort_ids(team_id: int, *, allow_realtimeCohort.objects.filter(team_id=team_id, deleted=False, is_static=False).annotate(_filters_text=Cast("filters", output_field=TextField())).filter(Q(_filters_text__icontains="behavioral") | Q(_filters_text__icontains="cohort"))- .only("id", "is_static", "filters", "cohort_type", "last_backfill_person_properties_at")+ .only(+ "id",+ "is_static",+ "filters",+ "cohort_type",+ "last_backfill_person_properties_at",+ "last_backfill_events_at",+ ))all_cohorts = {cohort.id: cohort for cohort in graph_source}return find_behavioral_cohorts(all_cohorts, allow_realtime_backfilled=allow_realtime_backfilled)diff --git a/products/cohorts/backend/models/test/test_dependencies.py b/products/cohorts/backend/models/test/test_dependencies.pyindex 51d30f769ba2..b317c02c94e3 100644--- a/products/cohorts/backend/models/test/test_dependencies.py+++ b/products/cohorts/backend/models/test/test_dependencies.py@@ -1372,6 +1372,7 @@ class TestFlagExcludedBehavioralCohortIds(BaseTest):cohort_type=CohortType.REALTIME,filters=self.BEHAVIORAL_FILTERS,last_backfill_person_properties_at=timezone.now(),+ last_backfill_events_at=timezone.now(),)excluded_without = get_flag_excluded_behavioral_cohort_ids(self.team.id, allow_realtime_backfilled=False)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.ambrindex d0a4e7ce86c9..9d181fbafa7d 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@@ -764,6 +764,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -1133,6 +1134,7 @@"posthog_cohort"."errors_calculating","posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at",+ "posthog_cohort"."last_backfill_events_at","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex d385544cf942..79409e2d7aae 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -5526,6 +5526,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):cohort_kwargs["cohort_type"] = cohort_typeif is_backfilled:cohort_kwargs["last_backfill_person_properties_at"] = datetime.now(tz=UTC)+ cohort_kwargs["last_backfill_events_at"] = datetime.now(tz=UTC)cohort = Cohort.objects.create(**cohort_kwargs)diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 4b5c1fdb2718..955ec0c9de33 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -233,6 +233,9 @@ def _serialize_cohort(cohort: Cohort) -> dict[str, Any]:"last_backfill_person_properties_at": (cohort.last_backfill_person_properties_at.isoformat() if cohort.last_backfill_person_properties_at else None),+ "last_backfill_events_at": (+ cohort.last_backfill_events_at.isoformat() if cohort.last_backfill_events_at else None+ ),}diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex d803ed96b05a..068e6e11dc55 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -1160,6 +1160,7 @@ class TestServiceFlagsDataFormat(BaseTest):}},last_backfill_person_properties_at=datetime(2024, 1, 15, 12, 0, 0, tzinfo=UTC),+ last_backfill_events_at=datetime(2024, 1, 15, 12, 0, 0, tzinfo=UTC),)# 1) full-flag: exercises all optional nested structures.@@ -3635,7 +3636,7 @@ class TestSerializeCohort(BaseTest):)result = _serialize_cohort(cohort)- # Hypercache/service cohort schema: these 17 fields must always be present in the serialized payload+ # Hypercache/service cohort schema: these 18 fields must always be present in the serialized payloadexpected_fields = {"id","name",@@ -3654,6 +3655,7 @@ class TestSerializeCohort(BaseTest):"created_by_id","cohort_type","last_backfill_person_properties_at",+ "last_backfill_events_at",}assert set(result.keys()) == expected_fieldsassert result["id"] == cohort.iddiff --git a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs b/rust/feature-flags/src/cohorts/cohort_cache_manager.rsindex a80e3fb056a5..04f84e540fab 100644--- a/rust/feature-flags/src/cohorts/cohort_cache_manager.rs+++ b/rust/feature-flags/src/cohorts/cohort_cache_manager.rs@@ -270,6 +270,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,}}@@ -765,6 +766,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};cohort_cache.cache.insert(1, vec![test_cohort]).await;// Moka caches update internal stats lazily - sync ensures stats are current@@ -1131,6 +1133,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,}])}}diff --git a/rust/feature-flags/src/cohorts/cohort_models.rs b/rust/feature-flags/src/cohorts/cohort_models.rsindex 56c419aac685..caa044ec573a 100644--- a/rust/feature-flags/src/cohorts/cohort_models.rs+++ b/rust/feature-flags/src/cohorts/cohort_models.rs@@ -48,19 +48,27 @@ pub struct Cohort {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>>,}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 a populated backfill- /// timestamp, which indicates that the membership table has been written to.- /// Without the timestamp, the cohort falls through to dynamic filter evaluation.+ /// 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.+ ///+ /// 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+ /// cohort at all. Here we only need to know that the membership table has been+ /// populated, so accepting either timestamp is sufficient.pub fn uses_realtime_membership(&self) -> bool {matches!(self.cohort_type,Some(CohortType::Realtime) | Some(CohortType::Behavioral)- ) && self.last_backfill_person_properties_at.is_some()+ ) && (self.last_backfill_person_properties_at.is_some()+ || self.last_backfill_events_at.is_some())}/// Estimates the memory size of this cohort in bytes.@@ -184,6 +192,7 @@ mod tests {created_by_id: Some(1),cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,}}@@ -309,33 +318,49 @@ mod tests {}#[test]+ #[allow(clippy::type_complexity)]fn test_uses_realtime_membership() {let backfill_ts = Some(Utc::now());- let cases: Vec<(Option<CohortType>, Option<DateTime<Utc>>, bool)> = vec![- (None, None, false),- (None, backfill_ts, false),- (Some(CohortType::Static), None, false),- (Some(CohortType::Static), backfill_ts, false),- (Some(CohortType::PersonProperty), None, false),- (Some(CohortType::PersonProperty), backfill_ts, false),- (Some(CohortType::Analytical), None, false),- (Some(CohortType::Analytical), backfill_ts, false),- (Some(CohortType::Realtime), None, false),- (Some(CohortType::Realtime), backfill_ts, true),- (Some(CohortType::Behavioral), None, false),- (Some(CohortType::Behavioral), backfill_ts, true),+ // (cohort_type, person_props_ts, events_ts, expected)+ let cases: Vec<(+ Option<CohortType>,+ Option<DateTime<Utc>>,+ Option<DateTime<Utc>>,+ 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),];- for (cohort_type, ts, expected) in cases {+ for (cohort_type, pp_ts, events_ts, 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 = ts;+ cohort.last_backfill_person_properties_at = pp_ts;+ cohort.last_backfill_events_at = events_ts;assert_eq!(cohort.uses_realtime_membership(),expected,- "cohort_type={cohort_type:?}, backfill_ts={} should return {expected}",- ts.is_some()+ "cohort_type={cohort_type:?}, pp_ts={}, events_ts={} should return {expected}",+ pp_ts.is_some(),+ events_ts.is_some());}}diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rsindex e5f5d1da0e6c..072598045bb7 100644--- a/rust/feature-flags/src/cohorts/cohort_operations.rs+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs@@ -28,7 +28,7 @@ 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.cohort_type, c.last_backfill_person_properties_at, c.last_backfill_events_at"#;impl Cohort {@@ -614,6 +614,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};// This should not fail even though the filters are malformed@@ -641,6 +642,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};let dependencies = static_cohort_empty_filters.extract_dependencies().unwrap();@@ -665,6 +667,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};// This should fail because it's dynamic and the filters are malformed@@ -710,6 +713,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,}}@@ -757,6 +761,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};// Create a dynamic cohort (cohort 20) that depends on the static cohort@@ -791,6 +796,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};let cohorts = vec![static_cohort, dynamic_cohort];@@ -885,6 +891,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};let cohorts = vec![cohort];@@ -957,6 +964,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,};let cohorts = vec![cohort_with_negation];@@ -1048,6 +1056,7 @@ mod tests {created_by_id: None,cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: None,}}diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rsindex 321b7bcc82eb..44436cfbe83b 100644--- a/rust/feature-flags/src/utils/mock.rs+++ b/rust/feature-flags/src/utils/mock.rs@@ -416,6 +416,7 @@ mod tests {created_by_id: Some(1),cohort_type: None,last_backfill_person_properties_at: None,+ last_backfill_events_at: 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.rsindex efbf583782c6..b58b94c254f7 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -810,6 +810,7 @@ pub async fn insert_person_for_team_in_pg(Ok(person_id)}+#[allow(clippy::too_many_arguments)]pub async fn insert_cohort_for_team_in_pg(client: Arc<dyn Client + Send + Sync>,team_id: i32,@@ -818,6 +819,7 @@ pub async fn insert_cohort_for_team_in_pg(is_static: bool,cohort_type: Option<CohortType>,last_backfill_person_properties_at: Option<DateTime<Utc>>,+ last_backfill_events_at: Option<DateTime<Utc>>,) -> Result<Cohort, Error> {let cohort = Cohort {id: 0, // Placeholder, will be updated after insertion@@ -837,13 +839,14 @@ pub async fn insert_cohort_for_team_in_pg(created_by_id: None,cohort_type,last_backfill_person_properties_at,+ last_backfill_events_at,};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) VALUES- ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)+ (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)RETURNING id"#,).bind(&cohort.name)@@ -862,6 +865,7 @@ pub async fn insert_cohort_for_team_in_pg(.bind(cohort.created_by_id).bind(cohort.cohort_type).bind(cohort.last_backfill_person_properties_at)+ .bind(cohort.last_backfill_events_at).fetch_one(&mut *conn).await?;@@ -1279,10 +1283,12 @@ impl TestContext {is_static,None,None,+ None,).await}+ #[allow(clippy::too_many_arguments)]pub async fn insert_cohort_with_type(&self,team_id: i32,@@ -1291,6 +1297,7 @@ impl TestContext {is_static: bool,cohort_type: Option<CohortType>,last_backfill_person_properties_at: Option<DateTime<Utc>>,+ last_backfill_events_at: Option<DateTime<Utc>>,) -> Result<Cohort, Error> {insert_cohort_for_team_in_pg(self.non_persons_writer.clone(),@@ -1300,6 +1307,7 @@ impl TestContext {is_static,cohort_type,last_backfill_person_properties_at,+ last_backfill_events_at,).await}diff --git a/rust/feature-flags/tests/fixtures/hypercache_contract.json b/rust/feature-flags/tests/fixtures/hypercache_contract.jsonindex 10988b1c97d0..95fe26117c8e 100644--- a/rust/feature-flags/tests/fixtures/hypercache_contract.json+++ b/rust/feature-flags/tests/fixtures/hypercache_contract.json@@ -213,7 +213,8 @@"groups": [],"created_by_id": 1,"cohort_type": null,- "last_backfill_person_properties_at": "2024-01-15T12:00:00+00:00"+ "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/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex a6fd2cbb39c4..95d2395bdaf6 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -6199,6 +6199,7 @@ async fn test_realtime_cohort_without_backfill_falls_through_to_dynamic_eval() -false,Some(CohortType::Realtime),None, // no backfill timestamp+ None, // no events backfill timestamp).await.unwrap();